branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>package com.rgfp.psd.logbook.domain;
import org.junit.Test;
import java.time.LocalDateTime;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class NoteTest {
// your tests here
@Test
public void itShouldRetornFifteenCharacters (){
String fifteenCharacters;
Note note = new Note();
note.setContent("wertyuiopasdfgh");
fifteenCharacters = note.getSummary();
assertEquals(15,fifteenCharacters.length());
}
@Test
public void itShouldShowPhrase(){
String fifteenCharacters;
Note note = new Note();
note.setContent("wertyuiopasdfgh");
fifteenCharacters = note.getSummary();
assertEquals("wertyuiopasdfgh",fifteenCharacters);
}
@Test
public void itShouldSubstringPhraseFifteenCharacters(){
String fifteenCharacters;
Note note = new Note();
note.setContent("asdfghjklzxcvbnm");
fifteenCharacters = note.getSummary();
assertEquals("asdfghjklzxcvbn",fifteenCharacters);
}
@Test
public void itShouldShowPhraseLessFifteenCharacters(){
String fifteenCharacters;
Note note = new Note();
note.setContent("asdfghjk");
fifteenCharacters = note.getSummary();
assertEquals("asdfghjk",fifteenCharacters);
}
@Test
public void itShouldExecuteCloneMethod (){
Note note = new Note();
note.setTitle("Prueba");
note.setContent("Esta es una prueba");
note.clone();
}
@Test
public void itShouldECloneNoteWithTheSameTitleAndSameContent (){
LocalDateTime hoy = LocalDateTime.now().minusDays(1);
Note noteClone = new Note();
Note note = new Note();
note.setTitle("Prueba");
note.setContent("Esta es una prueba");
note.setTimestamp(hoy);
noteClone = note.clone();
assertEquals(noteClone.getTitle(), note.getTitle());
assertEquals(noteClone.getContent(), note.getContent());
assertTrue(noteClone.getTimestamp().isAfter(hoy) );
}
/* @Test
public void itShouldCloneNote(){
Note note = new Note();
note.setContent("Prueba de contenido");
note.setTitle("Prueba");
note.setTimestamp(LocalDateTime.now());
List<Note> noteList = new ArrayList<>();
noteList.add(note);
int countNotesBefore = noteList.size();
note.clone(note.getId());
int countNotesAfter = noteList.size();
assertEquals(countNotesBefore+1,countNotesAfter);
//assertTrue((countNotesBefore + 1 == countNotesAfter));
}*/
}<file_sep>rootProject.name = 'is-logbook-app'
| f2845c475c461f2506408ecb90a9254d3416874d | [
"Java",
"Gradle"
] | 2 | Java | ijsilva83/logbook-app | 2912f2e6a1761e50d908029ae00e32ff22bf2080 | 52fefcc77f2ed0b8a3680b38ad3eece448b2a590 |
refs/heads/master | <file_sep>SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';
DROP SCHEMA IF EXISTS `bd_contensavel` ;
CREATE SCHEMA IF NOT EXISTS `bd_contensavel` DEFAULT CHARACTER SET latin1 ;
USE `bd_contensavel` ;
-- -----------------------------------------------------
-- Table `bd_contensavel`.`filiais`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `bd_contensavel`.`filiais` ;
CREATE TABLE IF NOT EXISTS `bd_contensavel`.`filiais` (
`cod_filial` INT(11) NOT NULL AUTO_INCREMENT ,
`razao_social` VARCHAR(45) NULL DEFAULT NULL ,
`cnpj` INT(11) NULL DEFAULT NULL ,
`rua` VARCHAR(45) NULL DEFAULT NULL ,
`bairro` VARCHAR(45) NULL DEFAULT NULL ,
`cidade` VARCHAR(45) NULL DEFAULT NULL ,
`estado` VARCHAR(45) NULL DEFAULT NULL ,
`cep` INT(11) NULL DEFAULT NULL ,
PRIMARY KEY (`cod_filial`) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `bd_contensavel`.`funcoes`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `bd_contensavel`.`funcoes` ;
CREATE TABLE IF NOT EXISTS `bd_contensavel`.`funcoes` (
`cod_funcao` INT(11) NOT NULL AUTO_INCREMENT ,
`funcao` VARCHAR(45) NULL DEFAULT NULL ,
PRIMARY KEY (`cod_funcao`) )
ENGINE = InnoDB
AUTO_INCREMENT = 2
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `bd_contensavel`.`funcionarios`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `bd_contensavel`.`funcionarios` ;
CREATE TABLE IF NOT EXISTS `bd_contensavel`.`funcionarios` (
`cod_funcionario` INT(11) NOT NULL AUTO_INCREMENT ,
`cod_funcao` INT(11) NOT NULL ,
`matricula` INT(11) NULL DEFAULT NULL ,
`nome` VARCHAR(45) NULL DEFAULT NULL ,
`rua` VARCHAR(45) NULL DEFAULT NULL ,
`bairro` VARCHAR(45) NULL DEFAULT NULL ,
`cidade` VARCHAR(45) NULL DEFAULT NULL ,
`estado` VARCHAR(45) NULL DEFAULT NULL ,
`cep` INT(11) NULL DEFAULT NULL ,
`cpf` INT(11) NULL DEFAULT NULL ,
PRIMARY KEY (`cod_funcionario`) ,
INDEX `FK_funcionarios_funcoes1` (`cod_funcao` ASC) ,
CONSTRAINT `FK_funcionarios_funcoes1`
FOREIGN KEY (`cod_funcao` )
REFERENCES `bd_contensavel`.`funcoes` (`cod_funcao` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `bd_contensavel`.`ordens`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `bd_contensavel`.`ordens` ;
CREATE TABLE IF NOT EXISTS `bd_contensavel`.`ordens` (
`cod_ordem` INT(11) NOT NULL AUTO_INCREMENT ,
`cod_filial` INT(11) NOT NULL ,
`cod_funcionario` INT(11) NOT NULL ,
`tipo_ordem` VARCHAR(45) NOT NULL ,
`num_carro` INT(11) NULL DEFAULT NULL ,
`km` INT(11) NULL DEFAULT NULL ,
`horario` TIME NULL DEFAULT NULL ,
`data_lanc` DATE NULL DEFAULT NULL ,
`origem` VARCHAR(80) NOT NULL ,
`destino` VARCHAR(80) NOT NULL ,
PRIMARY KEY (`cod_ordem`) ,
INDEX `FK_ordens_filiais` (`cod_filial` ASC) ,
INDEX `FK_ordens_funcionarios1` (`cod_funcionario` ASC) ,
CONSTRAINT `FK_ordens_filiais`
FOREIGN KEY (`cod_filial` )
REFERENCES `bd_contensavel`.`filiais` (`cod_filial` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `FK_ordens_funcionarios1`
FOREIGN KEY (`cod_funcionario` )
REFERENCES `bd_contensavel`.`funcionarios` (`cod_funcionario` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package projeto_contensavel;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
*
* @author renata
*/
@Entity
@Table(name = "funcionarios", catalog = "bd_contensavel", schema = "")
@NamedQueries({
@NamedQuery(name = "Funcionarios.findAll", query = "SELECT f FROM Funcionarios f"),
@NamedQuery(name = "Funcionarios.findByCodFuncionario", query = "SELECT f FROM Funcionarios f WHERE f.codFuncionario = :codFuncionario"),
@NamedQuery(name = "Funcionarios.findByCodFuncao", query = "SELECT f FROM Funcionarios f WHERE f.codFuncao = :codFuncao"),
@NamedQuery(name = "Funcionarios.findByMatricula", query = "SELECT f FROM Funcionarios f WHERE f.matricula = :matricula"),
@NamedQuery(name = "Funcionarios.findByNome", query = "SELECT f FROM Funcionarios f WHERE f.nome = :nome"),
@NamedQuery(name = "Funcionarios.findByRua", query = "SELECT f FROM Funcionarios f WHERE f.rua = :rua"),
@NamedQuery(name = "Funcionarios.findByBairro", query = "SELECT f FROM Funcionarios f WHERE f.bairro = :bairro"),
@NamedQuery(name = "Funcionarios.findByCidade", query = "SELECT f FROM Funcionarios f WHERE f.cidade = :cidade"),
@NamedQuery(name = "Funcionarios.findByEstado", query = "SELECT f FROM Funcionarios f WHERE f.estado = :estado"),
@NamedQuery(name = "Funcionarios.findByCep", query = "SELECT f FROM Funcionarios f WHERE f.cep = :cep"),
@NamedQuery(name = "Funcionarios.findByCpf", query = "SELECT f FROM Funcionarios f WHERE f.cpf = :cpf")})
public class Funcionarios implements Serializable {
@Transient
private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "cod_funcionario")
private Integer codFuncionario;
@JoinColumn(name="cod_funcao",referencedColumnName="cod_funcao")
@ManyToOne(optional = false)
private Funcoes codFuncao;
@Column(name = "matricula")
private Integer matricula;
@Column(name = "nome")
private String nome;
@Column(name = "rua")
private String rua;
@Column(name = "bairro")
private String bairro;
@Column(name = "cidade")
private String cidade;
@Column(name = "estado")
private String estado;
@Column(name = "cep")
private Integer cep;
@Column(name = "cpf")
private Integer cpf;
@OneToMany(mappedBy = "codFuncionario")
private List<Ordens> ordensList;
public Funcionarios() {
}
public Funcionarios(Integer codFuncionario) {
this.codFuncionario = codFuncionario;
}
public Funcionarios(Integer codFuncionario, Funcoes codFuncao) {
this.codFuncionario = codFuncionario;
this.codFuncao = codFuncao;
}
public Integer getCodFuncionario() {
return codFuncionario;
}
public void setCodFuncionario(Integer codFuncionario) {
Integer oldCodFuncionario = this.codFuncionario;
this.codFuncionario = codFuncionario;
changeSupport.firePropertyChange("codFuncionario", oldCodFuncionario, codFuncionario);
}
public Funcoes getCodFuncao() {
return codFuncao;
}
public void setCodFuncao(Funcoes codFuncao) {
Funcoes oldCodFuncao = this.codFuncao;
this.codFuncao = codFuncao;
changeSupport.firePropertyChange("codFuncao", oldCodFuncao, codFuncao);
}
public Integer getMatricula() {
return matricula;
}
public void setMatricula(Integer matricula) {
Integer oldMatricula = this.matricula;
this.matricula = matricula;
changeSupport.firePropertyChange("matricula", oldMatricula, matricula);
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
String oldNome = this.nome;
this.nome = nome;
changeSupport.firePropertyChange("nome", oldNome, nome);
}
public String getRua() {
return rua;
}
public void setRua(String rua) {
String oldRua = this.rua;
this.rua = rua;
changeSupport.firePropertyChange("rua", oldRua, rua);
}
public String getBairro() {
return bairro;
}
public void setBairro(String bairro) {
String oldBairro = this.bairro;
this.bairro = bairro;
changeSupport.firePropertyChange("bairro", oldBairro, bairro);
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
String oldCidade = this.cidade;
this.cidade = cidade;
changeSupport.firePropertyChange("cidade", oldCidade, cidade);
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
String oldEstado = this.estado;
this.estado = estado;
changeSupport.firePropertyChange("estado", oldEstado, estado);
}
public Integer getCep() {
return cep;
}
public void setCep(Integer cep) {
Integer oldCep = this.cep;
this.cep = cep;
changeSupport.firePropertyChange("cep", oldCep, cep);
}
public Integer getCpf() {
return cpf;
}
public void setCpf(Integer cpf) {
Integer oldCpf = this.cpf;
this.cpf = cpf;
changeSupport.firePropertyChange("cpf", oldCpf, cpf);
}
@Override
public int hashCode() {
int hash = 0;
hash += (codFuncionario != null ? codFuncionario.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Funcionarios)) {
return false;
}
Funcionarios other = (Funcionarios) object;
if ((this.codFuncionario == null && other.codFuncionario != null) || (this.codFuncionario != null && !this.codFuncionario.equals(other.codFuncionario))) {
return false;
}
return true;
}
@Override
public String toString() {
return "projeto_contensavel.Funcionarios[codFuncionario=" + codFuncionario + "]";
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
changeSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
changeSupport.removePropertyChangeListener(listener);
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package projeto_contensavel;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
*
* @author renata
*/
@Entity
@Table(name = "funcoes", catalog = "bd_contensavel", schema = "")
@NamedQueries({
@NamedQuery(name = "Funcoes.findAll", query = "SELECT f FROM Funcoes f"),
@NamedQuery(name = "Funcoes.findByCodFuncao", query = "SELECT f FROM Funcoes f WHERE f.codFuncao = :codFuncao"),
@NamedQuery(name = "Funcoes.findByFuncao", query = "SELECT f FROM Funcoes f WHERE f.funcao = :funcao")})
public class Funcoes implements Serializable {
@Transient
private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "cod_funcao")
private Integer codFuncao;
@Column(name = "funcao")
private String funcao;
@OneToMany(cascade = CascadeType.ALL,mappedBy = "codFuncao")
private List<Funcionarios> funcionariosList;
public Funcoes() {
}
public Funcoes(Integer codFuncao) {
this.codFuncao = codFuncao;
}
public Integer getCodFuncao() {
return codFuncao;
}
public void setCodFuncao(Integer codFuncao) {
Integer oldCodFuncao = this.codFuncao;
this.codFuncao = codFuncao;
changeSupport.firePropertyChange("codFuncao", oldCodFuncao, codFuncao);
}
public String getFuncao() {
return funcao;
}
public void setFuncao(String funcao) {
String oldFuncao = this.funcao;
this.funcao = funcao;
changeSupport.firePropertyChange("funcao", oldFuncao, funcao);
}
@Override
public int hashCode() {
int hash = 0;
hash += (codFuncao != null ? codFuncao.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Funcoes)) {
return false;
}
Funcoes other = (Funcoes) object;
if ((this.codFuncao == null && other.codFuncao != null) || (this.codFuncao != null && !this.codFuncao.equals(other.codFuncao))) {
return false;
}
return true;
}
@Override
public String toString() {
return "projeto_contensavel.Funcoes[codFuncao=" + codFuncao + "]";
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
changeSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
changeSupport.removePropertyChangeListener(listener);
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package projeto_contensavel;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
*
* @author renata
*/
@Entity
@Table(name = "filiais", catalog = "bd_contensavel", schema = "")
@NamedQueries({
@NamedQuery(name = "Filiais.findAll", query = "SELECT f FROM Filiais f"),
@NamedQuery(name = "Filiais.findByCodFilial", query = "SELECT f FROM Filiais f WHERE f.codFilial = :codFilial"),
@NamedQuery(name = "Filiais.findByRazaoSocial", query = "SELECT f FROM Filiais f WHERE f.razaoSocial = :razaoSocial"),
@NamedQuery(name = "Filiais.findByCnpj", query = "SELECT f FROM Filiais f WHERE f.cnpj = :cnpj"),
@NamedQuery(name = "Filiais.findByRua", query = "SELECT f FROM Filiais f WHERE f.rua = :rua"),
@NamedQuery(name = "Filiais.findByBairro", query = "SELECT f FROM Filiais f WHERE f.bairro = :bairro"),
@NamedQuery(name = "Filiais.findByCidade", query = "SELECT f FROM Filiais f WHERE f.cidade = :cidade"),
@NamedQuery(name = "Filiais.findByEstado", query = "SELECT f FROM Filiais f WHERE f.estado = :estado"),
@NamedQuery(name = "Filiais.findByCep", query = "SELECT f FROM Filiais f WHERE f.cep = :cep")})
public class Filiais implements Serializable {
@Transient
private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "cod_filial")
private Integer codFilial;
@Column(name = "razao_social")
private String razaoSocial;
@Column(name = "cnpj")
private Integer cnpj;
@Column(name = "rua")
private String rua;
@Column(name = "bairro")
private String bairro;
@Column(name = "cidade")
private String cidade;
@Column(name = "estado")
private String estado;
@Column(name = "cep")
private Integer cep;
@OneToMany(mappedBy = "codFilial")
private List<Ordens> ordensList;
public Filiais() {
}
public Filiais(Integer codFilial) {
this.codFilial = codFilial;
}
public Integer getCodFilial() {
return codFilial;
}
public void setCodFilial(Integer codFilial) {
Integer oldCodFilial = this.codFilial;
this.codFilial = codFilial;
changeSupport.firePropertyChange("codFilial", oldCodFilial, codFilial);
}
public String getRazaoSocial() {
return razaoSocial;
}
public void setRazaoSocial(String razaoSocial) {
String oldRazaoSocial = this.razaoSocial;
this.razaoSocial = razaoSocial;
changeSupport.firePropertyChange("razaoSocial", oldRazaoSocial, razaoSocial);
}
public Integer getCnpj() {
return cnpj;
}
public void setCnpj(Integer cnpj) {
Integer oldCnpj = this.cnpj;
this.cnpj = cnpj;
changeSupport.firePropertyChange("cnpj", oldCnpj, cnpj);
}
public String getRua() {
return rua;
}
public void setRua(String rua) {
String oldRua = this.rua;
this.rua = rua;
changeSupport.firePropertyChange("rua", oldRua, rua);
}
public String getBairro() {
return bairro;
}
public void setBairro(String bairro) {
String oldBairro = this.bairro;
this.bairro = bairro;
changeSupport.firePropertyChange("bairro", oldBairro, bairro);
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
String oldCidade = this.cidade;
this.cidade = cidade;
changeSupport.firePropertyChange("cidade", oldCidade, cidade);
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
String oldEstado = this.estado;
this.estado = estado;
changeSupport.firePropertyChange("estado", oldEstado, estado);
}
public Integer getCep() {
return cep;
}
public void setCep(Integer cep) {
Integer oldCep = this.cep;
this.cep = cep;
changeSupport.firePropertyChange("cep", oldCep, cep);
}
@Override
public int hashCode() {
int hash = 0;
hash += (codFilial != null ? codFilial.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Filiais)) {
return false;
}
Filiais other = (Filiais) object;
if ((this.codFilial == null && other.codFilial != null) || (this.codFilial != null && !this.codFilial.equals(other.codFilial))) {
return false;
}
return true;
}
@Override
public String toString() {
return "projeto_contensavel.Filiais[codFilial=" + codFilial + "]";
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
changeSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
changeSupport.removePropertyChangeListener(listener);
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* JFFiliais.java
*
* Created on 01/12/2011, 10:46:52
*/
package projeto_contensavel;
import java.awt.EventQueue;
import java.beans.Beans;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.RollbackException;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* @author <NAME>
*/
public class JFFiliais extends JPanel {
public JFFiliais() {
initComponents();
if (!Beans.isDesignTime()) {
entityManager.getTransaction().begin();
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(projeto_contensavel.Projeto_contensavelApp.class).getContext().getResourceMap(JFFiliais.class);
entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory(resourceMap.getString("entityManager.persistenceUnit")).createEntityManager(); // NOI18N
query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery(resourceMap.getString("query.query")); // NOI18N
list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
masterScrollPane = new javax.swing.JScrollPane();
masterTable = new javax.swing.JTable();
razaoSocialLabel = new javax.swing.JLabel();
cnpjLabel = new javax.swing.JLabel();
ruaLabel = new javax.swing.JLabel();
bairroLabel = new javax.swing.JLabel();
cidadeLabel = new javax.swing.JLabel();
estadoLabel = new javax.swing.JLabel();
cepLabel = new javax.swing.JLabel();
razaoSocialField = new javax.swing.JTextField();
cnpjField = new javax.swing.JTextField();
ruaField = new javax.swing.JTextField();
bairroField = new javax.swing.JTextField();
cidadeField = new javax.swing.JTextField();
estadoField = new javax.swing.JTextField();
cepField = new javax.swing.JTextField();
saveButton = new javax.swing.JButton();
refreshButton = new javax.swing.JButton();
newButton = new javax.swing.JButton();
deleteButton = new javax.swing.JButton();
FormListener formListener = new FormListener();
setName("Form"); // NOI18N
masterScrollPane.setName("masterScrollPane"); // NOI18N
masterTable.setName("masterTable"); // NOI18N
org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${codFilial}"));
columnBinding.setColumnName("Cod Filial");
columnBinding.setColumnClass(Integer.class);
columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${razaoSocial}"));
columnBinding.setColumnName("Razao Social");
columnBinding.setColumnClass(String.class);
bindingGroup.addBinding(jTableBinding);
jTableBinding.bind();
masterScrollPane.setViewportView(masterTable);
masterTable.getColumnModel().getColumn(0).setPreferredWidth(80);
masterTable.getColumnModel().getColumn(0).setMaxWidth(80);
masterTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("masterTable.columnModel.title0")); // NOI18N
masterTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("masterTable.columnModel.title1")); // NOI18N
razaoSocialLabel.setText(resourceMap.getString("razaoSocialLabel.text")); // NOI18N
razaoSocialLabel.setName("razaoSocialLabel"); // NOI18N
cnpjLabel.setText(resourceMap.getString("cnpjLabel.text")); // NOI18N
cnpjLabel.setName("cnpjLabel"); // NOI18N
ruaLabel.setText(resourceMap.getString("ruaLabel.text")); // NOI18N
ruaLabel.setName("ruaLabel"); // NOI18N
bairroLabel.setText(resourceMap.getString("bairroLabel.text")); // NOI18N
bairroLabel.setName("bairroLabel"); // NOI18N
cidadeLabel.setText(resourceMap.getString("cidadeLabel.text")); // NOI18N
cidadeLabel.setName("cidadeLabel"); // NOI18N
estadoLabel.setText(resourceMap.getString("estadoLabel.text")); // NOI18N
estadoLabel.setName("estadoLabel"); // NOI18N
cepLabel.setText(resourceMap.getString("cepLabel.text")); // NOI18N
cepLabel.setName("cepLabel"); // NOI18N
razaoSocialField.setName("razaoSocialField"); // NOI18N
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.razaoSocial}"), razaoSocialField, org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceUnreadableValue(null);
bindingGroup.addBinding(binding);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), razaoSocialField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
bindingGroup.addBinding(binding);
cnpjField.setName("cnpjField"); // NOI18N
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.cnpj}"), cnpjField, org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceUnreadableValue(null);
bindingGroup.addBinding(binding);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), cnpjField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
bindingGroup.addBinding(binding);
ruaField.setName("ruaField"); // NOI18N
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.rua}"), ruaField, org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceUnreadableValue(null);
bindingGroup.addBinding(binding);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), ruaField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
bindingGroup.addBinding(binding);
bairroField.setName("bairroField"); // NOI18N
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.bairro}"), bairroField, org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceUnreadableValue(null);
bindingGroup.addBinding(binding);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), bairroField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
bindingGroup.addBinding(binding);
cidadeField.setName("cidadeField"); // NOI18N
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.cidade}"), cidadeField, org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceUnreadableValue(null);
bindingGroup.addBinding(binding);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), cidadeField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
bindingGroup.addBinding(binding);
estadoField.setName("estadoField"); // NOI18N
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.estado}"), estadoField, org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceUnreadableValue(null);
bindingGroup.addBinding(binding);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), estadoField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
bindingGroup.addBinding(binding);
cepField.setName("cepField"); // NOI18N
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.cep}"), cepField, org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceUnreadableValue(null);
bindingGroup.addBinding(binding);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), cepField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
bindingGroup.addBinding(binding);
saveButton.setText(resourceMap.getString("saveButton.text")); // NOI18N
saveButton.setName("saveButton"); // NOI18N
saveButton.addActionListener(formListener);
refreshButton.setText(resourceMap.getString("refreshButton.text")); // NOI18N
refreshButton.setName("refreshButton"); // NOI18N
refreshButton.addActionListener(formListener);
newButton.setText(resourceMap.getString("newButton.text")); // NOI18N
newButton.setName("newButton"); // NOI18N
newButton.addActionListener(formListener);
deleteButton.setText(resourceMap.getString("deleteButton.text")); // NOI18N
deleteButton.setName("deleteButton"); // NOI18N
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), deleteButton, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
bindingGroup.addBinding(binding);
deleteButton.addActionListener(formListener);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(newButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(deleteButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(refreshButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(saveButton))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(razaoSocialLabel)
.addComponent(cnpjLabel)
.addComponent(ruaLabel)
.addComponent(bairroLabel)
.addComponent(cidadeLabel)
.addComponent(estadoLabel)
.addComponent(cepLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(razaoSocialField, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
.addComponent(cnpjField, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
.addComponent(ruaField, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
.addComponent(bairroField, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
.addComponent(cidadeField, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
.addComponent(estadoField, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
.addComponent(cepField, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 383, Short.MAX_VALUE)))
.addContainerGap())
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {deleteButton, newButton, refreshButton, saveButton});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(razaoSocialLabel)
.addComponent(razaoSocialField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cnpjLabel)
.addComponent(cnpjField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ruaLabel)
.addComponent(ruaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bairroLabel)
.addComponent(bairroField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cidadeLabel)
.addComponent(cidadeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(estadoLabel)
.addComponent(estadoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cepLabel)
.addComponent(cepField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(saveButton)
.addComponent(refreshButton)
.addComponent(deleteButton)
.addComponent(newButton))
.addContainerGap())
);
bindingGroup.bind();
}
// Code for dispatching events from components to event handlers.
private class FormListener implements java.awt.event.ActionListener {
FormListener() {}
public void actionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == saveButton) {
JFFiliais.this.saveButtonActionPerformed(evt);
}
else if (evt.getSource() == refreshButton) {
JFFiliais.this.refreshButtonActionPerformed(evt);
}
else if (evt.getSource() == newButton) {
JFFiliais.this.newButtonActionPerformed(evt);
}
else if (evt.getSource() == deleteButton) {
JFFiliais.this.deleteButtonActionPerformed(evt);
}
}
}// </editor-fold>//GEN-END:initComponents
@SuppressWarnings("unchecked")
private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
entityManager.getTransaction().rollback();
entityManager.getTransaction().begin();
java.util.Collection data = query.getResultList();
for (Object entity : data) {
entityManager.refresh(entity);
}
list.clear();
list.addAll(data);
}//GEN-LAST:event_refreshButtonActionPerformed
private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
int[] selected = masterTable.getSelectedRows();
List<projeto_contensavel.Filiais> toRemove = new ArrayList<projeto_contensavel.Filiais>(selected.length);
for (int idx=0; idx<selected.length; idx++) {
projeto_contensavel.Filiais f = list.get(masterTable.convertRowIndexToModel(selected[idx]));
toRemove.add(f);
entityManager.remove(f);
}
list.removeAll(toRemove);
}//GEN-LAST:event_deleteButtonActionPerformed
private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
projeto_contensavel.Filiais f = new projeto_contensavel.Filiais();
entityManager.persist(f);
list.add(f);
int row = list.size()-1;
masterTable.setRowSelectionInterval(row, row);
masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
}//GEN-LAST:event_newButtonActionPerformed
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
try {
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
} catch (RollbackException rex) {
rex.printStackTrace();
entityManager.getTransaction().begin();
List<projeto_contensavel.Filiais> merged = new ArrayList<projeto_contensavel.Filiais>(list.size());
for (projeto_contensavel.Filiais f : list) {
merged.add(entityManager.merge(f));
}
list.clear();
list.addAll(merged);
}
}//GEN-LAST:event_saveButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField bairroField;
private javax.swing.JLabel bairroLabel;
private javax.swing.JTextField cepField;
private javax.swing.JLabel cepLabel;
private javax.swing.JTextField cidadeField;
private javax.swing.JLabel cidadeLabel;
private javax.swing.JTextField cnpjField;
private javax.swing.JLabel cnpjLabel;
private javax.swing.JButton deleteButton;
private javax.persistence.EntityManager entityManager;
private javax.swing.JTextField estadoField;
private javax.swing.JLabel estadoLabel;
private java.util.List<projeto_contensavel.Filiais> list;
private javax.swing.JScrollPane masterScrollPane;
private javax.swing.JTable masterTable;
private javax.swing.JButton newButton;
private javax.persistence.Query query;
private javax.swing.JTextField razaoSocialField;
private javax.swing.JLabel razaoSocialLabel;
private javax.swing.JButton refreshButton;
private javax.swing.JTextField ruaField;
private javax.swing.JLabel ruaLabel;
private javax.swing.JButton saveButton;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration//GEN-END:variables
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setContentPane(new JFFiliais());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
| 9fab1146c666f695c52b4bf5c77a90704141f7d3 | [
"Java",
"SQL"
] | 5 | SQL | elandio/contensavel | 8bf0d40317226bf0a524e0ada78b40cf3fbe36b6 | 786f01c20514b6d95a744a855ece8e43cd71a41b |
refs/heads/master | <repo_name>TomasPachnik/SpringBootBasic<file_sep>/src/main/java/sk/tomas/app/dao/impl/IdentityDaoImpl.java
package sk.tomas.app.dao.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import sk.tomas.app.dao.IdentityDao;
import sk.tomas.app.model.Identity;
import sk.tomas.app.orm.IdentityNode;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
/**
* Created by tomas on 24.12.2016.
*/
@Repository
public class IdentityDaoImpl extends BaseDaoImpl<Identity, IdentityNode> implements IdentityDao {
private static Logger loger = LoggerFactory.getLogger(IdentityDaoImpl.class);
@Resource
private DataSource dataSource;
public IdentityDaoImpl() {
super(Identity.class, IdentityNode.class);
}
@Override
public boolean hasRole(UUID identityUuid, UUID roleUuid) {
String hql = "SELECT i.login FROM Identity i " +
"JOIN role_identity ri ON i.uuid = ri.identity_uuid " +
"JOIN Role r ON ri.role_uuid = r.uuid " +
"WHERE i.uuid = ? and r.uuid = ?";
Connection connection;
try {
connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(hql);
preparedStatement.setString(1, identityUuid.toString());
preparedStatement.setString(2, roleUuid.toString());
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return true;
}
} catch (SQLException e) {
loger.error("hasRole: " + e);
}
return false;
}
}
<file_sep>/src/main/java/sk/tomas/app/mapper/UuidStringConverter.java
package sk.tomas.app.mapper;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.converter.BidirectionalConverter;
import ma.glasnost.orika.metadata.Type;
import java.util.UUID;
/**
* Created by <NAME> on 05-Jan-17.
*/
public class UuidStringConverter extends BidirectionalConverter<UUID, String> {
@Override
public String convertTo(UUID source, Type<String> destinationType, MappingContext mappingContext) {
return source.toString();
}
@Override
public UUID convertFrom(String source, Type<UUID> destinationType, MappingContext mappingContext) {
return UUID.fromString(source);
}
}
<file_sep>/src/main/java/sk/tomas/app/service/impl/RoleServiceImpl.java
package sk.tomas.app.service.impl;
import ma.glasnost.orika.MapperFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sk.tomas.app.dao.BaseDao;
import sk.tomas.app.dao.RoleDao;
import sk.tomas.app.exception.InputValidationException;
import sk.tomas.app.iam.model.input.RoleInput;
import sk.tomas.app.iam.model.output.IdentityOutput;
import sk.tomas.app.iam.model.output.IdentityPaginationWithCount;
import sk.tomas.app.iam.model.output.RoleOutput;
import sk.tomas.app.iam.model.output.RolePaginationWithCount;
import sk.tomas.app.model.Identity;
import sk.tomas.app.model.Role;
import sk.tomas.app.service.RoleService;
import java.util.List;
import java.util.UUID;
/**
* Created by <NAME> on 05-Jan-17.
*/
@Service
@Transactional
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {
private static Logger loger = LoggerFactory.getLogger(RoleServiceImpl.class);
@Autowired
private RoleDao roleDao;
@Autowired
private MapperFacade mapper;
@Override
public BaseDao getDao() {
return roleDao;
}
@Override
public Role findByName(String name) {
return roleDao.findByValue("name", name);
}
@Override
public List<RoleOutput> getList() {
List<Role> list = list();
return mapper.mapAsList(list, RoleOutput.class);
}
@Override
@Cacheable(value = "findRoleOutputByUuid", key = "#uuid")
public RoleOutput findRoleOutputByUuid(UUID uuid) {
Role byUuid = findByUuid(uuid);
return mapper.map(byUuid, RoleOutput.class);
}
@Override
public UUID create(RoleInput roleInput) {
Role role = mapper.map(roleInput, Role.class);
UUID uuid = create(role);
loger.info("Vytvorena rola '{}'", role);
return uuid;
}
@Override
@CacheEvict(value = "findRoleOutputByUuid", key = "#uuid")
public void update(RoleInput roleInput, UUID uuid) {
Role old = findByUuid(uuid);
Role role = mapper.map(roleInput, Role.class);
role.setUuid(uuid);
role.setIdentities(old.getIdentities());
update(role);
loger.info("Rola '{}' aktualizovana na '{}'", old, roleInput);
}
@Override
public RolePaginationWithCount listwithCount(int firstResult, int maxResult, String orderBy, boolean desc) {
List<Role> list = list(firstResult, maxResult, orderBy, desc);
List<RoleOutput> roleOutputs = mapper.mapAsList(list, RoleOutput.class);
return new RolePaginationWithCount(count(), roleOutputs);
}
@Override
@CacheEvict(value = "findRoleOutputByUuid", key = "#uuid")
public void delete(UUID uuid) throws InputValidationException {
Role role = findByUuid(uuid);
getDao().delete(uuid);
loger.info("Zmazana rola '{}'.", role);
}
}
<file_sep>/src/main/java/sk/tomas/app/util/ErrorMessages.java
package sk.tomas.app.util;
/**
* Created by <NAME> on 05-Jan-17.
*/
public enum ErrorMessages {
MISSING_UUID(1, "Uuid must be set!"),
MOREOVER_UUID(2, "Uuid should not be set, the repository sets it automatically!"),
RELATED_NOT_CREATED(3, "Related object is not created before!");
private int code;
private String message;
ErrorMessages(int code, String test) {
this.code = code;
this.message = test;
}
public String getMessage() {
return message;
}
public int getCode() {
return code;
}
}
<file_sep>/src/main/java/sk/tomas/app/security/CustomAuthenticationTokenFilter.java
package sk.tomas.app.security;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.UrlPathHelper;
import sk.tomas.app.model.Token;
import sk.tomas.app.service.TokenService;
import sk.tomas.app.util.Util;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static sk.tomas.app.util.Constrants.AUTHORIZE_ENDPOINT;
/**
* Created by tomas on 07.01.2017.
*/
@Component
public class CustomAuthenticationTokenFilter extends OncePerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationTokenFilter.class);
@Autowired
AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private TokenService tokenService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String path = new UrlPathHelper().getPathWithinApplication(request);
String authToken = request.getHeader("authorization");
//ako prve ide bearer, bude castejsi
if (!AUTHORIZE_ENDPOINT.equals(path)) {
String bearer = "Bearer ";
if (authToken != null && authToken.startsWith(bearer) && authToken.length() > bearer.length()) {
//TODO lepsia validacia authorization
String token = authToken.substring(authToken.lastIndexOf(bearer) + bearer.length());
Token user = tokenService.getUserByToken(token);
if (user != null) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserDetails().getUsername(), null, user.getUserDetails().getAuthorities());
usernamePasswordAuthenticationToken.setDetails(token);
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
filterChain.doFilter(request, response);
} else {
logger.warn("Zadany token '{}' sa v systeme nenachadza.", token);
throw new BadCredentialsException("Bad Credentials");
}
} else {
logger.warn("Bearer token '{}' je v nespravnom tvare, alebo neexistuje.", authToken);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
} else {
//autentifikujem
String basic = "Basic ";
if (authToken != null && authToken.startsWith(basic) && authToken.length() > basic.length()) {
//TODO lepsia validacia authorization
UsernamePasswordAuthenticationToken authRequest = basicCheck(authToken);
SecurityContextHolder.getContext().setAuthentication(authRequest);
filterChain.doFilter(request, response);
} else {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
}
/**
* vrati UsernamePasswordAuthenticationToken vygenerovany z basic auth
*
* @param authToken
* @return
*/
private UsernamePasswordAuthenticationToken basicCheck(String authToken) throws BadCredentialsException {
String basic = "Basic ";
String encodedAuth = authToken.substring(authToken.lastIndexOf(basic) + basic.length());
String decodedAuth = Util.base64decode(encodedAuth);
String[] parts = decodedAuth.split(":");
if (parts.length != 2) {
throw new BadCredentialsException("Bad Credentials");
}
String username = parts[0];
String password = parts[1];
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (userDetails == null) {
logger.warn("Pouzivatel '{}' nenajdeny.", username);
throw new BadCredentialsException("Bad Credentials");
}
if (!passwordEncoder.matches(password, userDetails.getPassword())) {
logger.warn("Pouzivatel '{}' zadal nespravne heslo.", username);
throw new BadCredentialsException("Bad Credentials");
}
String tokenByLogin = tokenService.getTokenByLogin(username);
if (tokenByLogin != null) {//ak uz token existuje, tak ho zmazem
tokenService.removeUser(tokenByLogin);
}
String token = tokenService.loginUser(userDetails);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, null, userDetails.getAuthorities());
authRequest.setDetails(token);
logger.info("Prihlasenie pouzivatela '{}', vydany token: '{}'", userDetails.getUsername(), token);
return authRequest;
}
}
<file_sep>/src/main/java/sk/tomas/app/exception/InputValidationException.java
package sk.tomas.app.exception;
/**
* Created by <NAME> on 12-Jan-17.
*/
public class InputValidationException extends BusinessException {
public InputValidationException(String message) {
super(message);
}
}
<file_sep>/src/main/java/sk/tomas/app/orm/IdentityNode.java
package sk.tomas.app.orm;
import javax.persistence.*;
import java.util.Set;
/**
* Created by <NAME> on 05-Jan-17.
*/
@Entity
@Table(name = "Identity")
public class IdentityNode extends EntityNode {
@Column(length = 50)
private String name;
@Column(length = 50)
private String surname;
@Column(unique = true, nullable = false, length = 50)
private String login;
private String email;
private String encodedPassword;
private int age;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "role_identity",
joinColumns = {@JoinColumn(name = "identity_uuid", nullable = false, updatable = false)},
inverseJoinColumns = {@JoinColumn(name = "role_uuid", nullable = false, updatable = false)})
private Set<RoleNode> roles;
public IdentityNode(String uuid, String name, String surname, String login, String email, String encodedPassowrd, int age) {
super(uuid);
this.name = name;
this.surname = surname;
this.login = login;
this.email = email;
this.encodedPassword = <PASSWORD>;
this.age = age;
}
public IdentityNode() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEncodedPassword() {
return encodedPassword;
}
public void setEncodedPassword(String encodedPassword) {
this.encodedPassword = encodedPassword;
}
public Set<RoleNode> getRoles() {
return roles;
}
public void setRoles(Set<RoleNode> roles) {
this.roles = roles;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
IdentityNode that = (IdentityNode) o;
if (age != that.age) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (surname != null ? !surname.equals(that.surname) : that.surname != null) return false;
if (login != null ? !login.equals(that.login) : that.login != null) return false;
if (email != null ? !email.equals(that.email) : that.email != null) return false;
if (encodedPassword != null ? !encodedPassword.equals(that.encodedPassword) : that.encodedPassword != null)
return false;
return roles != null ? roles.equals(that.roles) : that.roles == null;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (surname != null ? surname.hashCode() : 0);
result = 31 * result + (login != null ? login.hashCode() : 0);
result = 31 * result + (email != null ? email.hashCode() : 0);
result = 31 * result + (encodedPassword != null ? encodedPassword.hashCode() : 0);
result = 31 * result + age;
result = 31 * result + (roles != null ? roles.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "IdentityNode{" +
"name='" + name + '\'' +
", surname='" + surname + '\'' +
", login='" + login + '\'' +
", email='" + email + '\'' +
", encodedPassword='" + encodedPassword + '\'' +
", age=" + age +
'}';
}
}
<file_sep>/src/main/java/sk/tomas/app/service/impl/UserDetailsServiceImpl.java
package sk.tomas.app.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sk.tomas.app.model.Identity;
import sk.tomas.app.model.Role;
import sk.tomas.app.service.IdentityService;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by tomas on 06.01.2017.
*/
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private IdentityService identityService;
@Transactional(readOnly = true)
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Identity identity = identityService.findByLogin(username);
if (identity != null) {
List<GrantedAuthority> grantedAuthorities = buildUserAuthority(identity.getRoles());
return new User(identity.getLogin(), identity.getPassword().getPassword(), true, true, true, true, grantedAuthorities);
}
return null;
}
private List<GrantedAuthority> buildUserAuthority(Set<Role> roles) {
Set<GrantedAuthority> result = new HashSet<>();
for (Role role : roles) {
result.add(new SimpleGrantedAuthority(role.getName()));
}
return new ArrayList<>(result);
}
}
<file_sep>/src/main/java/sk/tomas/app/exception/BusinessException.java
package sk.tomas.app.exception;
/**
* Created by <NAME> on 12-Jan-17.
*/
public class BusinessException extends Exception {
BusinessException(String message) {
super(message);
}
}
<file_sep>/src/main/java/sk/tomas/app/controller/AuthController.java
package sk.tomas.app.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sk.tomas.app.iam.model.output.Token;
import sk.tomas.app.iam.model.output.TokenOutput;
import sk.tomas.app.service.TokenService;
import static sk.tomas.app.util.Constrants.AUTHORIZE_ENDPOINT;
import static sk.tomas.app.util.Constrants.TOKEN_INFO_ENDPOINT;
/**
* Created by <NAME> on 12-Jan-17.
*/
@RestController
public class AuthController {
@Autowired
TokenService tokenService;
@RequestMapping(method = RequestMethod.GET, value = AUTHORIZE_ENDPOINT)
public Token authenticate() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String token = (String) authentication.getDetails();
return new Token(token);
}
@RequestMapping(method = RequestMethod.GET, value = TOKEN_INFO_ENDPOINT)
public TokenOutput tokenInfo() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String token = (String) authentication.getDetails();
return tokenService.getTokenEntityByToken(token);
}
}
<file_sep>/src/main/java/sk/tomas/app/dao/RoleDao.java
package sk.tomas.app.dao;
import sk.tomas.app.model.Role;
/**
* Created by <NAME> on 05-Jan-17.
*/
public interface RoleDao extends BaseDao<Role>{
}
<file_sep>/src/main/java/sk/tomas/app/model/base/Entity.java
package sk.tomas.app.model.base;
import java.util.UUID;
/**
* Created by <NAME> on 04-Jan-17.
*/
public abstract class Entity {
private UUID uuid;
public Entity(UUID uuid) {
this.uuid = uuid;
}
public Entity() {
}
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Entity entity = (Entity) o;
return uuid != null ? uuid.equals(entity.uuid) : entity.uuid == null;
}
@Override
public int hashCode() {
return uuid != null ? uuid.hashCode() : 0;
}
@Override
public String toString() {
return "Entity{" +
"uuid='" + uuid + '\'' +
'}';
}
}
<file_sep>/src/main/java/sk/tomas/app/orm/EntityNode.java
package sk.tomas.app.orm;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
/**
* Created by <NAME> on 05-Jan-17.
*/
@MappedSuperclass
public abstract class EntityNode implements Serializable {
@Id
@Column(unique = true, nullable = false, length = 36)
private String uuid;
EntityNode(String uuid) {
this.uuid = uuid;
}
EntityNode() {
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EntityNode that = (EntityNode) o;
return uuid != null ? uuid.equals(that.uuid) : that.uuid == null;
}
@Override
public int hashCode() {
return uuid != null ? uuid.hashCode() : 0;
}
@Override
public String toString() {
return "EntityNode{" +
"uuid=" + uuid +
'}';
}
}
<file_sep>/src/main/java/sk/tomas/app/mapper/PasswordStringConverter.java
package sk.tomas.app.mapper;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.converter.BidirectionalConverter;
import ma.glasnost.orika.metadata.Type;
import sk.tomas.app.model.Password;
/**
* Created by tomas on 06.01.2017.
*/
public class PasswordStringConverter extends BidirectionalConverter<Password, String> {
@Override
public String convertTo(Password source, Type<String> destinationType, MappingContext mappingContext) {
return source.getPassword();
}
@Override
public Password convertFrom(String source, Type<Password> destinationType, MappingContext mappingContext) {
return new Password(source);
}
}
<file_sep>/src/main/java/sk/tomas/app/service/impl/BaseServiceImpl.java
package sk.tomas.app.service.impl;
import sk.tomas.app.dao.BaseDao;
import sk.tomas.app.exception.InputValidationException;
import sk.tomas.app.model.base.Entity;
import sk.tomas.app.service.BaseService;
import java.util.List;
import java.util.UUID;
/**
* Created by <NAME> on 05-Jan-17.
*/
public abstract class BaseServiceImpl<T extends Entity> implements BaseService<T> {
protected abstract BaseDao getDao();
@SuppressWarnings("unchecked")
public UUID create(T t) {
return getDao().create(t);
}
@SuppressWarnings("unchecked")
public UUID update(T t) {
return getDao().update(t);
}
public void delete(UUID uuid) throws InputValidationException {
getDao().delete(uuid);
}
@SuppressWarnings("unchecked")
public List<T> list() {
return getDao().list();
}
@SuppressWarnings("unchecked")
public List<T> list(int firstResult, int maxResult, String orderBy, boolean desc) {
return getDao().list(firstResult, maxResult, orderBy, desc);
}
public long count() {
return getDao().count();
}
@SuppressWarnings("unchecked")
public T findByUuid(UUID uuid) {
return (T) getDao().findByUuid(uuid);
}
}
<file_sep>/src/main/java/sk/tomas/app/dao/impl/RoleDaoImpl.java
package sk.tomas.app.dao.impl;
import org.springframework.stereotype.Repository;
import sk.tomas.app.dao.RoleDao;
import sk.tomas.app.model.Role;
import sk.tomas.app.orm.RoleNode;
/**
* Created by <NAME> on 05-Jan-17.
*/
@Repository
public class RoleDaoImpl extends BaseDaoImpl<Role, RoleNode> implements RoleDao {
public RoleDaoImpl() {
super(Role.class, RoleNode.class);
}
}
<file_sep>/src/main/resources/application.properties
spring.datasource.url=jdbc:mysql://localhost/springbootbasic
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false<file_sep>/src/main/java/sk/tomas/app/configuration/Config.java
package sk.tomas.app.configuration;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import sk.tomas.app.mapper.ClassMapper;
import sk.tomas.app.mapper.PasswordStringConverter;
import sk.tomas.app.mapper.SetArrayConverter;
import sk.tomas.app.mapper.UuidStringConverter;
/**
* Created by <NAME> on 05-Jan-17.
*/
@EnableCaching
@Configuration
public class Config {
@Bean
public MapperFacade mapper() {
MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
mapperFactory.getConverterFactory().registerConverter(new UuidStringConverter());
mapperFactory.getConverterFactory().registerConverter(new PasswordStringConverter());
mapperFactory.getConverterFactory().registerConverter(new SetArrayConverter());
ClassMapper.mapClass(mapperFactory);
return mapperFactory.getMapperFacade();
}
@Bean
public CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheCacheManager().getObject());
}
@Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
cmfb.setShared(true);
return cmfb;
}
}
<file_sep>/src/main/java/sk/tomas/app/util/Util.java
package sk.tomas.app.util;
import org.apache.commons.codec.binary.Base64;
import static org.apache.commons.codec.binary.StringUtils.getBytesUtf8;
import static org.apache.commons.codec.binary.StringUtils.newStringUtf8;
/**
* Created by tomas on 09.01.2017.
*/
public class Util {
public static String base64decode(String endoded) {
return newStringUtf8(Base64.decodeBase64(endoded));
}
public static String base64encode(String decoded) {
return Base64.encodeBase64String(getBytesUtf8(decoded));
}
}
<file_sep>/src/main/java/sk/tomas/app/controller/Controller.java
package sk.tomas.app.controller;
import sk.tomas.app.exception.InputValidationException;
import sk.tomas.app.exception.OutputValidationException;
import sk.tomas.app.iam.model.output.Count;
import java.util.List;
import java.util.UUID;
/**
* Created by <NAME> on 01-Mar-17.
*/
public interface Controller<T, N, R> {
UUID create(T t) throws InputValidationException;
void delete(UUID uuid) throws InputValidationException;
N getSingle(UUID uuid) throws InputValidationException, OutputValidationException;
List<N> list() throws OutputValidationException;
R listWithParam(int firstResult, int maxResult, String orderBy, boolean desc) throws InputValidationException, OutputValidationException;
Count getCount() throws OutputValidationException;
void update(UUID uuid, T t) throws InputValidationException;
Controller getController();
}
<file_sep>/src/test/java/sk/tomas/app/util/CustomStringManufacturer.java
package sk.tomas.app.util;
import sk.tomas.app.iam.model.input.IdentityInput;
import uk.co.jemos.podam.api.AttributeMetadata;
import uk.co.jemos.podam.api.DataProviderStrategy;
import uk.co.jemos.podam.typeManufacturers.StringTypeManufacturerImpl;
import java.lang.reflect.Type;
import java.util.Map;
/**
* Created by <NAME> on 02-Mar-17.
*/
public class CustomStringManufacturer extends StringTypeManufacturerImpl {
@Override
public String getType(DataProviderStrategy strategy,
AttributeMetadata attributeMetadata,
Map<String, Type> genericTypesArgumentsMap) {
if (IdentityInput.class.isAssignableFrom(attributeMetadata.getPojoClass())) {
if ("email".equals(attributeMetadata.getAttributeName())) {
return "<EMAIL>";
}
}
return super.getType(strategy, attributeMetadata, genericTypesArgumentsMap);
}
}
<file_sep>/build.gradle
plugins {
id 'org.springframework.boot' version '1.5.1.RELEASE'
id "info.solidsoft.pitest" version "1.1.11"
}
apply plugin: 'java'
apply plugin: 'idea'
repositories {
mavenCentral()
maven { url "https://jitpack.io" }
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:1.4.3.RELEASE")
compile group: 'org.springframework', name: 'spring-jdbc', version: '4.3.3.RELEASE'
compile group: 'org.springframework', name: 'spring-orm', version: '4.3.3.RELEASE'
compile group: 'org.springframework', name: 'spring-aop', version: '4.3.3.RELEASE'
compile group: 'org.aspectj', name: 'aspectjrt', version: '1.8.9'
compile group: 'org.springframework', name: 'spring-aspects', version: '4.3.3.RELEASE'
compile group: 'org.springframework.security', name: 'spring-security-config', version: '4.2.1.RELEASE'
compile group: 'org.springframework.security', name: 'spring-security-web', version: '4.2.1.RELEASE'
compile group: 'org.hibernate', name: 'hibernate-core', version: '5.2.5.Final'
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.38'
compile group: 'ma.glasnost.orika', name: 'orika-core', version: '1.5.0'
compile 'org.slf4j:slf4j-api:1.7.21'
compile group: 'commons-codec', name: 'commons-codec', version: '1.9'
// validator
compile group: 'commons-validator', name: 'commons-validator', version: '1.4.0'
// ehcache
compile group: 'net.sf.ehcache', name: 'ehcache', version: '2.10.3'
compile group: 'org.springframework', name: 'spring-context', version: '4.3.3.RELEASE'
compile group: 'org.springframework', name: 'spring-context-support', version: '4.3.3.RELEASE'
// https://mvnrepository.com/artifact/org.springframework.security/spring-security-test
testCompile group: 'org.springframework.security', name: 'spring-security-test', version: '4.2.1.RELEASE'
testCompile 'junit:junit:4.12'
compile group: 'uk.co.jemos.podam', name: 'podam', version: '7.0.5.RELEASE'
compile group: 'org.springframework', name: 'spring-test', version: '4.3.3.RELEASE'
compile group: 'com.h2database', name: 'h2', version: '1.4.193'
compile group: 'hsqldb', name: 'hsqldb', version: '1.8.0.7'
compile group: 'org.apache.commons', name: 'commons-dbcp2', version: '2.1.1'
compile 'com.github.TomasPachnik:DependencyBasic:0.21'
}
springBoot {
mainClass = "sk.tomas.app.configuration.Application"
}
pitest {
targetClasses = ['sk.tomas.app.*'] //by default "${project.group}.*"
pitestVersion = "1.1.11" //not needed when a default PIT version should be used
threads = 4
outputFormats = ['XML', 'HTML']
}
<file_sep>/src/main/java/sk/tomas/app/controller/ExceptionHandlingController.java
package sk.tomas.app.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import sk.tomas.app.exception.BusinessException;
import sk.tomas.app.exception.ServerMessage;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
/**
* Created by tomas on 06.01.2017.
*/
@EnableWebMvc
@RestController
@ControllerAdvice
public class ExceptionHandlingController implements ErrorController {
private static final Logger logger = LoggerFactory.getLogger(ExceptionHandlingController.class);
private static final String PATH = "/error";
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
@ExceptionHandler(BadCredentialsException.class)
public ServerMessage badCredentials(BadCredentialsException e) {
return new ServerMessage("BadCredentialsException", e.getMessage());
}
@ResponseStatus(value = HttpStatus.FORBIDDEN)
@ExceptionHandler(AccessDeniedException.class)
public ServerMessage businessException(AccessDeniedException e) {
return new ServerMessage("AccessDeniedException", "Forbidden");
}
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(NoHandlerFoundException.class)
public ServerMessage noHandlerFound(NoHandlerFoundException e) {
return new ServerMessage("NoHandlerFoundException", e.getMessage());
}
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(BusinessException.class)
public ServerMessage accessDenied(BusinessException e) {
logger.warn(e.getMessage());
return new ServerMessage("BusinessException", e.getMessage());
}
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public ServerMessage handleAllException(Exception e) {
UUID uuid = UUID.randomUUID();
logger.error(uuid.toString(), e);
return new ServerMessage("InternalServerError", "interna chyba servera, id chyby: " + uuid);
}
@RequestMapping(value = PATH)
public void error(HttpServletRequest request, HttpServletResponse response) throws Throwable {
Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
if (throwable != null) {
throw throwable;
}
int status = response.getStatus();
if (status != HttpServletResponse.SC_OK) {
if (status == HttpServletResponse.SC_UNAUTHORIZED) {
throw new BadCredentialsException("Unauthorized");
} else {
logger.error("nepriradeny http status: " + status);
throw new Exception("nepriradeny http status: " + status);
}
}
}
@Override
public String getErrorPath() {
return PATH;
}
}
<file_sep>/src/main/java/sk/tomas/app/security/SpringSecurityInitializer.java
package sk.tomas.app.security;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
/**
* Created by tomas on 06.01.2017.
*/
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
<file_sep>/src/test/resources/application-test.properties
spring.datasource.url=jdbc:hsqldb:mem:springbootbasic
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.datasource.driver-class-name=org.hsqldb.jdbcDriver<file_sep>/src/main/java/sk/tomas/app/dao/impl/TokenDaoImpl.java
package sk.tomas.app.dao.impl;
import org.springframework.stereotype.Repository;
import sk.tomas.app.dao.TokenDao;
import sk.tomas.app.model.TokenEntity;
import sk.tomas.app.orm.TokenNode;
/**
* Created by <NAME> on 18-Jan-17.
*/
@Repository
public class TokenDaoImpl extends BaseDaoImpl<TokenEntity, TokenNode> implements TokenDao {
TokenDaoImpl() {
super(TokenEntity.class, TokenNode.class);
}
}
<file_sep>/src/main/java/sk/tomas/app/controller/IdentityController.java
package sk.tomas.app.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import sk.tomas.app.exception.InputValidationException;
import sk.tomas.app.exception.OutputValidationException;
import sk.tomas.app.iam.model.input.IdentityInput;
import sk.tomas.app.iam.model.output.Count;
import sk.tomas.app.iam.model.output.HasRole;
import sk.tomas.app.iam.model.output.IdentityOutput;
import sk.tomas.app.iam.model.output.IdentityPaginationWithCount;
import sk.tomas.app.service.IdentityService;
import sk.tomas.app.validator.IdentityValidator;
import java.util.List;
import java.util.UUID;
import static sk.tomas.app.util.Constrants.BASE_PATH;
/**
* Created by tomas on 23.12.2016.
*/
@RestController
@RequestMapping(BASE_PATH + "/identities")
public class IdentityController implements Controller<IdentityInput, IdentityOutput, IdentityPaginationWithCount> {
@Autowired
private IdentityService identityService;
@Override
@RequestMapping(method = RequestMethod.GET)
public List<IdentityOutput> list() throws OutputValidationException {
List<IdentityOutput> list = identityService.getList();
IdentityValidator.validateOutput(list);
return list;
}
@Override
@RequestMapping(method = RequestMethod.GET, value = "/{uuid}")
public IdentityOutput getSingle(@PathVariable("uuid") UUID uuid) throws OutputValidationException, InputValidationException {
IdentityOutput identityOutputByUuid = identityService.findIdentityOutputByUuid(uuid);
IdentityValidator.validateOutput(identityOutputByUuid);
return identityOutputByUuid;
}
@RequestMapping(method = RequestMethod.GET, value = "/{identityUuid}/hasRole/{roleUuid}")
public HasRole hasRole(@PathVariable("identityUuid") UUID identityUuid, @PathVariable("roleUuid") UUID roleUuid) {
return identityService.hasRole(identityUuid, roleUuid);
}
@RequestMapping(method = RequestMethod.GET, value = "/{identityUuid}/addRole/{roleUuid}")
public void addRole(@PathVariable("identityUuid") UUID identityUuid, @PathVariable("roleUuid") UUID roleUuid) {
identityService.addRole(identityUuid, roleUuid);
}
@RequestMapping(method = RequestMethod.GET, value = "/{identityUuid}/removeRole/{roleUuid}")
public void removeRole(@PathVariable("identityUuid") UUID identityUuid, @PathVariable("roleUuid") UUID roleUuid) {
identityService.removeRole(identityUuid, roleUuid);
}
@Override
@RequestMapping(method = RequestMethod.GET, value = "/withParam")
public IdentityPaginationWithCount listWithParam(@RequestParam(defaultValue = "0", value = "firstResult") int firstResult, @RequestParam(defaultValue = "10", value = "maxResult") int maxResult,
@RequestParam(required = false, defaultValue = "uuid", value = "orderBy") String orderBy, @RequestParam(required = false, defaultValue = "false", value = "desc") boolean desc) throws InputValidationException, OutputValidationException {
IdentityValidator.validateInput(firstResult, maxResult, orderBy);
IdentityPaginationWithCount identityPaginationWithCount = identityService.listIdentityOutput(firstResult, maxResult, orderBy, desc);
IdentityValidator.validateOutput(identityPaginationWithCount.getIdentityOutputs());
return identityPaginationWithCount;
}
@Override
@RequestMapping(method = RequestMethod.GET, value = "/count}")
public Count getCount() throws OutputValidationException {
return new Count(identityService.count());
}
@Override
@PreAuthorize("hasAuthority('admin')")
@RequestMapping(method = RequestMethod.POST, value = "/create")
public UUID create(@RequestBody IdentityInput identity) throws InputValidationException {
IdentityValidator.validateInput(identity);
return identityService.create(identity);
}
@Override
@PreAuthorize("hasAuthority('admin')")
@RequestMapping(method = RequestMethod.POST, value = "/update/{uuid}")
public void update(@PathVariable("uuid") UUID uuid, @RequestBody IdentityInput identityInput) throws InputValidationException {
IdentityValidator.validateInput(identityInput, uuid);
identityService.update(identityInput, uuid);
}
@Override
public Controller getController() {
return this;
}
@Override
@PreAuthorize("hasAuthority('admin')")
@RequestMapping(method = RequestMethod.GET, value = "/delete/{uuid}")
public void delete(@PathVariable("uuid") UUID uuid) throws InputValidationException {
identityService.delete(uuid);
}
}
<file_sep>/src/test/resources/db/create-db.sql
CREATE TABLE identity (
uuid VARCHAR(36) PRIMARY KEY ,
name VARCHAR(50),
surname VARCHAR(50),
login VARCHAR(50),
enabled BOOLEAN,
email VARCHAR(256),
encodedPassword VARCHAR(256),
age INTEGER
);
CREATE TABLE role (
uuid VARCHAR(36) PRIMARY KEY ,
name VARCHAR(50),
description VARCHAR(256),
level INTEGER,
identity_uuid VARCHAR(36)
);
CREATE TABLE role_identity (
identity_uuid VARCHAR(36),
role_uuid VARCHAR(36),
FOREIGN KEY (identity_uuid)
REFERENCES Identity(uuid),
FOREIGN KEY (role_uuid)
REFERENCES Role(uuid)
);
CREATE TABLE token (
uuid VARCHAR(36) PRIMARY KEY,
token VARCHAR(48),
validity BIGINT,
login VARCHAR(50)
);<file_sep>/src/test/java/sk/tomas/app/tests/TokenTest.java
package sk.tomas.app.tests;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import sk.tomas.app.dao.TokenDao;
import sk.tomas.app.model.TokenEntity;
/**
* Created by <NAME> on 18-Jan-17.
*/
public class TokenTest extends BaseTest {
@Autowired
TokenDao tokenDao;
@Test
public void createTokenTest() {
//vytvorim token
TokenEntity tokenEntity = new TokenEntity("token", 1L, "login");
tokenDao.create(tokenEntity);
TokenEntity byValue = tokenDao.findByValue("login", "login");
Assert.assertTrue("Token nevytvoreny", tokenEntity.getToken().equals(byValue.getToken()));
}
}
| 327f1b48590d23b1623df270b091009ada05cd32 | [
"Java",
"SQL",
"INI",
"Gradle"
] | 29 | Java | TomasPachnik/SpringBootBasic | 121899149ba08619c48635ba0bfc15716b933830 | e89900cf0fa9284931be27965fc3babf1cd699d6 |
refs/heads/master | <file_sep>package net.okjsp.gmy;
import java.util.Date;
import java.util.List;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
public class GawiDao {
private static final String KEY_KIND = "Game";
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
String keyName = "games";
public void save(Game game) {
Key entityKey = KeyFactory.createKey(KEY_KIND, keyName);
Entity entity = new Entity(KEY_KIND, entityKey);
User firstUser = game.getFirstUser();
User secondUser = game.getSecondUser();
entity.setProperty("first", firstUser.getName());
entity.setProperty("firstchoice", firstUser.getChoice());
entity.setProperty("second", secondUser.getName());
entity.setProperty("secondchoice", secondUser.getChoice());
entity.setProperty("datetime", new Date());
entity.setProperty("ip", game.getIp());
datastore.put(entity);
}
public List<Entity> fetchAll() {
Key entityKey = KeyFactory.createKey(KEY_KIND, keyName);
Query query = new Query(KEY_KIND, entityKey).addSort("datetime",
Query.SortDirection.DESCENDING);
List<Entity> games = datastore.prepare(query).asList(
FetchOptions.Builder.withLimit(50));
return games;
}
}
<file_sep>package rick;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
/**
* code from: http://stackoverflow.com/questions/15432024/how-to-upload-a-file-using-commons-file-upload-streaming-api
*/
@WebServlet("/upload4")
public class UploadServlet4 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setHeader("Content-Type", "text/html");
out.print("Request content length is " + request.getContentLength()
+ "<br/>");
out.print("Request content type is "
+ request.getHeader("Content-Type") + "<br/>");
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator iter = upload.getItemIterator(request);
FileItemStream item = null;
String name = "";
InputStream stream = null;
while (iter.hasNext()) {
item = iter.next();
name = item.getFieldName();
stream = item.openStream();
if (item.isFormField()) {
out.write("Form field " + name + ": "
+ Streams.asString(stream) + "<br/>");
} else {
name = item.getName();
System.out.println("name==" + name);
if (name != null && !"".equals(name)) {
String fileName = new File(item.getName())
.getName();
out.write("Client file: " + item.getName()
+ " <br/>with file name " + fileName
+ " was uploaded.<br/>");
File file = new File(getServletContext()
.getRealPath("/" + fileName));
FileOutputStream fos = new FileOutputStream(file);
long fileSize = Streams.copy(stream, fos, true);
out.write("Size was " + fileSize + " bytes <br/>");
out.write("File Path is " + file.getPath()
+ "<br/>");
}
}
}
} catch (FileUploadException fue) {
out.write("fue!!!!!!!!!");
}
}
}
}<file_sep>package net.okjsp.gmy;
public class Game {
private User firstUser;
private User secondUser;
private String ip;
public Game(User firstUser, User secondUser, String ip) {
this.setFirstUser(firstUser);
this.setSecondUser(secondUser);
this.ip = ip;
}
public User getFirstUser() {
return firstUser;
}
public void setFirstUser(User firstUser) {
this.firstUser = firstUser;
}
public User getSecondUser() {
return secondUser;
}
public void setSecondUser(User secondUser) {
this.secondUser = secondUser;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
@Override
public String toString() {
return "Game [firstUser=" + firstUser + ", secondUser=" + secondUser
+ ", ip=" + ip + "]";
}
}
<file_sep>// this whole script won't have access to the dom either
importScripts('annealing.js');
var annealing = new Annealing();
onmessage = function(event) {
var callback = {
onNewMin: function(p) {
// postMessage('newmin')
postMessage(JSON.stringify(["newMin", p]));
},
onDone: function(p) {
// postMessage('draw')
postMessage(JSON.stringify(["draw", p]));
}
};
var passedData = JSON.parse(event.data);
annealing.init(passedData.opts, passedData.width,
passedData.height, callback);
annealing.go();
};
<file_sep>package net.okjsp.gmy;
import java.util.Arrays;
public class GawiBawiBo {
public static void main(String[] args) {
int[] ages = { 25, 32, 19, 27, 24 };
for (int i = 0; i < ages.length; i++) {
System.out.print(ages[i] + " ");
}
Arrays.sort(ages);
System.out.println("nsorted---->");
for (int i = 0; i < ages.length; i++) {
System.out.print(ages[i] + " ");
}
}
}
<file_sep>$(init);
function init() {
$('button').on('click', play);
hasInternets();
}
var items = ['가위', '바위', '보'];
var images = ['scissors', 'rock', 'paper'];
var onoff;
function play() {
var comIdx = Math.floor(Math.random() * 3);
var mine = $(this).html();
var mineIdx;
for (var i in items) {
if (mine === items[i]) {
mineIdx = i;
}
}
var diff = mineIdx - comIdx;
var result;
if (diff === 0) {
result = '<div>=</div>비겼습니다.';
} else if (diff === 1 || diff === -2) {
result = '<div>☜</div>당신이 이겼습니다.';
} else {
result = '<div>☞</div>컴퓨터가 이겼습니다.';
}
var message = getImgTag(mineIdx) + " : " + getImgTag(comIdx)
+ '<div>' + result + '</div>';
$('#result').html(message);
saveGame("p1", mineIdx, "p2", comIdx);
}
function getImgTag(idx) {
return '<img src="./images/' + images[idx] + '.png" alt="' + items[idx] + '">'
}
// code from https://gist.github.com/scottjehl/947084
//quick online/offline check
function hasInternets() {
var s = $.ajax({
type: "HEAD",
url: window.location.href.split("?")[0] + "?" + Math.random(),
async: false,
complete: showStatus
}).status;
//thx http://www.louisremi.com/2011/04/22/navigator-online-alternative-serverreachable/
return s >= 200 && s < 300 || s === 304;
}
function showStatus(r) {
var s = r.status;
onoff = s >= 200 && s < 300 || s === 304;
$('#online').html(onoff);
}
function saveGame(p1, c1, p2, c2) {
$.ajax({
url:'/gawi/save.jsp',
type: 'post',
data : {
'p1' : p1,
'c1' : c1,
'p2' : p2,
'c2' : c2
},
complete: function(r) {
console.log(r.statusCode);
}
});
console.log('console' + p1 + ' ' + c1);
}
<file_sep><!DOCTYPE html>
<html manifest="cache.appcache">
<head>
<meta charset="UTF-8">
<title>App Cache</title>
<style>
#appcache-message {
text-align: center;
}
#appcache-message img {
vertical-align: middle;
cursor: pointer;
}
.appcache-examples pre {
font-size: 80%;
}
</style>
</head>
<body>
<div class="slide offline-storage" id="app-cache">
<header><span class="js">JS</span> <h1>Application Cache</h1></header>
<section class="appcache-examples">
<pre><html <b>manifest="cache.appcache"</b>></pre>
<pre>
window.<b>applicationCache</b>.addEventListener('updateready', function(e) {
if (window.<b>applicationCache</b>.<b>status</b> == window.<b>applicationCache</b>.<b>UPDATEREADY</b>) {
window.<b>applicationCache</b>.<b>swapCache()</b>;
if (confirm('A new version of this site is available. Load it?')) {
window.location.reload();
}
}
}, false);
</pre>
cache.appcache:
<pre>CACHE MANIFEST
# version 1.0.0
CACHE:
/html5/src/logic.js
/html5/src/style.css
/html5/src/background.png
NETWORK:
*
</pre>
<p id="appcache-message">Turn off your internet connection and refresh this page!
<img src="refresh.png" onclick="window.location.reload();"/></p>
</section>
</div>
<script>
// Check if new appcache is available, load it, and reload page.
if (window.applicationCache) {
window.applicationCache.addEventListener('updateready', function(e) {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
window.applicationCache.swapCache();
if (confirm('A new version of this site is available. Load it?')) {
window.location.reload();
}
}
}, false);
}
</script>
</body>
</html><file_sep># Deploy
* use Windows JDK 1.7
* not MacOSX jdk
<http://okgawi.appspot.com/>
source:
<http://github.com/kenu/oksample/okgawi>
<file_sep>package net.okjsp.gmy;
public @interface Raddler {
}
<file_sep>package net.okjsp.ajax;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class Proxy {
public static void main(String[] args) throws Exception {
String sb = Proxy.getSource("http://okjsp.tistory.com/rss");
System.out.println(sb);
}
public static String getSource(String string) throws MalformedURLException,
IOException {
URL url = new URL(string);
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine).append("\n");
}
in.close();
return sb.toString();
}
}
| df9ae7d6cafe6aa14d394e1bb9fb925ff21110b2 | [
"JavaScript",
"Java",
"HTML",
"Markdown"
] | 10 | Java | kenu/oksample | ad3f5c82417b6e191cba8d82038774e538b5a7db | c38d9b8715806c19619e1cc1c2e587951291ff98 |
refs/heads/master | <file_sep>'''
Created on Apr 13, 2013
@author: agrammenos
'''
from Queue import PriorityQueue
'''
This is a simple priority Queue that extends the functionality
of the existing priority Queue that's built in Python already.
The functionality to be added is to put and remove tuples of the
form (item, priority) which is not available.
'''
class SuperPriorityQueue(PriorityQueue):
'''
Constructor, it creates a Priority Queue object and
increases the counter
'''
def __init__(self):
PriorityQueue.__init__(self)
self.counter = 0
'''
Put in the Queue
'''
def put(self, item, priority):
PriorityQueue.put(self, (priority, self.counter, item))
self.counter += 1
'''
Get it out of the Queue
'''
def get(self, *args, **kwargs):
_, _, item = PriorityQueue.get(self, *args, **kwargs)
return item
'''
To check if our queue is empty
'''
def empty(self):
return PriorityQueue.empty(self)<file_sep>'''
Created on Apr 13, 2013
@author: agrammenos
'''
import os
import time
import sys
from fileReader import fileReader
import searchProblem
from graphBuilder import graphBuilder
'''
This is for samples only [generate the sample
graph names that was provided as a sample
database for our program]
'''
def datasetNameCreator():
# create the files
files = []
# now append
for i in range(6):
files.append('dataset/sampleGraph'+str(i+1)+'.txt')
# now return it
return files
def processDay(data, day):
print('\nStarting Processing Day: ' + str(day+1) + '\n')
# problem builder
sp = graphBuilder(data, day)
str_ucs = '\nUCS Result for Day ' + str(day+1) + ': \n'
str_ida = '\nIDA* Result for Day ' + str(day+1) + ': \n'
# UCS Segment
t0 = time.time()
availActions = searchProblem.ucs(sp)
t1 = time.time()
ucstDiff = t1-t0
actualCost = sp.GetPathCost(availActions, sflag = True)
ucsCost = actualCost
# day result
ucsResult = (sp.visited, ucstDiff, sp.GetPathCost(availActions), actualCost, availActions)
print('UCS Result: \n')
print('\t' + str(ucsResult))
str_ucs += ('\t' + str(ucsResult) + '\n')
ucsPerf = (sp.visited, ucstDiff)
# End of UCS Segment
# IDA* Segment
t0 = time.time()
availActions, costEstimation = searchProblem.idaStarCallback(sp)
t1 = time.time()
idatDiff = t1-t0
actualCost = sp.GetPathCost(availActions, sflag = True)
idaCost = actualCost
idaResult = (sp.visited, idatDiff, costEstimation, actualCost, availActions)
print('\nIDA Result: \n')
print('\t' + str(idaResult))
str_ida += ('\t' + str(idaResult)+'\n')
idaPerf = (sp.visited, idatDiff)
# End of IDA* Segment
print('\nDone for day: ' + str(day+1) + '\n\n')
# return is for processing
return (ucsCost, idaCost, str_ucs, str_ida, ucsPerf, idaPerf)
'''
This function parses the files and generates the required
results (provided the files exist and are valid)
'''
def processFiles(files, bench):
# create the names
if(bench is True):
files = datasetNameCreator()
# get count
#percentage = len(files) * 80
# construct the file reader
r = fileReader()
# this is for global average
ucsSamples = []
idaSamples = []
#ucsPerfGlob = []
#idaPerfGlob = []
# now loop for each file
for f in files:
# reset costs for each run
ucsCost = 0
idaCost = 0
# performance counts
ucsPerfTime = 0
ucsVisited = 0
idaPerfTime = 0
idaVisited = 0
# reset the files
str_ida = ''
str_ucs = ''
# read data
fdat = r.readInputFile(f, 0)
for i in range(DAYS_RANGE_MAX):
# process each day and return
(tucsCost, tidaCost, t1, t2, tp1, tp2) = processDay(fdat, i)
# now add
# average costs
ucsCost += tucsCost
idaCost += tidaCost
# string data
str_ucs += t1
str_ida += t2
# performance
ucsPerfTime += tp1[1]
idaPerfTime += tp2[1]
ucsVisited += tp1[0]
idaVisited += tp2[0]
# when 80-day simulation finishes normalize
ucsCost /= DAYS_RANGE_MAX
idaCost /= DAYS_RANGE_MAX
ucsPerfTime /= DAYS_RANGE_MAX
idaPerfTime /= DAYS_RANGE_MAX
ucsVisited /= DAYS_RANGE_MAX
idaVisited /= DAYS_RANGE_MAX
# file header
str_fheader = 'Results for file: ' + str(f) + '\n' + '\nAverage Results for this file: \n' + '\tUCS: ' + str(ucsCost) + '\n\tIDA*: ' + str(idaCost) + '\n'
str_fheader += '\n\nAverage Performance for this file:\n\t UCS:\n\t\tVisited Nodes (Avg): ' + str(ucsVisited)
str_fheader += '\n\t\tExecution Time (Avg): ' + str(ucsPerfTime) + '\n\n'
str_fheader += '\n\nAverage Performance for this file:\n\t IDA*:\n\t\tVisited Nodes (Avg): ' + str(idaVisited)
str_fheader += '\n\t\tExecution Time (Avg): ' + str(idaPerfTime) + '\n\n'
str_filename = str(f).replace('dataset/', '') + '.result'
# write it to the corresponding file
writeOutput(str_ucs, str_ida, str_fheader, str_filename)
# now add it
ucsSamples.append(ucsCost)
idaSamples.append(idaCost)
# when all 6 files finish print Average Costs
print('Average UCS cost for all data sets (in an 80-day simulation period): ')
print('\n\t' + str(ucsSamples))
print('Average IDA* cost for all data sets (in an 80-day simulation period): ')
print('\n\t' + str(idaSamples))
# output it to a file
global_str_header = 'Accumulated Results for all Parsed files:\n\n'
global_str_header += 'Average UCS cost for all data sets (in an 80-day simulation period): \n'
global_str_header += '\n\t' + str(ucsSamples) + '\n'
global_str_header += '\nAverage IDA* cost for all data sets (in an 80-day simulation period): \n'
global_str_header += '\n\t' + str(idaSamples)
global_str_filename = 'global_results.txt'
writeOutput('', '', global_str_header, global_str_filename)
def writeOutput(ucsStr, idaStr, header, filename):
# ensure we have created the output directory
if not os.path.exists(OUTPUT_PATH):
os.makedirs(OUTPUT_PATH)
# now open it
with open(OUTPUT_PATH + filename, 'w') as f:
# write in the following order
#
# 1) file header
# 2) UCS results
# 3) IDA results
f.write(header)
f.write(ucsStr)
f.write(idaStr)
# close file
f.close()
'''
Progress bar
'''
def update_progress(amtDone):
#print(amtDone)
#sys.stdout.write('\r[{0}] {1}%'.format('#'*(progress/10), progress))
print("\rProgress: [{0:50s}] {1:.1f}%".format('#' * int(amtDone * 50), amtDone * 100))
sys.stdout.flush()
'''
Our main function
'''
def main(bench, files):
# by definition
global DAYS_RANGE_MAX
global OUTPUT_PATH
DAYS_RANGE_MAX = 80
OUTPUT_PATH = 'output/'
'''
Check our input and decide what to do
'''
# check if we have to benchmark our software
if(bench is True):
print('Benchmarking program with provided dataset from "dataset/" folder')
processFiles(0, bench)
# parse input and process it
else:
print('Parsing provided files')
processFiles(files, 0)
if __name__ == '__main__':
'''
Library used for easy command line parsing
'''
import argparse
'''
Command line arguments Parser
'''
parser = argparse.ArgumentParser(description='Search for the best possible route between roads based on their traffic level')
group = parser.add_mutually_exclusive_group()
'''
Add mutually exclusive options
'''
group.add_argument('-b','--bench', action='store_true', help='benchmark the software using the provided data-set which is located in the "dataset" folder')
group.add_argument('-f', '--files', nargs='*', help='provide your own files for analysis (separate each one with commas) [ a.txt, b.txt ... ]')
'''
Update the parser
'''
args = parser.parse_args()
'''
Ensure we have the correct input combination
'''
if(args.bench):
print('Got bench')
main(args.bench, 0)
elif(args.files):
print('Got files')
main(0, args.files)
else:
print("Wrong input arguments... please use --help argument")
pass<file_sep>'''
Created on Apr 13, 2013
@author: agrammenos
'''
import os
class fileReader(object):
'''
classdocs
'''
global RANGE_DEPTH
def __init__(self):
'''
Constructor
'''
self.RANGE_DEPTH = 80
'''
This is done due to the fact that the input
files were created using Windows... and I
develop in a posix-compliant OS. This trick
is used to parse the files correctly no matter
the OS we are in.
'''
def getLineDelimiterBasedOnOS(self):
if(os.name == 'nt'):
return '\n'
else:
return '\r\n'
'''
This function filters the input of the file
we just read
'''
def filterInput(self, filedata):
# initialize the delimiters
delim = self.getLineDelimiterBasedOnOS()
sdelim = '; '
# parse Source & Destination Vertex
# Filtering of the Source & Destination (extract it from the two first lines)
destNode = filedata[1].replace('<Destination>','').replace('</Destination>'+delim,'')
srcNode = filedata[0].replace('<Source>', '').replace('</Source>'+delim, '')
#print(srcNode)
#print(destNode)
# initialize our graph
providedRoads = {}
providedCosts = {}
# parse costs & road connections
# use this trick to start from line 3 and onwards
for l in filedata[3:]:
# check if we reached the end
if(l == '</Roads>'+delim):
break;
# if not parse
# split the lines using the delimiter '; '
t = l.split(sdelim)
#print(t)
# get the arithmetic value
t[3] = int(t[3])
# check if it's in our map and if it's
# not add it
if(t[1] not in providedRoads.keys()):
providedRoads[t[1]]= []
if(t[2] not in providedRoads.keys()):
providedRoads[t[2]] = []
# add it to the map that road 0 is linked with
# the other two
providedRoads[t[1]].append((t[0], t[2]))
providedRoads[t[2]].append((t[0], t[1]))
# update the cost for the road
providedCosts[t[0]]=t[3]
# prediction day line number, 6 is padding for non
# actual information lines
predline = len(providedCosts) + 6
# parse predictions
dayPredictions = []
for j in range(self.RANGE_DEPTH):
dayPredictions.append({})
# necessary padding to start from the correct position
for l in filedata[predline+j*(len(providedCosts)+2):]:
# check if we reached the end
if(l == '</Day>'+delim):
break
# split the same way as above
t = l.split(sdelim)
# strip the newlines
t[1] = t[1].strip(delim)
# now check the traffic density and based on
# the given values give the necessary values
if(t[1] == 'heavy'):
# if the traffic is heavy it's 25 % more
# expensive so... it's 1.25
c_cost = 1.25
elif(t[1] == 'low'):
# if the traffic is low it's 10 % less
# expensive than normal so... it's 0.9
c_cost = 0.9
else:
# else we have a normal traffic and a
# normal cost
c_cost = 1.0
# update the day predictions
dayPredictions[j][t[0]] = c_cost
# parse actual day measurements
# in the same manner as above calculate the padding
actualDayline = predline + 2 + 80*(len(providedCosts)+2)
actualDayMeasurements = []
# this is given from definition (the 80)
for j in range(self.RANGE_DEPTH):
actualDayMeasurements.append({})
# necessary padding to start form the correct position
for l in filedata[actualDayline+j*(len(providedCosts)+2):]:
# check if we end
if(l == '</Day>'+delim):
break;
# if not, parse
# same segment as above...
# split using the correct delimiter
t = l.split(sdelim)
# strip newlines
t[1] = t[1].strip(delim)
# now check the traffic density and based on
# the given values give the necessary values
if(t[1] == 'heavy'):
# if the traffic is heavy it's 25 % more
# expensive so... it's 1.25
c_cost = 1.25
elif(t[1] == 'low'):
# if the traffic is low it's 10 % less
# expensive than normal so... it's 0.9
c_cost = 0.9
else:
# else we have a normal traffic and a
# normal cost
c_cost = 1.0
# update the costs
actualDayMeasurements[j][t[0]] = c_cost
#print(providedRoads)
# finally return
return (destNode, srcNode, providedRoads, providedCosts, dayPredictions, actualDayMeasurements)
'''
This function reads a file we have as an input
'''
def readInputFile(self, filename, verbose):
#print('Reading Input files')
# this is the files tuple, check it's size
if filename == []:
return
# try to open it
print(filename)
with open(filename, 'r') as fstream:
# and... read it.
filedata = fstream.readlines()
# close stream, since we are done
fstream.closed
# return this in the main program
return self.filterInput(filedata)
#print(filedata)
<file_sep>TrafficRoadCalculation
======================
This is a solver for finding the shortest path to work taking in account the Traffic Costs that each of
the available roads have (based on their traffic levels). The software implements two algorithms in order
to find a solution to the problem:
* UCS: Uniform-Cost Search
* IDA*: Iterative Deepening A*
The IDA* heuristic function is the UCS itself, resulting in a more Dijkstra-like algorithm for traversing
the graph. It also results in a much higher complexity of the IDA* algorithm while having little gain in
the actual generated cost.
Finally the format which our dataset was provided was not very good, nor intuitive but that was out of
my hands and had to deal with it.
Enjoy the code.
Peace out!
<file_sep>'''
Created on Apr 14, 2013
@author: agrammenos
'''
import searchProblem
import random
class graphBuilder(searchProblem.GeneralSearchProblem):
'''
classdocs
'''
def __init__(self, searchData, day):
'''
Constructor
initialize the class using the data
We initialize the nodes of our graph based on
our data as well as store the start/target
vertices
'''
# if we visited a node
self.visited = 0
'''
Based on our file reads
'''
self.startVertex = searchData[0]
self.goalVertex = searchData[1]
self.inputRoads = searchData[2]
self.inputRoadCost = searchData[3]
self.inputEstimationCosts = searchData[4]
self.inputActualCosts = searchData[5]
# days passed
self.day = day
# prob
self.defProb = 0.6
'''
Function that returns the Start Vertex
'''
def getStartVertex(self):
return(self.startVertex)
'''
Function that returns True if we have
reached our goal
'''
def goal_test(self, currentState):
return(currentState == self.goalVertex)
'''
Function that returns the Goal Vertex
'''
def goalVertexTest(self):
return(self.goalVertex)
'''
Function that builds up our successors based
on a given state
'''
def successorBuilder(self, currentState):
c = self.inputEstimationCosts[self.day]
successors = []
for sucAction, sucState in self.inputRoads[currentState]:
cost = self.inputRoadCost[sucAction]*c[sucAction]
successors.append((sucState, sucAction, cost))
# set expanded flag
self.setExpanded()
return successors
'''
This sets the provided node expanded status to 1
'''
def setExpanded(self):
self.visited += 1
'''
Calculates the cost of edges in our graph
'''
def GetPathCost(self, actions, sflag = False):
c = []
cost = 0
# no actions to make, return a very large value
if(actions == None):
return 1000000
# loop through available actions in our bucket
for action in actions:
# calculation of actual costs
if(sflag is True):
c = self.inputActualCosts[self.day]
cost += self.inputRoadCost[action]*c[action]
# calculation of probabilistic costs
else:
c = self.inputEstimationCosts[self.day]
c_weight = self.distributeCoef(c[action], self.defProb)
cost += self.inputRoadCost[action]*c_weight
# finally return
return cost
'''
This distributes the probabilities and creates the necessary
weights in our graph
'''
def distributeCoef(self, coef, probability):
# generate a random number [0, 1]
prob = random.random()
# high traffic prob
if(coef == 1.25):
p1 = 1
p2 = 1.25
# normal traffic
elif(coef == 1):
p1 = 0.9
p2 = 1.25
# low traffic
else:
p1 = 1
p2 = 1.25
# this is to decide the actual traffic probs
if(prob > (1+probability)/2):
return p2
else:
return p1
<file_sep>'''
Created on Apr 13, 2013
@author: agrammenos
'''
from util import SuperPriorityQueue
'''
We use the AIMA-Python Code approach for our Search problem,
that is create a General-Abstract class for the problems we
want to solve and then derive from that one.
'''
class GeneralSearchProblem:
"""The abstract class for a formal problem. You should subclass this and
implement the method successor, and possibly __init__, goal_test, and
path_cost. Then you will create instances of your subclass and solve them
with the various search functions."""
#def __init__(self, initial, goal):
# """The constructor specifies the initial state, and possibly a goal
# state, if there is a unique goal. Your subclass's constructor can add
# other arguments."""
# self.initial = initial; self.goal = goal
def successorBuilder(self, currentState):
"""Given a state, return a sequence of (action, state) pairs reachable
from this state. If there are many successors, consider an iterator
that yields the successors one at a time, rather than building them
all at once. Iterators will work fine within the framework."""
def getStartVertex(self):
"""
This returns the start state of our graph
"""
def goal_test(self, state):
"""Return True if the state is a goal. The default method compares the
state to self.goal, as specified in the constructor. Implement this
method if checking against a single self.goal is not enough."""
#return state == self.goal
def goalVertexTest(self):
'''
This is nice
'''
def GetPathCost(self, bucketOfActions):
"""Return the cost of a solution path that arrives at state2 from
state1 via action, assuming cost c to get up to state1. If the problem
is such that the path doesn't matter, this function will only look at
state2. If the path does matter, it will consider c and maybe state1
and action. The default method costs 1 for every step in the path."""
def setExpanded(self):
"""For optimization problems, each state has a value. Hill-climbing
and related algorithms try to maximize this value."""
'''
Search Algorithms General Functions
'''
'''
This is the code for Uniform-Cost Search function.
This was derived from Wikipedia code is in the
corresponding article. Translation from pseudocode
to Python was trivial
'''
def ucs(searchProblem, currentState = None):
# Create our queue and set
pq = SuperPriorityQueue()
ucsSet = set()
# now initialize our problem
if(currentState == None):
pq.put((searchProblem.getStartVertex(),[]), 0)
else:
pq.put((currentState,[]), 0)
# Searching
while (not pq.empty()):
vertex = pq.get()
# check the if we have reached our destination
if(searchProblem.goal_test(vertex[0])):
# return the destination vertex
return vertex[1]
# if not, search
# first check if our vertex is in the set
if(vertex[0] not in ucsSet):
# if not add it
ucsSet.add(vertex[0])
# and run a for loop for each of the vertex successors
# and calculate the costs
for successorVertices in searchProblem.successorBuilder(vertex[0]):
bucketOfActions = list(vertex[1])
bucketOfActions.append(successorVertices[1])
# actual cost calculation
pr = searchProblem.GetPathCost(bucketOfActions)
# put it back in the queue
pq.put((successorVertices[0],bucketOfActions), pr)
'''
This method is used due to a hint that the Professor gave us;
we use the UCS search as the heuristic function of our IDA*
'''
def ucsBasedIDAHeuristic(currentState, searchProblem = None):
'''
We take each 'snapshot' of IDA* and apply a new UCS
on that 'snapshot' in order to get the heuristic costs
This is quite slow as in each turn of the algorithm we
have to apply both IDA* and UCS at the same time.
It is also expected to give approximately the same results
(since we are using UCS to grade our paths)
'''
# we search here using UCS
bucketOfPosibleActions = ucs(searchProblem, currentState)
# and here we return the path costs calculated using the
# formula above
return searchProblem.GetPathCost(bucketOfPosibleActions)
'''
This is the wrapper of the IDA* algorithm that is used to call
the actual recursion
Code was derived from Wikipedia IDA* algorithm pseudocode,
translation to Python was trivial
Heuristic function used is the UCS algorithm
'''
def idaStarCallback(searchProblem, hf=ucsBasedIDAHeuristic):
# get our initial state
snode = (searchProblem.getStartVertex(), [])
# now pass it to our heuristic function to find the
# cutoff point
cutoff = hf(snode[0], searchProblem)
# our starting vertex
vertex = [None,]
# run the loop
while vertex[0] == None:
# vertex, cost tuple return from idaStar
(vertex, cost) = idaStar(searchProblem, snode, hf, cutoff)
# update the cutoff point
cutoff = cost
# check if we reached the end
if(searchProblem.goal_test(vertex[0])):
# if so return the tuple of (vertex,cost)
# that is returned by ida*
return(vertex[1], cost)
'''
This function returns the costs of the edges
'''
def pf(searchProblem, snode, hf):
# the f = g + h
g = searchProblem.GetPathCost(snode[1])
h = hf(snode[0], searchProblem)
# now return it
return (g+h)
'''
Actual idaStar function. Takes as parameters
the required search problem, the starting vertex
the heuristic function [which we defined above as
the UCS] as well as the cutoff limit
'''
def idaStar(searchProblem, snode, hf, cutoff):
# get the costs
costs = pf(searchProblem, snode, hf)
# check what we got
# if our costs are greater than our cutoff value
# just return
if(costs > cutoff):
return((None, snode[1]), costs)
# now check if we are at a goal state
if(searchProblem.goal_test(snode[0])):
# return the node and the cost
return(snode,costs)
# if not, continue searching
l = 1000000 # very large
# now loop
for successor in searchProblem.successorBuilder(snode[0]):
# our bucket of actions
bucket = list(snode[1])
bucket.append(successor[1])
# now pass it
(sucNode, sucCost) = idaStar(searchProblem, (successor[0], bucket), hf, cutoff)
# check if we are at the end
if(searchProblem.goal_test(sucNode[0])):
# if so return the required tuple
return(sucNode, sucCost)
# update the limit
l = min(l, sucCost)
# now return the tuple with the updated node and limit
return((None, snode[1]), l)
| ef9380e046ad55170537a463ad1dd02a0514b663 | [
"Markdown",
"Python"
] | 6 | Python | andylamp/TrafficRoadCalculation | 9161ade6ea322036e5e984258f286f4f87a923d1 | edbfd0e3895c0f76b0e8ee09f86394bea7133752 |
refs/heads/master | <file_sep>using System.Collections.Generic;
namespace ModereTest.Models
{
public class ClassStudents
{
public Class Class { get; set; }
public IEnumerable<Student> Students { get; set; }
}
}
<file_sep>using DataAccess.Entities;
using DataAccess.Infrastructure.Interfaces;
using DataAccess.Repositories.Interfaces;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace DataAccess.Repositories
{
public class StudentRepository : Repository<Class>, IStudentRepository
{
public StudentRepository(IConnectionFactory connectionFactory) : base(connectionFactory)
{
}
public async Task<Student> GetStudentAsync(int studentId)
{
throw new NotImplementedException();
}
public async Task<IEnumerable<Student>> GetStudentsAsync()
{
throw new NotImplementedException();
}
}
}
<file_sep>using DataAccess.Infrastructure.Interfaces;
using DataAccess.Repositories.Interfaces;
using System;
using System.Collections.Generic;
using System.Data;
namespace DataAccess.Repositories
{
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
private readonly IDbConnection connection;
public Repository(IConnectionFactory connectionFactory)
{
connection = connectionFactory.GetConnection();
}
public IDbConnection Connection => connection;
public void Add(TEntity entity)
{
throw new NotImplementedException();
}
public void Delete(TEntity entity)
{
throw new NotImplementedException();
}
public void Dispose()
{
if (connection != null)
{
connection.Dispose();
}
}
public TEntity Get(int Id)
{
throw new NotImplementedException();
}
public IEnumerable<TEntity> GetAll()
{
throw new NotImplementedException();
}
public void Update(TEntity entity)
{
throw new NotImplementedException();
}
}
}
<file_sep>using System.Data;
namespace DataAccess.Infrastructure.Interfaces
{
public interface IConnectionFactory
{
IDbConnection GetConnection();
}
}
<file_sep>using Dapper;
using DataAccess.Entities;
using DataAccess.Infrastructure.Interfaces;
using DataAccess.Repositories.Interfaces;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace DataAccess.Repositories
{
public class ClassRepository : Repository<Class>, IClassRepository
{
public ClassRepository(IConnectionFactory connectionFactory) : base(connectionFactory)
{
}
public async Task<Class> GetClassAsync(int classId)
{
// Would normally put this in a stored procedure:
var query = "SELECT * FROM dbo.Class WHERE ClassId = @classId";
var param = new DynamicParameters();
param.Add("@classId", classId);
var cls = await SqlMapper.QuerySingleOrDefaultAsync<Class>(Connection, query, param,
commandType: System.Data.CommandType.Text);
return cls;
}
public Task<IEnumerable<Class>> GetClasses()
{
throw new NotImplementedException();
}
}
}
<file_sep>using ModereTest.Models;
using System.Threading.Tasks;
namespace ModereTest.Services.Interfaces
{
public interface IClassService
{
Task<ClassStudents> GetClassRegisterByClassIdAsync(int classId);
}
}
<file_sep>using DataAccess.Repositories.Interfaces;
using ModereTest.Models;
using ModereTest.Services.Interfaces;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ModereTest.Services
{
public class ClassService : IClassService
{
private readonly IClassRegisterRepository classRegisterRepository;
private readonly IClassRepository classRepository;
public ClassService(IClassRegisterRepository classRegisterRepository, IClassRepository classRepository)
{
this.classRegisterRepository = classRegisterRepository;
this.classRepository = classRepository;
}
public async Task<ClassStudents> GetClassRegisterByClassIdAsync(int classId)
{
await ClassShouldExistAsync(classId);
var list = await classRegisterRepository.GetAllStudentsByClassAsync(classId);
if (list.Any())
{
// Would normally use a library like AutoMapper for these kinds of mapping operations,
// but this is so simple in this case it was not deemed practical
var students = new List<Student>();
foreach (var classRegister in list)
{
students.Add(new Student
{
StudentId = classRegister.StudentId,
FirstName = classRegister.FirstName,
LastName = classRegister.LastName
});
}
var classStudents = new ClassStudents
{
Class = new Class
{
ClassId = classId,
ClassName = list.First().ClassName
},
Students = students
};
return classStudents;
}
return null;
}
private async Task ClassShouldExistAsync(int classId)
{
var cls = await classRepository.GetClassAsync(classId);
if (cls == null)
{
throw new InvalidClassException(classId);
}
}
}
}
<file_sep>using DataAccess.Entities;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace DataAccess.Repositories.Interfaces
{
public interface IClassRepository
{
Task<IEnumerable<Class>> GetClasses();
Task<Class> GetClassAsync(int classId);
}
}
<file_sep>using Dapper;
using DataAccess.Entities;
using DataAccess.Infrastructure.Interfaces;
using DataAccess.Repositories.Interfaces;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace DataAccess.Repositories
{
public class ClassRegisterRepository : Repository<ClassRegister>, IClassRegisterRepository
{
public ClassRegisterRepository(IConnectionFactory connectionFactory) : base(connectionFactory)
{
}
public async Task<IEnumerable<ClassRegister>> GetAllStudentsByClassAsync(int classId)
{
var query = "GetClassRegisterByClassId";
var param = new DynamicParameters();
param.Add("@classId", classId);
var registeredStudents = await SqlMapper.QueryAsync<ClassRegister>(Connection, query, param,
commandType: System.Data.CommandType.StoredProcedure);
return registeredStudents;
}
}
}
<file_sep>using DataAccess.Entities;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace DataAccess.Repositories.Interfaces
{
public interface IClassRegisterRepository
{
Task<IEnumerable<ClassRegister>> GetAllStudentsByClassAsync(int classId);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
namespace DataAccess.Repositories.Interfaces
{
public interface IRepository<TEntity> : IDisposable where TEntity : class
{
IDbConnection Connection { get; }
TEntity Get(int Id);
IEnumerable<TEntity> GetAll();
void Add(TEntity entity);
void Delete(TEntity entity);
void Update(TEntity entity);
}
}
<file_sep>using DataAccess.Entities;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace DataAccess.Repositories.Interfaces
{
public interface IStudentRepository
{
Task<IEnumerable<Student>> GetStudentsAsync();
Task<Student> GetStudentAsync(int studentId);
}
}
<file_sep>using System;
namespace ModereTest.Services
{
public class InvalidClassException : Exception
{
public InvalidClassException(int classId) : base($"Class does not exist: {classId}")
{
}
}
}
<file_sep>using DataAccess.Infrastructure;
using DataAccess.Infrastructure.Interfaces;
using DataAccess.Repositories;
using DataAccess.Repositories.Interfaces;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using ModereTest.Services;
using ModereTest.Services.Interfaces;
using System.Data.Common;
using System.Data.SqlClient;
namespace ModereTestApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient", SqlClientFactory.Instance);
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "ModereTestApi", Version = "v1" });
});
services.AddMvc();
services.AddScoped<IClassService, ClassService>();
services.AddTransient<IClassRepository, ClassRepository>();
services.AddTransient<IStudentRepository, StudentRepository>();
services.AddTransient<IClassRegisterRepository, ClassRegisterRepository>();
services.AddSingleton<IConnectionFactory, SqlConnectionFactory>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ModereTestApi v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
//app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
<file_sep>namespace DataAccess.Entities
{
public class ClassRegister
{
public int ClassId { get; set; }
public string ClassName { get; set; }
public int StudentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
<file_sep>using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ModereTest.Services;
using ModereTest.Services.Interfaces;
using System;
using System.Threading.Tasks;
namespace ModereTestApi.Controllers
{
[Produces("application/json")]
[ApiController]
[Route("[controller]")]
public class ClassController : ControllerBase
{
private readonly ILogger<ClassController> logger;
private readonly IConfiguration configuration;
private readonly IClassService classService;
public ClassController(IConfiguration configuration, ILogger<ClassController> logger, IClassService classService)
{
this.configuration = configuration;
this.logger = logger;
this.classService = classService;
}
[HttpGet]
[Route("students/{classId}")]
public async Task<IActionResult> GetStudentsByClassIdAsync(int classId)
{
try
{
var list = await classService.GetClassRegisterByClassIdAsync(classId);
if (list != null)
{
return Ok(list);
}
return NotFound();
}
catch (Exception e)
{
if (e is InvalidClassException)
{
return BadRequest(e.Message);
}
throw;
}
}
}
}
<file_sep>using DataAccess.Infrastructure.Interfaces;
using Microsoft.Extensions.Configuration;
using System.Data;
using System.Data.Common;
namespace DataAccess.Infrastructure
{
public class SqlConnectionFactory : IConnectionFactory
{
private readonly string connectionString;
public SqlConnectionFactory(IConfiguration configuration)
{
connectionString = configuration.GetConnectionString("Modere");
}
public IDbConnection GetConnection()
{
var factory = DbProviderFactories.GetFactory("Microsoft.Data.SqlClient");
var connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
connection.Open();
return connection;
}
}
}
| a5528a8ae8d76bf8fc82ddd0b4e26c2b70b9510b | [
"C#"
] | 17 | C# | oleboy/ModereTestApi | 8190e47819b963a8f9a25e426b8e584f82d3d515 | 1b6a8d0c9647da5fc688be0b46789b4e69c4b6b3 |
refs/heads/master | <repo_name>patoCode/doctor-speaker<file_sep>/app/Http/Controllers/DiagnosticoController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class DiagnosticoController extends Controller
{
public function index(){
return view('pacientes.diagnostico');
}
public function create(){
return view('pacientes.menu-areas');
}
public function consulta($area){
switch($area){
case 'cabeza':
$dolores = array('0' => 1,'dolor2'=>2 );
return view('pacientes.formularios.cabeza')->with('dolores', $dolores);
}
}
public function store(Request $req)
{
}
}
<file_sep>/routes/web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', function () {
return view('home');
});
Route::get('diagnostico',"DiagnosticoController@index");
Route::get('diagnostico/menu',"DiagnosticoController@create");
Route::get('consulta/{area}',"DiagnosticoController@consulta"); | de8ba0b8515a4a418494c9a998ab3a0f2b50bafe | [
"PHP"
] | 2 | PHP | patoCode/doctor-speaker | 4bd6a0c1f0d52d30b300deb5c2c600b9fd6bdb54 | 9c4223974daced4ea25cc4d37f54bdceceaca34b |
refs/heads/master | <repo_name>pappu116/loginreact<file_sep>/src/component/Shear/Footer/Footer.js
import { Grid } from '@mui/material';
import React from 'react';
import './Footer.css'
import Button from '@mui/material/Button';
const Footer = (props) => {
return (
<div className="footer">
<Grid container
direction="row"
justifyContent="space-evenly"
alignItems="center">
<Grid item xs>
<a href="#">contact <br /> PrivateDelight</a>
</Grid>
<Grid item xs>
<a href="#">Blog</a>
</Grid>
<Grid item xs>
<a href="#">Twitter</a>
</Grid>
<Grid item xs>
<a href="#">Locations</a>
</Grid>
<Grid item xs>
<a href="#">Privacy policy</a>
</Grid>
<Grid item xs>
<a href="#">Terms</a>
</Grid>
<Grid item xs>
<Button variant="contained">Help/FeedBack</Button>
</Grid>
</Grid>
<p>© {new Date().getFullYear()} PrivateDelights.ch</p>
</div>
);
};
export default Footer;<file_sep>/src/component/Shear/AppBar/AppNav.js
import React from 'react';
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import SearchIcon from '@mui/icons-material/Search';
import LocationOnIcon from '@mui/icons-material/LocationOn';
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
import Box from '@mui/material/Box';
import '../../login/Login.css'
const AppNav = (props) => {
return (
<div>
<Box sx={{ flexGrow: 1 }}>
<AppBar style={{backgroundColor:"white",color:"#637EF6"}} position="static">
<Toolbar>
<IconButton
size="large"
edge="start"
color="inherit"
aria-label="menu"
sx={{ mr: 2 }}
>
</IconButton>
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
PrivateDelight
</Typography>
<Button color="inherit"><LocationOnIcon style={{color:"#757575"}}/> <a href="#">Location</a></Button>
<Button color="inherit"> <SearchIcon style={{color:"#757575"}} /> <a href="#">Search</a></Button>
<Button color="inherit"><AccountCircleIcon style={{color:"#757575"}}/> <a href="#">Login</a> </Button>
</Toolbar>
</AppBar>
</Box>
</div>
);
};
export default AppNav;<file_sep>/src/component/Home/Home.js
import React from 'react';
import SignUp from '../SignUp/SignUp';
import Footer from '../Shear/Footer/Footer';
import Login from './../login/Login';
import AppNav from './../Shear/AppBar/AppNav';
import Nid from '../NID/Nid';
const Home = (props) => {
var login = true;
return (
<div>
<AppNav/>
<Nid/>
{/* {
login?<Login/>:<SignUp/>
} */}
<Footer/>
</div>
);
};
export default Home; | 8f263db557be077524943d1ec4812efe5903a5a2 | [
"JavaScript"
] | 3 | JavaScript | pappu116/loginreact | 5505c8d9a8020a3f55b0ee9932c3fd31d81cd679 | f546bb2db570e09bc13d9d22f7209afe883aab8e |
refs/heads/master | <repo_name>mokacao/bookmarklets<file_sep>/zoom_text.js
javascript: (function() {
var p = document.getElementsByTagName('*');
for (i = 0; i < p.length; i++) {
if (p[i].style.fontSize) {
var s = parseInt(p[i].style.fontSize.replace("px", ""));
} else {
var s = 17;
}
s += 2;
p[i].style.fontSize = s + "px"
}
})();<file_sep>/highlighter.js
javascript: (function() {
var count = 0, text, dv;
text = prompt("Search phrase:", "");
if (text == null || text.length == 0)return;
hlColor = prompt("Color:", "yellow");
dv = document.defaultView;
function searchWithinNode(node, te, len) {
var pos, skip, spannode, middlebit, endbit, middleclone;
skip = 0;
if (node.nodeType == 3) {
pos = node.data.toUpperCase().indexOf(te);
if (pos >= 0) {
spannode = document.createElement("SPAN");
spannode.style.backgroundColor = hlColor;
middlebit = node.splitText(pos);
endbit = middlebit.splitText(len);
middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
++count;
skip = 1;
}
} else if (node.nodeType == 1 && node.childNodes && node.tagName.toUpperCase() != "SCRIPT" && node.tagName.toUpperCase != "STYLE") {
for (var child = 0; child < node.childNodes.length; ++child) {
child = child + searchWithinNode(node.childNodes[child], te, len);
}
}
return skip;
}
window.status = "Searching for '" +text + "'...";
searchWithinNode(document.body, text.toUpperCase(), text.length);
window.status = "Found " +count + " occurrence" + (count == 1?"": "s") + " of '" +text + "'.";
})(); | f0ff0ea85f72404c0887ef914c9b4e1da07e6825 | [
"JavaScript"
] | 2 | JavaScript | mokacao/bookmarklets | 3f97848ede46460d65fbaa1b1065464734f1c3f1 | 219a428a2b16718a235e34dc0fdfaa84e936a272 |
refs/heads/master | <file_sep>package automatoer;
public class Validacao {
public boolean validateAlphabet(String value) {
boolean returnValue = false;
char[] fragmentedValue = value.toCharArray();
for (int i = 0; i < fragmentedValue.length; i++) {
if (Character.isAlphabetic(fragmentedValue[i])) {
returnValue = true;
break;
}
}
return returnValue;
}
}
| 77c7f6afb394b4aab51ce9666f67ac19af6fc5cc | [
"Java"
] | 1 | Java | MatheusBrandalise/AutomatoER | 3794cf084bb8a166a12a5138c75fe77e3c1987e8 | e981b835279d73e7c98ec2ec01dcc82ab6cda95b |
refs/heads/develop | <repo_name>sobakasu/google_web_translate<file_sep>/lib/google_web_translate/api.rb
require 'execjs'
require 'json'
module GoogleWebTranslate
# interface to the google web translation api
class API
def initialize(options = {})
@dt = options[:dt] || DEFAULT_DT
@token_ttl = options[:token_ttl] || DEFAULT_TOKEN_TTL
@debug = options[:debug]
@http_client = options[:http_client] || HTTPClient.new(options)
@rate_limit = options[:rate_limit] || DEFAULT_RATE_LIMIT
end
def translate(string, from, to)
data = fetch_translation(string, from, to)
Result.new(data)
end
def languages
@languages ||= begin
html = fetch_main
html.scan(/\['(\w{2})','(\w{2})'\]/).flatten.uniq.sort
end
end
private
URL_MAIN = 'https://translate.google.com'.freeze
TRANSLATE_PATH = '/translate_a/single'.freeze
DEFAULT_DT = %w[at bd ex ld md qca rw rm ss t].freeze
DEFAULT_TOKEN_TTL = 3600
DEFAULT_RATE_LIMIT = 5
def fetch_translation(string, from, to)
debug('getting next server')
server = ServerList.next_server(@rate_limit)
debug("using server #{server}")
json = fetch_url_body(translate_url(server, string, from, to))
# File.write("response.json", json) if debug?
debug("response: #{json}")
JSON.parse(json)
end
def fetch_url_response(url)
@http_client.get(url.to_s)
end
def fetch_url_body(url)
uri = URI.parse(url)
uri = URI.join(URL_MAIN, url) if uri.relative?
debug("fetch #{uri}")
response = fetch_url_response(uri)
response.body
end
def valid_token?
@token_updated_at && Time.now - @token_updated_at < @token_ttl
end
def fetch_main(options = {})
@html = nil if options[:no_cache]
@html ||= fetch_url_body(URL_MAIN)
end
def fetch_desktop_module(html)
html =~ /([^="]*desktop_module_main.js)/
url = Regexp.last_match(1)
raise 'unable to find desktop module' unless url
fetch_url_body(url)
end
def munge_module(js)
js.gsub(/((?:var\s+)?\w+\s*=\s*\w+\.createElement.*?;)/) do |_i|
'return "";'
end
end
def compile_js(html)
desktop_module_js = munge_module(fetch_desktop_module(html))
window_js = File.read(File.join(__dir__, '..', 'js', 'window.js'))
js = window_js + desktop_module_js
# File.write('generated.js', js) if debug?
@tk_function = detect_tk_function(desktop_module_js)
debug("detected tk function: #{@tk_function}")
ExecJS.compile(js)
end
def detect_tk_function(js)
js =~ /translate_tts.*,\s*(\w+)\(.*\)/
Regexp.last_match(1) || 'vq'
end
def update_token
# download main page
html = fetch_main(no_cache: true)
# extract tkk from html
@tkk = extract_tkk(html)
# compile desktop module javascript
@js_context = compile_js(html)
@token_updated_at = Time.now
end
def tk(string)
update_token unless valid_token?
tk = @js_context.call('generateToken', @tk_function, @tkk, string)
(tk.split('=') || [])[1]
end
def tk_js
File.read(File.join(__dir__, 'google_web.js'))
end
def extract_tkk(html)
raise 'TKK not found' unless html =~ /TKK=eval\('(.*?)'\);/
tkk_code = Regexp.last_match(1)
# tkk_code = Translatomatic::StringEscaping.unescape(tkk_code)
tkk_code = StringEscaping.unescape(tkk_code)
debug("tkk code unescaped: #{tkk_code}")
tkk = ExecJS.eval(tkk_code)
# tkk = context.call(nil)
debug("evaluated tkk: #{tkk}")
tkk
end
def translate_url(server, string, from, to)
tk = tk(string)
debug("tk: #{tk}")
query = {
sl: from, tl: to, ie: 'UTF-8', oe: 'UTF-8',
q: string, dt: @dt, tk: tk,
# not sure what these are for
client: 't', hl: 'en', otf: 1, ssel: 4, tsel: 6, kc: 5
}
url = "https://#{server.host}" + TRANSLATE_PATH
uri = URI.parse(url)
uri.query = URI.encode_www_form(query)
uri.to_s
end
def debug(msg)
puts msg if debug?
end
def debug?
@debug
end
end
end
<file_sep>/lib/js/window.js
var window = {
jstiming: {
load: {
tick: function() {}
}
}
};
var navigator = {};
var document = {};
function setWindowProperty(key, value) {
window[key] = value;
}
function generateToken(tk_function, tkk, string) {
setWindowProperty('TKK', tkk);
var fn = eval(tk_function);
return fn(string);
}
<file_sep>/spec/google_web_translate/server_list_spec.rb
RSpec.describe GoogleWebTranslate::ServerList do
context '#servers' do
it 'returns a list of servers' do
servers = server_list
# p servers
expect(servers).to be
expect(servers.length).to be > 1
end
end
context '#next_server' do
it 'cycles through all available servers' do
count = server_list.length
last_server = nil
(count * 2).times do
server = next_server
# puts "server: #{server}"
expect(server).to be
expect(server.ip).to_not eq(last_server.ip) if last_server
last_server = server
end
end
it 'delays according to a rate limit' do
count = server_list.length
count.times { next_server }
now = Time.now
expected_delay = 3
next_server(expected_delay)
actual_delay = Time.now - now
expect(actual_delay).to be_within(0.5).of(expected_delay)
end
end
def server_list
described_class.servers
end
def next_server(rate_limit = nil)
described_class.next_server(rate_limit)
end
end
<file_sep>/Gemfile
source 'https://rubygems.org'
git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
def gem_installed?(args)
name, *version = *args
dependency = Gem::Dependency.new(name, *version)
specs = dependency.matching_specs
specs && !specs.empty?
end
def optional_gem(*args)
gem(*args) if gem_installed?(args)
end
# database adapters
optional_gem 'therubyracer', platform: :ruby
optional_gem 'therubyrhino', platform: :jruby
# optional c extensions
optional_gem 'concurrent-ruby-ext', platform: :ruby
# Specify your gem's dependencies in google-web-translate.gemspec
gemspec
<file_sep>/lib/google_web_translate/http_client.rb
require 'net/http'
module GoogleWebTranslate
# HTTP client functionality
class HTTPClient
def self.user_agent
gem_version = "GoogleWebTranslate/#{VERSION}"
platform_version = "(#{RUBY_PLATFORM}) #{RUBY_ENGINE}/#{RUBY_VERSION}"
gem_version + ' ' + platform_version
end
def initialize(options = {})
@user_agent = options[:user_agent] || self.class.user_agent
end
def get(url)
uri = URI.parse(url)
request = Net::HTTP::Get.new(uri)
request['User-Agent'] = @user_agent
options = { use_ssl: uri.scheme == 'https' }
Net::HTTP.start(uri.host, uri.port, options) do |http|
http.request(request)
end
end
end
end
<file_sep>/bin/google_web_translate
#!/usr/bin/env ruby
require 'bundler/setup'
require 'google_web_translate'
require 'google_web_translate/cli'
GoogleWebTranslate::CLI.start(ARGV.dup.unshift('translate'))
<file_sep>/lib/google_web_translate/cli.rb
require 'thor'
require 'pp'
module GoogleWebTranslate
# Command line interface
class CLI < Thor
desc 'string from to', 'translate a string from one language to another'
method_option :dt, type: :array, desc: 'data types'
def translate(string, from, to)
api_options = { debug: ENV['DEBUG'] }
api_options[:dt] = options[:dt] if options[:dt]
api = API.new(api_options)
result = api.translate(string, from, to)
pp result.to_h
end
end
end
<file_sep>/README.md
[](http://www.rubydoc.info/gems/google_web_translate)
[](https://badge.fury.io/rb/google_web_translate)
[](https://travis-ci.org/sobakasu/google_web_translate)
# GoogleWebTranslate
Translates text using the Google translate web interface.
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'google_web_translate'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install google_web_translate
## Usage
### Command line
google_web_translate "Hello" en de
### API
api = GoogleWebTranslate::API.new
result = api.translate("Hello", "en", "de")
puts result.translation
supported_languages = api.languages
## Development
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
## Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/sobakasu/google_web_translate. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
## License
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
## Code of Conduct
Everyone interacting in the GoogleWebTranslate project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/sobakasu/google_web_translate/blob/master/CODE_OF_CONDUCT.md).
<file_sep>/lib/google_web_translate/server.rb
module GoogleWebTranslate
# @private
SERVER_ATTRIBUTES = %i[host ip resolved_at last_used_at
counter available].freeze
Server = Struct.new(*SERVER_ATTRIBUTES) do
def to_json(*args)
result = {}
each_pair { |key, value| result[key] = value }
result.to_json(args)
end
end
end
<file_sep>/lib/google_web_translate/result.rb
module GoogleWebTranslate
# Translation results
class Result
attr_reader :raw
# @private
DATA_INDICES = {
translation: [0, 0, 0], # dt:t
alternatives: [5, 0, 2], # dt:at
dictionary: [1], # dt: bd
synonyms: [11], # dt:ss
definitions: [12, 0], # dt:md
examples: [13, 0], # dt:ex
see_also: [14, 0], # dt:rw
}.freeze
DATA_INDICES.each_key { |key| attr_reader key }
def initialize(data)
@raw = data
@keys = []
@properties = {}
DATA_INDICES.each do |key, indices|
indices = indices.dup
extract_data(key, *indices)
end
@alternatives = @alternatives.collect { |i| i[0] } if @alternatives
@keys.each { |key| @properties[key] = instance_variable_get("@#{key}") }
end
def to_h
@properties
end
private
def extract_data(name, *indices)
value = array_value(@raw, *indices)
return if value.nil?
instance_variable_set("@#{name}", value)
@keys.push(name)
end
def array_value(array, *indices)
return nil if array.nil?
index = indices.shift
value = array[index]
return value if indices.empty?
array_value(value, *indices)
end
end
end
<file_sep>/spec/google_web_translate/api_spec.rb
RSpec.describe GoogleWebTranslate::API do
it 'generates the correct token' do
# this test only works with fixture data
skip('live network test') if allow_net_connections?
api = described_class.new(debug: ENV['DEBUG'])
stub_requests
string = 'hello'
expected_token = '<PASSWORD>'
token = api.send(:tk, string)
expect(token).to eq(expected_token)
end
it 'translates a string' do
api = described_class.new(debug: ENV['DEBUG'])
stub_requests
string = 'right'
from = 'en'
to = 'de'
result = api.translate(string, from, to)
expect(result.translation).to eq('Recht')
expect(result.alternatives).to eq(%w[Recht richtig rechts])
end
it 'translates two strings' do
api = described_class.new(debug: ENV['DEBUG'])
stub_requests
strings = %w[right right]
from = 'en'
to = 'de'
strings.each do |string|
result = api.translate(string, from, to)
expect(result.translation).to eq('Recht')
expect(result.alternatives).to eq(%w[Recht richtig rechts])
end
end
it 'returns a list of supported languages' do
api = described_class.new(debug: ENV['DEBUG'])
stub_requests
result = api.languages
expect(result).to eq(%w[af am ar az be bg bn bs ca co cs cy da de el en eo es et eu fa fi fr fy ga gd gl gu ha hi hr ht hu hy id ig is it iw ja jw ka kk km kn ko ku ky la lb lo lt lv mg mi mk ml mn mr ms mt my ne nl no ny or pa pl ps pt ro ru rw sd si sk sl sm sn so sq sr st su sv sw ta te tg th tk tl tr tt ug uk ur uz vi xh yi yo zh zu])
end
def stub_requests
if allow_net_connections?
WebMock.allow_net_connect!
return
end
html_response = fixture_read('main.html')
json_response = fixture_read('single.json')
desktop_js_response = fixture_read('desktop_module_main.js')
# first request: gets main html
stub_url_request(described_class::URL_MAIN, html_response)
# second request: gets main desktop js
stub_url_request(/desktop_module_main.js/, desktop_js_response)
# third request: to google api
stub_url_request(/translate_a/, json_response)
end
def stub_url_request(url, response_body)
stub_request(:get, url)
.with(headers: test_http_headers)
.to_return(status: 200, body: response_body, headers: {})
end
end
<file_sep>/lib/google_web_translate.rb
require 'google_web_translate/version.rb'
require 'google_web_translate/server.rb'
require 'google_web_translate/server_list.rb'
require 'google_web_translate/string_escaping.rb'
require 'google_web_translate/http_client.rb'
require 'google_web_translate/result.rb'
require 'google_web_translate/api.rb'
<file_sep>/lib/google_web_translate/server_list.rb
require 'concurrent'
require 'resolv'
require 'json'
module GoogleWebTranslate
class ServerList
class << self
def servers
update_servers if @servers.nil?
@servers.dup
end
def next_server(rate_limit = nil)
@mutex ||= Mutex.new
@mutex.synchronize do
@counter ||= 0
@counter += 1
list = servers.sort_by { |i| i.counter || 0 }
server = list[0]
server.counter = @counter
sleep(rate_limit_delay(server, rate_limit))
server.last_used_at = Time.now
server
end
end
private
MAX_TTL = 86_400
def rate_limit_delay(server, rate_limit)
return 0 unless rate_limit && server.last_used_at
delay = rate_limit - (Time.now - server.last_used_at)
delay < 0 || ENV['TEST'] ? 0 : delay
end
def update_servers
server_list = read_server_data
pool = Concurrent::CachedThreadPool.new
# puts "updating #{server_list.length} servers"
server_list.each do |server|
pool.post { update_server(server) }
end
pool.shutdown
pool.wait_for_termination
@servers = unique_servers(server_list)
# puts "#{@servers.length} unique servers found"
save_server_data(server_list)
end
def update_server(server)
now = Time.now.to_i
if server.resolved_at.nil? ||
now - server.resolved_at > MAX_TTL #|| !server.available
server.resolved_at = now
server.ip = resolve_ip(server.host)
end
server.available = true
rescue Resolv::ResolvError
# puts "server #{server.host} is unavailable: #{e}"
server.available = false
end
def data_dir
File.join(__dir__, '..', '..', 'data')
end
def server_data_path
File.join(data_dir, 'server_data.txt')
end
def url_list_path
File.join(data_dir, 'urls.txt')
end
def hostnames
names = []
lines = File.read(url_list_path).split(/[\r\n]+/)
lines.each do |host|
next unless host && !host.empty?
names << "translate.#{host}"
end
names
end
def unique_servers(list)
server_by_ip = {}
list.each do |server|
next unless server.available
server_by_ip[server.ip] = server
end
server_by_ip.values
end
def initial_data
hostnames.collect do |host|
server = Server.new
server.host = host
server
end
end
def read_server_data
return initial_data unless File.exist?(server_data_path)
data = JSON.parse(File.read(server_data_path))
server_list = []
data.each do |entry|
attributes = SERVER_ATTRIBUTES.collect { |i| entry[i.to_s] }
server = Server.new(*attributes)
next unless server.host && !server.host.empty?
server.counter = 0
server_list << server
end
server_list
end
def save_server_data(servers)
File.write(server_data_path, servers.to_json)
end
def resolver
resolver = Resolv::DNS.new
resolver.timeouts = 5
resolver
end
def resolve_ip(host)
resolver.getaddress(host).to_s
end
end
end
end
<file_sep>/spec/spec_helper.rb
require 'simplecov'
SimpleCov.start do
add_filter 'spec'
end
require 'bundler/setup'
require 'webmock/rspec'
include WebMock::API
require 'google_web_translate'
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = '.rspec_status'
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
def fixture_read(path)
File.read(File.join(__dir__, 'fixtures', path))
end
def test_http_headers
{ 'Accept' => '*/*',
'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
'Host' => /translate.google.*/,
'User-Agent' => GoogleWebTranslate::HTTPClient.user_agent }
end
def allow_net_connections?
ENV['TEST_NETWORK'] || ENV['TRAVIS_EVENT_TYPE'] == 'cron'
end
| 2b84a838a738195575f52316fc8cdbaf55d158ba | [
"JavaScript",
"Ruby",
"Markdown"
] | 14 | Ruby | sobakasu/google_web_translate | 26875121b939337ffc9c8e3f0c593e6c18876e64 | 9d438be6f11ddbe031a8a584fc04ff89f4f900a3 |
refs/heads/master | <repo_name>akon8/todo-app<file_sep>/app.js
const express = require("express");
const bParser = require("body-parser");
const mongoose = require("mongoose");
const _ = require("lodash");
//const date = require(__dirname + "/date.js");
const app = express();
//const day = date.getDate(); //bounding our module to a day variable
app.set('view engine', 'ejs');
app.use(bParser.urlencoded({extended:true}));
app.use(express.static("public"));
//Insert cluster address with the password HERE!!!
// mongoose.connect("mongodb+srv://<admin-name:<EMAIL>.net/todoDB>", {useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false});
const itemsSchema = {
name: String
};
const Item = mongoose.model("Item", itemsSchema);
const item1 = new Item({
name: "Do first task"
});
const item2 = new Item({
name: "Do this"
});
const item3 = new Item({
name: "Do that"
});
const defaultItems = [item1, item2, item3];
const listSchema = {
name: String,
items: [itemsSchema]
};
const List = mongoose.model("List", listSchema);
app.get("/", function(req, res){
//Find - looking for {}=all elements in db
Item.find({}, function(err, results){
if(err){
console.log(err);
} else {
console.log(results);
//checking the list for added default items
if (results.length === 0) {
//insertMany defaultItems
Item.insertMany(defaultItems, function(err){
if (err){
console.log(err);
} else {
console.log("Successfully uploaded new items!");
}
}); //insertMany
//get back after inserting default items
res.redirect("/");
} //if (foundItems.length === 0)
else {
//rendering the values of "today" and "newListItems" to the list.ejs
res.render("list", {listTitle: "day", newListItems: results});
}
}
});
});
//CUSTOM ROUTING
//getting custom routes
app.get("/:newlist", (req, res) =>{
const routeName = _.capitalize(req.params.newlist);
List.findOne({name: routeName}, (err, results) => {
if (!err){
if(!results) {
//create a new list
const list = new List({
name: routeName,
items: defaultItems
});
list.save();
res.redirect("/" + routeName);
} else {
//show an existing list
res.render("list", {listTitle: results.name, newListItems: results.items})
}
}
});
});
//POST
//adding items from input of "list.ejs"
app.post("/", function(req, res){
const itemName = req.body.newItem;
const listName = req.body.list;
const newItem = new Item({name: itemName});
if (listName === "day") {
newItem.save();
res.redirect("/");
} else {
List.findOne({name: listName}, (err, foundList)=> {
foundList.items.push(newItem);
foundList.save();
res.redirect("/" + listName);
});
}
}); // app.post("/")
//app.post("/delete")
app.post("/delete",(req, res)=>{
const chceckedItemId = req.body.checkbox;
const listName = req.body.listName;
if (listName === "day") {
Item.deleteOne({_id: chceckedItemId},(err)=>{
if(err){console.log(err);
} else {
console.log("Successfully removed checked item");
} //else
});//delete.One
res.redirect("/");
} //if
//custom list item delete
else {
List.findOneAndUpdate({name: listName},{$pull: {items: {_id: chceckedItemId}}}, function(err, results){
if(!err){
res.redirect("/" + listName);
}
});
}
});//app.post("/delete")
app.get("/about", function(req, res){
res.render("about");
});
//setting up Heroku port routing
let port = process.env.PORT;
if(port == null || port == ""){
port = 3000;
};
app.listen(port, () =>{
console.log("Server has started successfully!");
});
<file_sep>/README.md
See it in action here: https://todotemplate.herokuapp.com
You can create new list under a custom URL just by adding its name at the end of app URL like this:
https://todotemplate.herokuapp.com/<my_custom_list_name>
| c2207910494af6a99195fbfed4a8b6d64656d9c3 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | akon8/todo-app | 1f436b60a5fa31c0374fdd19fc5ed4102d76f3e9 | 30264e1e537f5e6cce4662ddba8cd91dbdc729a1 |
refs/heads/master | <file_sep># Practica-13
<file_sep>/* doble // para cambiar de carpeta*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include <direct.h>
#include <ctype.h>
int main()
{
FILE *doc;
char nombrearchivo[20];
char letra;
int numcaracter,numpalabras=0,numeros=0,i;
printf("Nombre del archivo:");
gets(nombrearchivo);
fflush(stdin);
strcat(nombrearchivo,".txt");
doc = fopen(nombrearchivo,"r");
if(doc == NULL)
{
printf("El archivo no existe '%s'.\n",162,nombrearchivo);
return 0;
}
while(!feof(doc))
{
letra=fgetc(doc);
if(letra==' ')
{
numpalabras++;
}
if(isdigit(letra))
{
numeros++;
}
}
fclose(doc);
doc=fopen("palabras.txt","w");
fprintf(doc,"Son %d palabras",numpalabras);
fclose(doc);
doc=fopen("numeros.txt","w");
fprintf(doc,"Son %d digitos",numeros);
fclose(doc);
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <direct.h>
main()
{
FILE *doc;
char nombrearchivo[20];
char descripcion_archivo[100]="";
int numcaracter;
printf("Nombre del archivo:");
gets(nombrearchivo);
fflush(stdin);
strcat(nombrearchivo,".txt");
doc = fopen(nombrearchivo,"r");
if(doc == NULL)
{
doc = fopen(nombrearchivo,"a");
printf("Se cre%c correctamente el archivo '%s'.\n",162,nombrearchivo);
}
else
{
printf("El archivo '%s' ya existe.\n" ,nombrearchivo);
doc = fopen(nombrearchivo,"w");
}
printf("Ingrese descripci%cn del archivo:",162);
gets(descripcion_archivo);
fflush(stdin);
numcaracter=strlen(descripcion_archivo);
printf("%d",numcaracter);
fwrite(&descripcion_archivo,numcaracter,1,doc);
fclose(doc);
}
<file_sep>/*Leer un archivo.txt tiene un parrafo,
1-Eliminar espacios
2-Guardar el archivo alrevez en renglones y columnas
| e5b8d5fa87c6c044cb16ce1df737358090a0c078 | [
"Markdown",
"C"
] | 4 | Markdown | TattoSan/Practica-13 | 11b6faa1579e2cae68baf9363d09492f06b686a4 | 6b02ded909856526b05e9604677687b40510224b |
refs/heads/master | <file_sep>namespace YoutubeTagger
{
public enum DownloadType
{
YoutubeMix,
YoutubeSong,
Other1
}
public class DownloadInfo
{
//the type of download type to use
public DownloadType DownloadType;
//the name of the folder to process files
public string Folder;
public string Album;
//public int Year;//from datetime now
//public string Title;//from filename
//public string Artist;//from filename or VA
public string AlbumArtist;
//from saved in xml file
public uint LastTrackNumber;
public string Genre;
public string[] CopyPaths;
public string LastDate;
public bool FirstRun;
public string DownloadURL;
public uint BackupLastTrackNumber;
public string CustomYoutubedlCommands = string.Empty;
public bool Enabled = true;
}
}
<file_sep># YoutubePlaylistAlbumDownload
Downloads youtube videos and tags the audio files based on an xml document
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml;
using System.Reflection;
using System.ComponentModel;
namespace YoutubeTagger
{
class Program
{
#region Constants
//list of valid audio extensions for the scope of this project
private static readonly string[] ValidExtensions = new string[]
{
".m4a",
".M4A",
".mp3",
".MP3"
};
//list of binaries used for the scope of this project
private static readonly string[] BinaryFiles = new string[]
{
"AtomicParsley.exe",
"ffmpeg.exe",
"ffprobe.exe",
YoutubeDL
};
private static readonly string[] EmbeddedBinaryFiles = new string[]
{
"AtomicParsley.exe",
"ffmpeg.exe",
"ffprobe.exe"
};
//name of youtube-dl application
private const string YoutubeDL = "youtube-dl.exe";
//name of folder to keep above binary files
private const string BinaryFolder = "bin";
//name of xml file containing all download information
private const string DownloadInfoXml = "DownloadInfo.xml";
//list to be parse of info from above defined xml file
private static List<DownloadInfo> DownloadInfos = new List<DownloadInfo>();
//logile for the application
private const string Logfile = "logfile.log";
#endregion
//also using initializers as defaults
#region XML parsed Settings
//if prompts should be used from command line entry
public static bool NoPrompts = false;
//if it should run the scripts
public static bool RunScripts = false;
//if we should parse tags
public static bool ParseTags = false;
//if we should copy files
public static bool CopyFiles = false;
//if we shuld copy binary files
public static bool CopyBinaries = true;
//if we should delete binary files
public static bool DeleteBinaries = true;
//if we should update youtubedl
public static bool UpdateYoutubeDL = true;
//if we are saving the new date for the last time the script was run
public static bool SaveNewDate = true;
//if we should stop the application at error message prompts
public static bool NoErrorPrompts = false;
//if we should force write ff binaries to disk
public static bool ForceWriteFFBinaries = false;
//the default command line args passed into youtube-dl
private static string DefaultCommandLine = "-i --playlist-reverse --youtube-skip-dash-manifest {0} {1} --match-filter \"{2}\" -o \"%(autonumber)s-%(title)s.%(ext)s\" --format m4a --embed-thumbnail {3}";
//the start of the dateafter command line arg
private static string DateAfterCommandLine = "--dateafter";
//the duration match filter for youtube songs (600 = 600 seconds -> 10 mins, less indicates a song)
private static string YoutubeSongDurationCommandLine = "duration < 600";
//the duration match filter for youtube mixes (600 = 600 seconds -> 10 mins, more indicates a mix)
private static string YoutubeMixDurationCommandLine = "duration > 600";
#endregion
static void Init()
{
//hook up assembly resolver
//https://stackoverflow.com/a/25990979/3128017
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}
static int Main(string[] args)
{
Init();
return RunProgram(args);
}
static int RunProgram(string[] args)
{
//init tag parsing, load xml data
//check to make sure download info xml file is present
if (!File.Exists(DownloadInfoXml))
{
WriteToLog(string.Format("{0} is missing, application cannot continue", DownloadInfoXml));
Console.ReadLine();
Environment.Exit(-1);
}
WriteToLog("---------------------------APPLICATION START---------------------------");
WriteToLog("Loading XML document");
XmlDocument doc = new XmlDocument();
try
{
doc.Load(DownloadInfoXml);
}
catch (XmlException ex)
{
WriteToLog(ex.ToString());
Console.ReadLine();
Environment.Exit(-1);
}
try
{
//https://www.freeformatter.com/xpath-tester.html#ad-output
//get some default settings
NoPrompts = bool.Parse(doc.SelectSingleNode("//DownloadInfo.xml/Settings/NoPrompts").InnerText.Trim());
NoErrorPrompts = bool.Parse(doc.SelectSingleNode("//DownloadInfo.xml/Settings/NoErrorPrompts").InnerText.Trim());
ForceWriteFFBinaries = bool.Parse(doc.SelectSingleNode("//DownloadInfo.xml/Settings/ForceWriteFFBinaries").InnerText.Trim());
UpdateYoutubeDL = bool.Parse(doc.SelectSingleNode("//DownloadInfo.xml/Settings/UpdateYoutubeDL").InnerText.Trim());
CopyBinaries = bool.Parse(doc.SelectSingleNode("//DownloadInfo.xml/Settings/CopyBinaries").InnerText.Trim());
RunScripts = bool.Parse(doc.SelectSingleNode("//DownloadInfo.xml/Settings/RunScripts").InnerText.Trim());
SaveNewDate = bool.Parse(doc.SelectSingleNode("//DownloadInfo.xml/Settings/SaveNewDate").InnerText.Trim());
ParseTags = bool.Parse(doc.SelectSingleNode("//DownloadInfo.xml/Settings/ParseTags").InnerText.Trim());
CopyFiles = bool.Parse(doc.SelectSingleNode("//DownloadInfo.xml/Settings/CopyFiles").InnerText.Trim());
DeleteBinaries = bool.Parse(doc.SelectSingleNode("//DownloadInfo.xml/Settings/DeleteBinaries").InnerText.Trim());
//and some default command line settings
DefaultCommandLine = doc.SelectSingleNode("//DownloadInfo.xml/CommandLine/Default").InnerText.Trim();
DateAfterCommandLine = doc.SelectSingleNode("//DownloadInfo.xml/CommandLine/DateAfter").InnerText.Trim();
YoutubeMixDurationCommandLine = doc.SelectSingleNode("//DownloadInfo.xml/CommandLine/YoutubeMixDuration").InnerText.Trim();
YoutubeSongDurationCommandLine = doc.SelectSingleNode("//DownloadInfo.xml/CommandLine/YoutubeSongDuration").InnerText.Trim();
//for each xml element "DownloadInfo" in element "DownloadInfo.xml"
foreach (XmlNode infosNode in doc.SelectNodes("//DownloadInfo.xml/DownloadInfos/DownloadInfo"))
{
//this works for inner elements
//string test = infosNode.SelectSingleNode("//Folder").InnerText;
DownloadInfo temp = new DownloadInfo
{
/*
Folder = infosNode.Attributes[nameof(DownloadInfo.Folder)].Value.Trim(),
Album = infosNode.Attributes[nameof(DownloadInfo.Album)].Value.Trim(),
AlbumArtist = infosNode.Attributes[nameof(DownloadInfo.AlbumArtist)].Value.Trim(),
Genre = infosNode.Attributes[nameof(DownloadInfo.Genre)].Value.Trim(),
LastTrackNumber = uint.Parse(infosNode.Attributes[nameof(DownloadInfo.LastTrackNumber)].Value.Trim()),
DownloadType = (DownloadType)Enum.Parse(typeof(DownloadType), infosNode.Attributes[nameof(DownloadInfo.DownloadType)].Value.Trim()),
LastDate = infosNode.Attributes[nameof(DownloadInfo.LastDate)].Value.Trim(),
DownloadURL = infosNode.Attributes[nameof(DownloadInfo.DownloadURL)].Value.Trim(),
FirstRun = bool.Parse(infosNode.Attributes[nameof(DownloadInfo.FirstRun)].Value.Trim()),
CustomYoutubedlCommands = infosNode.Attributes[nameof(DownloadInfo.CustomYoutubedlCommands)].Value.Trim(),
Enabled = bool.Parse(infosNode.Attributes[nameof(DownloadInfo.Enabled)].Value.Trim())
*/
};
List<FieldInfo> fields = temp.GetType().GetFields().ToList();
foreach (XmlAttribute attribute in infosNode.Attributes)
{
FieldInfo field = fields.Where(fieldd => fieldd.Name.Equals(attribute.Name)).ToList()[0];
var converter = TypeDescriptor.GetConverter(field.FieldType);
//settingField.SetValue(classInstance, converter.ConvertFrom(settings[i].InnerText));
//field.SetValue(temp, attribute.Value);
field.SetValue(temp, converter.ConvertFrom(attribute.Value));
}
XmlNodeList pathsList = infosNode.ChildNodes;
//i can do it without lists
if (pathsList.Count > 0)
{
temp.CopyPaths = new string[pathsList.Count];
int i = 0;
foreach (XmlNode paths in pathsList)
{
//check to make sure the path is valid before trying to use later
if (!Directory.Exists(paths.InnerText))
{
if (temp.FirstRun)
{
WriteToLog(string.Format("INFO: path {0} does not exist, but firstRun = true, creating path", paths.InnerText));
Directory.CreateDirectory(paths.InnerText);
}
else
{
WriteToLog("ERROR: the path");
WriteToLog(paths.InnerText);
WriteToLog("Does not exist!");
Console.ReadLine();
Environment.Exit(-1);
}
}
temp.CopyPaths[i++] = paths.InnerText;
}
}
else
{
WriteToLog("ERROR: paths count is 0! for downloadFolder of folder attribute " + infosNode.Attributes[nameof(DownloadInfo.Folder)].Value);
Environment.Exit(-1);
}
//if it's the first time running, then we can set the last track count to 0 (if not already)
if (temp.FirstRun)
temp.LastTrackNumber = 0;
//and finally add it to the list
DownloadInfos.Add(temp);
}
}
catch (Exception ex)
{
WriteToLog(ex.ToString());
Console.ReadLine();
Environment.Exit(-1);
}
//check to make sure we have at least one downloadInfo to run!
if (DownloadInfos.Count == 0)
{
WriteToLog("No DownloadInfos parsed! (empty xml file?)");
if (!NoErrorPrompts)
Console.ReadLine();
Environment.Exit(-1);
}
//check to make sure at least one downloadInfo enabled
List<DownloadInfo> enabledInfos = DownloadInfos.Where(info => info.Enabled).ToList();
if (enabledInfos.Count == 0)
{
WriteToLog("No DownloadInfos enabled!");
if (!NoErrorPrompts)
Console.ReadLine();
Environment.Exit(-1);
}
//only process enabled infos
DownloadInfos = enabledInfos;
//if not silent, add start of application here
if (!NoPrompts)
{
WriteToLog("Press enter to start");
//https://stackoverflow.com/questions/11512821/how-to-stop-c-sharp-console-applications-from-closing-automatically
Console.ReadLine();
}
//run an update on youtube-dl
//https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process?redirectedfrom=MSDN&view=netframework-4.7.2
if (!NoPrompts)
{
UpdateYoutubeDL = GetUserResponse("UpdateYoutubeDL?");
}
if (UpdateYoutubeDL)
{
WriteToLog("Update YoutubeDL");
//create folder if it does not already exist
CheckMissingFolder(BinaryFolder);
//check if youtube-dl is missing, if so download it
string youtubeDLPath = Path.Combine(BinaryFolder, YoutubeDL);
if (!File.Exists(youtubeDLPath))
{
WriteToLog("Youtube-dl.exe does not exist, download it");
try
{
using (WebClient client = new WebClient())
{
client.DownloadFile("https://yt-dl.org/latest/youtube-dl.exe", youtubeDLPath);
}
}
catch (WebException ex)
{
WriteToLog("Failed to download youtube-dl.exe");
WriteToLog(ex.ToString());
if (!NoErrorPrompts)
Console.ReadLine();
Environment.Exit(-1);
}
}
else
WriteToLog("Youtube-dl.exe exists");
try
{
using (Process updateYoutubeDL = new Process())
{
//set properties
updateYoutubeDL.StartInfo.RedirectStandardError = false;
updateYoutubeDL.StartInfo.RedirectStandardOutput = false;
updateYoutubeDL.StartInfo.UseShellExecute = true;
updateYoutubeDL.StartInfo.WorkingDirectory = BinaryFolder;
updateYoutubeDL.StartInfo.FileName = YoutubeDL;
updateYoutubeDL.StartInfo.CreateNoWindow = false;
updateYoutubeDL.StartInfo.Arguments = "--update";
updateYoutubeDL.Start();
updateYoutubeDL.WaitForExit();
if (updateYoutubeDL.ExitCode != 0)
{
WriteToLog(string.Format("ERROR: update process exited with code {0}", updateYoutubeDL.ExitCode));
if (!NoErrorPrompts)
Console.ReadLine();
Environment.Exit(-1);
}
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10.0));
}
}
catch (Exception e)
{
WriteToLog(e.ToString());
if (!NoErrorPrompts)
Console.ReadLine();
Environment.Exit(-1);
}
}
else
WriteToLog("UpdateYoutubeDl skipped");
if (!NoPrompts)
{
CopyBinaries = GetUserResponse("CopyBinaries?");
}
if (CopyBinaries)
{
WriteToLog("Copy Binaries");
CheckMissingFolder(BinaryFolder);
//if embedded binary does not exist, OR force binary embedded write, then write it
foreach (string s in EmbeddedBinaryFiles)
{
string binaryPath = Path.Combine(BinaryFolder, s);
if (!File.Exists(binaryPath) || ForceWriteFFBinaries)
{
WriteToLog(string.Format("File {0} does not exist or ForceWriteFFBinaries is on, writing binaries to disk", s));
File.WriteAllBytes(binaryPath, GetEmbeddedResource(Path.GetFileNameWithoutExtension(s)));
}
}
//copy the binaries to each folder
foreach (DownloadInfo info in DownloadInfos.Where(temp => temp.DownloadType == DownloadType.YoutubeSong || temp.DownloadType == DownloadType.YoutubeMix))
{
CheckMissingFolder(info.Folder);
foreach (string binaryFile in BinaryFiles)
{
WriteToLog(string.Format("Copying file {0} into folder {1}", binaryFile, info.Folder));
string fileToCopy = Path.Combine(info.Folder, binaryFile);
if (File.Exists(fileToCopy))
File.Delete(fileToCopy);
File.Copy(Path.Combine(BinaryFolder, binaryFile), fileToCopy);
}
}
}
else
WriteToLog("CopyBinaries skipped");
//ask user if we will run the scripts
if (!NoPrompts)
{
RunScripts = GetUserResponse("RunScripts?");
}
if (RunScripts)
{
WriteToLog("Running scripts");
//build and run the process list for youtube downloads
//build first
List<Process> processes = new List<Process>();
//only create processes for youtube download types
foreach (DownloadInfo info in DownloadInfos.Where(temp => temp.DownloadType == DownloadType.YoutubeSong || temp.DownloadType == DownloadType.YoutubeMix))
{
//make sure folder path exists
CheckMissingFolder(info.Folder);
//make sure required binaries exist
foreach (string binaryFile in BinaryFiles)
CheckMissingFile(Path.Combine(info.Folder, binaryFile));
//delete any previous song file entries
foreach (string file in Directory.GetFiles(info.Folder, "*", SearchOption.TopDirectoryOnly).Where(file => ValidExtensions.Contains(Path.GetExtension(file))))
{
WriteToLog("Deleting old song file from previous run: " + Path.GetFileName(file));
File.Delete(file);
}
WriteToLog(string.Format("Build process info folder {0}", info.Folder));
processes.Add(new Process()
{
StartInfo = new ProcessStartInfo()
{
RedirectStandardError = false,
RedirectStandardOutput = false,
UseShellExecute = true,
WorkingDirectory = info.Folder,
FileName = YoutubeDL,
CreateNoWindow = false,
Arguments = string.Format(DefaultCommandLine,//from xml
info.FirstRun ? string.Empty : DateAfterCommandLine,//date after (youtube-dl command line key)
info.FirstRun ? string.Empty : info.LastDate,//date after (youtube-dl command line arg)
info.DownloadType == DownloadType.YoutubeMix ? YoutubeMixDurationCommandLine : YoutubeSongDurationCommandLine,//youtube-dl match filter duration selector
string.IsNullOrEmpty(info.CustomYoutubedlCommands) ? string.Empty : info.CustomYoutubedlCommands,
info.DownloadURL)
}
});
}
//run them all now
foreach (Process p in processes)
{
try
{
WriteToLog(string.Format("Launching process for folder {0} using arguments {1}", p.StartInfo.WorkingDirectory, p.StartInfo.Arguments));
p.Start();
}
catch (Exception ex)
{
WriteToLog("An error has occurred running a process, stopping all");
KillProcesses(processes);
WriteToLog(ex.ToString());
if (!NoErrorPrompts)
Console.ReadLine();
Environment.Exit(-1);
}
}
//iterate to wait for all to complete
foreach (Process p in processes)
{
p.WaitForExit();
WriteToLog(string.Format("Process of folder {0} has finished or previously finished", p.StartInfo.WorkingDirectory));
}
//check exit code status
bool forceExit = false;
foreach (Process p in processes)
{
WriteToLog(string.Format("Process of folder {0} exited of code {1}", p.StartInfo.WorkingDirectory, p.ExitCode));
if (p.ExitCode == 0 || p.ExitCode == 1)
{
WriteToLog("Valid exit code");
}
else
{
WriteToLog("Invalid exit code, marked to exit");
forceExit = true;
}
}
//determine if to quit
if (forceExit)
{
WriteToLog("An exit code above was bad, exiting");
KillProcesses(processes);
if (!NoErrorPrompts)
Console.ReadLine();
Environment.Exit(-1);
}
//after all completed successfully, dispose of them
foreach (Process p in processes)
p.Dispose();
GC.Collect();
WriteToLog("All processes completed");
}
else
WriteToLog("RunScripts skipped");
//save the new date for when the above scripts were last run
if (!NoPrompts)
{
SaveNewDate = GetUserResponse("SaveNewDate?");
}
if (SaveNewDate)
{
WriteToLog("Saving new date");
//https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
string newDate = string.Format("{0:yyyyMMdd}", DateTime.Now);
for (int i = 0; i < DownloadInfos.Count; i++)
{
WriteToLog(string.Format("Changing and saving xml old date from {0} to {1}", DownloadInfos[i].LastDate, newDate));
DownloadInfos[i].LastDate = newDate;
//then save it in xml
string xpath = string.Format("//DownloadInfo.xml/DownloadInfos/DownloadInfo[@Folder='{0}']", DownloadInfos[i].Folder);
XmlNode infoNode = doc.SelectSingleNode(xpath);
if (infoNode == null)
{
WriteToLog("Failed to save xml doc back folder " + DownloadInfos[i].Folder);
if (!NoErrorPrompts)
Console.ReadLine();
Environment.Exit(-1);
}
XmlAttribute lastDate = infoNode.Attributes["LastDate"];
if (lastDate == null)
{
//make it first then
lastDate = doc.CreateAttribute("LastDate");
infoNode.Attributes.Append(lastDate);
}
lastDate.Value = DownloadInfos[i].LastDate;
doc.Save(DownloadInfoXml);
}
}
else
WriteToLog("SaveNewDate skipped");
//start naming and tagging
//get a list of files from the directory listed
if (!NoPrompts)
{
ParseTags = GetUserResponse("ParseTags?");
}
if (ParseTags)
{
WriteToLog("Parsing tags");
for (int j = 0; j < DownloadInfos.Count; j++)
{
DownloadInfo info = DownloadInfos[j];
//save the track number in a backup in case if copying is true, and there's a "same title with different track number" error
//if that happends, the old number needs to be written back to disk because the whole naming process is not invalid
info.BackupLastTrackNumber = info.LastTrackNumber;
WriteToLog("");
WriteToLog("-----------------------Parsing directory " + info.Folder + "----------------------");
CheckMissingFolder(info.Folder);
//make and filter out the lists
List<string> files = Directory.GetFiles(info.Folder, "*", SearchOption.TopDirectoryOnly).Where(file => ValidExtensions.Contains(Path.GetExtension(file))).ToList();
//check to make sure there are valid audio files before proceding
if (files.Count == 0)
{
WriteToLog("no valid audio files in directory");
continue;
}
//step 0: check for if padding is needed
//get the number of track numbers for the first and last files
int firstEntryNumTrackNums = Path.GetFileName(files[0]).Split('-')[0].Length;
int maxEntryNumTrackNums = 0;
foreach (string s in files)
{
string filename = Path.GetFileName(s);
int currentEntryNumTrackNums = filename.Split('-')[0].Length;
if (currentEntryNumTrackNums > maxEntryNumTrackNums)
maxEntryNumTrackNums = currentEntryNumTrackNums;
}
WriteToLog(string.Format("first entry, track number padding = {0}\nmax entry, track number padding = {1}\n",
firstEntryNumTrackNums, maxEntryNumTrackNums));
if (firstEntryNumTrackNums != maxEntryNumTrackNums)
{
//inform and ask
WriteToLog("Not equal, padding entries");
//use the last entry as reference point for how many paddings to do
for (int i = 0; i < files.Count; i++)
{
string oldFileName = Path.GetFileName(files[i]);
int numToPadOut = maxEntryNumTrackNums - oldFileName.Split('-')[0].Length;
if (numToPadOut > 0)
{
string newFileName = oldFileName.PadLeft(oldFileName.Length + numToPadOut, '0');
WriteToLog(string.Format("{0}\nrenamed to\n{1}", oldFileName, newFileName));
File.Move(Path.Combine(info.Folder, oldFileName), Path.Combine(info.Folder, newFileName));
files[i] = Path.Combine(info.Folder, newFileName);
}
else
{
WriteToLog(string.Format("{0}\nnot renamed", oldFileName));
}
}
//and re-sort if afterwards
files.Sort();
}
//step 1: parse the tag info
for (int i = 0; i < files.Count; i++)
{
bool fileDeleted = false;
bool skipFile = false;
string fileName = files[i];
WriteToLog("Parsing " + fileName);
//create TagLib instance
TagLib.Tag tag = null;
TagLib.File file = null;
try
{
//https://stackoverflow.com/questions/40826094/how-do-i-use-taglib-sharp
file = TagLib.File.Create(fileName);
tag = file.Tag;
}
catch (Exception ex)
{
WriteToLog(ex.ToString());
if (!NoErrorPrompts)
Console.ReadLine();
Environment.Exit(-1);
}
//assign tag infos from xml properties
//album
tag.Album = info.Album;
//album artist
//https://stackoverflow.com/questions/17292142/taglib-sharp-not-editing-artist
if (!string.IsNullOrEmpty(info.AlbumArtist))
{
tag.AlbumArtists = null;
tag.AlbumArtists = new string[] { info.AlbumArtist };
}
//track number
//last saved number in the xml will be the last track number applied
//so up it first, then use it
tag.Track = ++info.LastTrackNumber;
//genre
tag.Genres = null;
tag.Genres = new string[] { info.Genre };
if (info.DownloadType == DownloadType.Other1)
{
//Other1 is mixes, add current year and artist as VA
tag.Performers = null;
tag.Performers = new string[] { "VA" };
tag.Year = (uint)DateTime.Now.Year;
WriteToLog("Song treated as heartAtThis mix");
}
else//youtube mix and song
{
//artist and title and year from filename
//get the name of the file to parse tag info to
string fileNameToParse = Path.GetFileNameWithoutExtension(fileName);
//replace "–" with "-", as well as "?-" with "-"
fileNameToParse = fileNameToParse.Replace('–', '-').Replace("?-", "-");
//split based on "--" unique separater
string[] splitFileName = fileNameToParse.Split(new string[] { "--" }, StringSplitOptions.RemoveEmptyEntries);
//if the count is 1, then there are no "--", implies a run in this directory already happened
if (splitFileName.Count() == 1)
{
WriteToLog(string.Format("File {0} seems to have already been parsed, skipping", splitFileName[0]));
//decrease the number, it's not a new song
info.LastTrackNumber--;
continue;
}
//split into mix parsing and song parsing
if (info.DownloadType == DownloadType.YoutubeMix)
{
//from youtube-dl output template:
//[0] = autonumber (discard), [1] = title (actual title), [2] = upload year
//title
tag.Title = splitFileName[1].Trim();
//year is YYYMMDD, only want YYYY
bool validYear = false;
string yearString = string.Empty;
yearString = splitFileName[2].Substring(0, 4).Trim();
//remove any extra "-" characters
yearString = yearString.Replace("-", string.Empty).Trim();
while (!validYear)
{
try
{
tag.Year = uint.Parse(yearString);
validYear = true;
}
catch
{
Console.Beep(1000, 500);
WriteToLog("ERROR: Invalid year, please manually type");
WriteToLog("Original: " + yearString);
WriteToLog("Enter new (ONLY \"YYYY\")");
yearString = Console.ReadLine().Trim();
}
}
//artist (is VA for mixes)
tag.Performers = null;
tag.Performers = new string[] { "VA" };
WriteToLog("Song treated as youtube mix");
}
else//youtube song
{
//from youtube-dl output template:
//[0] = autonumber (discard), [1] = title (artist and title), [2] = upload year
//first get the artist title combo from parsed filename form youtube-dl
string filenameArtistTitle = splitFileName[1].Trim();
string[] splitArtistTitleName = null;
bool validArtistTitleParse = false;
while (!validArtistTitleParse)
{
//labels divide the artist and title by " - "
//split into artist [0] and title [1]
splitArtistTitleName = filenameArtistTitle.Split(new string[] { " - " }, StringSplitOptions.None);
//should be 2 entries for this to work
if (splitArtistTitleName.Count() < 2)
{
Console.Beep(1000, 500);
WriteToLog("ERROR: not enough split entries for parsing, please enter manually! (count is " + splitArtistTitleName.Count() + " )");
WriteToLog("Original: " + filenameArtistTitle);
WriteToLog("Enter new: (just arist - title combo)");
WriteToLog("Or \"skip\" to remove song from parsing");
filenameArtistTitle = Console.ReadLine().Trim();
if (filenameArtistTitle.Equals("skip"))
{
skipFile = true;
break;
}
}
else
validArtistTitleParse = true;
}
if (skipFile)
{
filenameArtistTitle = "skipping - skipping--6969";
}
//get the artist name from split
tag.Performers = null;
tag.Performers = new string[] { splitArtistTitleName[0].Trim() };
//include anything after it rather than just get the last one, in case there's more split characters
//skip one for the artist name
tag.Title = string.Join(" - ", splitArtistTitleName.Skip(1)).Trim();
//year is YYYMMDD, only want YYYY
bool validYear = false;
string yearString = string.Empty;
yearString = splitFileName[2].Substring(0, 4).Trim();
//remove any extra "-" characters
yearString = yearString.Replace("-", string.Empty).Trim();
while (!validYear)
{
try
{
tag.Year = uint.Parse(yearString);
validYear = true;
}
catch
{
Console.Beep(1000, 500);
WriteToLog("ERROR: Invalid year, please manually type");
WriteToLog("Original: " + yearString);
WriteToLog("Enter new (ONLY \"YYYY\")");
yearString = Console.ReadLine().Trim();
}
}
WriteToLog("Song treated as youtube song");
}
}
if (skipFile)
{
WriteToLog(string.Format("Skipping song {0}", tag.Title));
File.Delete(fileName);
//also delete the entry from list of files to process
files.Remove(fileName);
//also put the counter back for track numbers
info.LastTrackNumber--;
//also decremant the counter as to not skip
i--;
//also note it
fileDeleted = true;
}
//check to make sure song doesn't already exist (but only if it's not the first time downloading
else if (!info.FirstRun)
{
if (SongAlreadyExists(info.CopyPaths, tag.Title))
{
WriteToLog(string.Format("WARNING: Song {0} already exists in a copy folder, deleting the entry!", tag.Title));
if (!NoPrompts)
Console.ReadLine();
File.Delete(fileName);
//also delete the entry from list of files to process
files.Remove(fileName);
//also put the counter back for track numbers
info.LastTrackNumber--;
//also decremant the counter as to not skip
i--;
//also note it
fileDeleted = true;
}
}
if (!fileDeleted)
file.Save();
}
//step 2: parse the filenames from the tags
foreach (string fileName in files)
{
//load the file again
TagLib.File file = null;
try
{
//https://stackoverflow.com/questions/40826094/how-do-i-use-taglib-sharp
file = TagLib.File.Create(fileName);
}
catch (Exception ex)
{
WriteToLog(ex.ToString());
if (!NoErrorPrompts)
Console.ReadLine();
Environment.Exit(-1);
}
//get the old name
string oldFileName = Path.GetFileNameWithoutExtension(fileName);
//prepare the new name
string newFileName = string.Empty;
//manual check to make sure track and title exist
if (file.Tag.Track == 0)
{
WriteToLog(string.Format("ERROR: Track property is missing in file {0}", fileName));
if (NoErrorPrompts)
Environment.Exit(-1);
while (true)
{
WriteToLog("Please input unsigned int manually!");
if (uint.TryParse(Console.ReadLine(), out uint result))
{
file.Tag.Track = result;
file.Save();
break;
}
}
}
if (string.IsNullOrWhiteSpace(file.Tag.Title))
{
WriteToLog(string.Format("ERROR: Title property is missing in file {0}", fileName));
if (NoErrorPrompts)
Environment.Exit(-1);
WriteToLog("Please input manually!");
file.Tag.Title = Console.ReadLine();
file.Save();
}
switch (info.DownloadType)
{
case DownloadType.Other1:
//using the pre-parsed title...
newFileName = string.Format("{0}-{1}", file.Tag.Track.ToString(), file.Tag.Title);
break;
case DownloadType.YoutubeMix:
newFileName = string.Format("{0}-{1}", file.Tag.Track.ToString(), file.Tag.Title);
break;
case DownloadType.YoutubeSong:
if (file.Tag.Performers == null || file.Tag.Performers.Count() == 0)
{
WriteToLog(string.Format("ERROR: Artist property is missing in file {0}", fileName));
if (NoErrorPrompts)
Environment.Exit(-1);
WriteToLog("Please input manually!");
file.Tag.Performers = null;
file.Tag.Performers = new string[] { Console.ReadLine() };
file.Save();
}
newFileName = string.Format("{0}-{1} - {2}", file.Tag.Track.ToString(), file.Tag.Performers[0], file.Tag.Title);
break;
default:
WriteToLog("Invalid downloadtype: " + info.DownloadType.ToString());
if (!NoErrorPrompts)
Console.ReadLine();
continue;
}
//check for padding
//set padding to highest number of tracknumbers
//(if tracks go from 1-148, make sure filename for 1 is 001)
int trackPaddingLength = newFileName.Split('-')[0].Length;
int maxTrackNumPaddingLength = info.LastTrackNumber.ToString().Length;
if (trackPaddingLength < maxTrackNumPaddingLength)
{
WriteToLog("Correcting for track padding");
int numToPad = maxTrackNumPaddingLength - trackPaddingLength;
newFileName = newFileName.PadLeft(newFileName.Length + numToPad, '0');
}
//save the complete folder path
string completeFolderPath = Path.GetDirectoryName(fileName);
string completeOldPath = Path.Combine(completeFolderPath, oldFileName + Path.GetExtension(fileName));
string completeNewPath = Path.Combine(completeFolderPath, newFileName + Path.GetExtension(fileName));
WriteToLog(string.Format("Renaming {0}\n to {1}", oldFileName, newFileName));
File.Move(completeOldPath, completeNewPath);
}
//also change firstRun to false if not done already
if (info.FirstRun)
{
WriteToLog(string.Format("DEBUG: folder {0} firstRun is true, setting to false", info.Folder));
info.FirstRun = false;
}
//at the end of each folder, write the new value back to the xml file
string xpath = string.Format("//DownloadInfo.xml/DownloadInfos/DownloadInfo[@Folder='{0}']", info.Folder);
XmlNode infoNode = doc.SelectSingleNode(xpath);
if (infoNode == null)
{
WriteToLog("Failed to select node for saving LastTrackNumber back to folder " + info.Folder);
if (!NoErrorPrompts)
Console.ReadLine();
Environment.Exit(-1);
}
XmlAttribute lastTrackNumber = infoNode.Attributes["LastTrackNumber"];
if (lastTrackNumber == null)
{
lastTrackNumber = doc.CreateAttribute("LastTrackNumber");
infoNode.Attributes.Append(lastTrackNumber);
}
lastTrackNumber.Value = info.LastTrackNumber.ToString();
infoNode.Attributes[nameof(info.FirstRun)].Value = info.FirstRun.ToString();
doc.Save(DownloadInfoXml);
WriteToLog("Saved LastTrackNumber for folder " + info.Folder);
}
}
else
WriteToLog("ParseTags skipped");
//copy newly parsed files to their directories
if (!NoPrompts)
{
CopyFiles = GetUserResponse("CopyFiles?");
}
if (CopyFiles)
{
WriteToLog("Copy Files");
for (int j = 0; j < DownloadInfos.Count; j++)
{
DownloadInfo info = DownloadInfos[j];
CheckMissingFolder(info.Folder);
//make and filter out the lists
List<string> files = Directory.GetFiles(info.Folder, "*", SearchOption.TopDirectoryOnly).Where(file => ValidExtensions.Contains(Path.GetExtension(file))).ToList();
WriteToLog("");
WriteToLog("-----------------------CopyFiles for directory " + info.Folder + "----------------------");
if (files.Count == 0)
{
WriteToLog("no files to copy");
continue;
}
bool breakout = false;
//using copy for all then delete because you can't move across drives (easily)
foreach (string copypath in info.CopyPaths)
{
WriteToLog("Copying files to directory " + copypath);
foreach (string file in files)
{
WriteToLog(Path.GetFileName(file));
string newPath = Path.Combine(copypath, Path.GetFileName(file));
File.Copy(file, newPath);
}
}
if (breakout)
continue;
//now delete
WriteToLog("Deleting files in infos folder");
foreach (string file in files)
if (File.Exists(file))
File.Delete(file);
}
}
else
WriteToLog("CopyFiles skipped");
//delete the binaries in each folder
if (!NoPrompts)
{
DeleteBinaries = GetUserResponse("DeleteBinaries?");
}
if (DeleteBinaries)
{
WriteToLog("Delete Binaries");
CheckMissingFolder(BinaryFolder);
foreach (DownloadInfo info in DownloadInfos.Where(temp => temp.DownloadType == DownloadType.YoutubeSong || temp.DownloadType == DownloadType.YoutubeMix))
{
CheckMissingFolder(info.Folder);
foreach (string binaryFile in BinaryFiles)
{
WriteToLog(string.Format("Deleting file {0} in folder {1} if exist", binaryFile, info.Folder));
string fileToCopy = Path.Combine(info.Folder, binaryFile);
if (File.Exists(fileToCopy))
File.Delete(fileToCopy);
}
}
}
else
WriteToLog("DeleteBinaries skipped");
//and we're all set here
WriteToLog("Done");
if (!NoPrompts)
Console.ReadLine();
Environment.ExitCode = 0;
Environment.Exit(0);
return 0;
}
#region Helper Methods
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string dllName = new AssemblyName(args.Name).Name + ".dll";
Assembly assem = Assembly.GetExecutingAssembly();
string resourceName = assem.GetManifestResourceNames().FirstOrDefault(rn => rn.EndsWith(dllName));
using (Stream stream = assem.GetManifestResourceStream(resourceName))
{
byte[] assemblyData = new byte[stream.Length];
stream.Read(assemblyData, 0, assemblyData.Length);
return Assembly.Load(assemblyData);
}
}
private static byte[] GetEmbeddedResource(string resourceName)
{
Assembly assem = Assembly.GetExecutingAssembly();
//https://stackoverflow.com/questions/1024559/when-to-use-first-and-when-to-use-firstordefault-with-linq
string resourceNameFound = assem.GetManifestResourceNames().FirstOrDefault(rn => rn.Contains(resourceName));
if (!string.IsNullOrWhiteSpace(resourceNameFound))
{
using (Stream stream = assem.GetManifestResourceStream(resourceNameFound))
{
byte[] assemblyData = new byte[stream.Length];
stream.Read(assemblyData, 0, assemblyData.Length);
return assemblyData;
}
}
else
return null;
}
//write to the console and the logfile
private static void WriteToLog(string logMessage)
{
Console.WriteLine(logMessage);
File.AppendAllText(Logfile, string.Format("{0}: {1}{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), logMessage, Environment.NewLine));
}
//get the response to a user question
private static bool GetUserResponse(string question)
{
//ask user the question
WriteToLog(question);
while (true)
{
if (bool.TryParse(Console.ReadLine(), out bool res))
{
return res;
}
else
{
WriteToLog("Response must be bool parse-able (i.e. true or false)");
}
}
}
//check if a song with a same title exists based on what was just parsed
private static bool SongAlreadyExists(string[] copyFoldersToCheck, string titleOfSongToCheck)
{
bool doesSongAlreadyExist = false;
foreach(string copyFolderToCheck in copyFoldersToCheck)
{
if (!Directory.Exists(copyFolderToCheck))
continue;
//get a lsit of files in that copy folder (with media extension)
foreach(string fileInCopyFolder in Directory.GetFiles(copyFolderToCheck).Where(filename => ValidExtensions.Contains(Path.GetExtension(filename))))
{
TagLib.Tag tag = null;
TagLib.File file = null;
//get the taglist entry for that file
try
{
//https://stackoverflow.com/questions/40826094/how-do-i-use-taglib-sharp
file = TagLib.File.Create(fileInCopyFolder);
tag = file.Tag;
}
catch (Exception ex)
{
WriteToLog(ex.ToString());
if (!NoErrorPrompts)
Console.ReadLine();
Environment.Exit(-1);
}
if(tag.Title.Equals(titleOfSongToCheck))
{
doesSongAlreadyExist = true;
break;
}
file.Dispose();
}
if (doesSongAlreadyExist)
break;
}
return doesSongAlreadyExist;
}
//check if a folder path is missing. create and continue is true
private static void CheckMissingFolder(string folderPath)
{
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
}
//check if a file is missing. error and exit if true
private static void CheckMissingFile(string filePath)
{
if (!File.Exists(filePath))
{
WriteToLog(string.Format("ERROR: missing file {0} for path {1}", Path.GetFileName(filePath), filePath));
Console.ReadLine();
//https://stackoverflow.com/questions/10286056/what-is-the-command-to-exit-a-console-application-in-c
Environment.Exit(-1);
}
}
//kill all running youtube download processes in list, then dispose of all of them
private static void KillProcesses(List<Process> processes)
{
foreach (Process proc in processes)
{
try
{
proc.Kill();
}
catch
{
//WriteToLog("process " + proc.Id + "not stopped");
}
try
{
proc.Dispose();
}
catch
{
//WriteToLog("process " + proc.Id + "not stopped");
}
}
}
#endregion
}
}
| 55d99e62f87a87cf920dd98ee1d3d4153cb52ca8 | [
"Markdown",
"C#"
] | 3 | C# | Willster419/YoutubePlaylistAlbumDownload | bab65a796fb65b185b59ee7015952f05b5196f15 | ce2b967304348adcddb1e7cc99d4ebc5d85122bf |
refs/heads/master | <repo_name>Jessricardo/Examen-Roket<file_sep>/app/components/Header/index.js
import React from 'react';
import { FormattedMessage } from 'react-intl';
import A from './A';
import Img from './Img';
import NavBar from './NavBar';
import HeaderLink from './HeaderLink';
import Banner from './logo1.png';
import Banner2 from './logo2.png';
import messages from './messages';
class Header extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
const item={
display: 'inline-block',
margin: '1%'
}
const selectedItem={
display: 'inline-block',
margin: '1%',
borderBottom: '4px solid #f2f200'
}
const menu={
width: '56%',
display: 'inline-block',
textAlign: 'right',
verticalAlign: 'bottom'
}
const head={
margin: '22px 0'
}
return (
<section style={head}>
<img src={Banner} />
<img src={Banner2} />
<article style={menu}>
<div style={selectedItem}>
home
</div>
<div style={item}>
about
</div>
<div style={item}>
news
</div>
<div style={item}>
work
</div>
<div style={item}>
clients
</div>
<div style={item}>
contact
</div>
</article>
</section>
);
}
}
export default Header;
<file_sep>/README.md
Proyecto realizado para la evaluación de trabajo.
Fecha: 20/Ago/2017
| fa9a0fa75ef2df5a6a064446233c0d31d381afeb | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Jessricardo/Examen-Roket | 02b1340073161804ec605c5623236a0fd4321157 | 31f7cbb227f1c7fdadfa4b2e67f01dc3f98ce734 |
refs/heads/master | <file_sep>package com.shenkar.laurachiche.viewlist_task;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class AddTask extends AppCompatActivity {
private Button addButton;
private EditText taskDescription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_task);
addButton = (Button)findViewById(R.id.buttonAdd);
addButton.setOnClickListener(myOnClickListener);
taskDescription = (EditText)findViewById(R.id.editTask);
}
private View.OnClickListener myOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
String taskData = taskDescription.getText().toString();
if(!taskData.isEmpty()) {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
i.putExtra("Task",taskData);
setResult(1,i);
}
finish();
}
};
}
<file_sep>package com.shenkar.laurachiche.viewlist_task;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.inputmethodservice.InputMethodService;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ListView;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
private IToDoListController controller;
private Button buttonAdd;
private RecyclerView recycleView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonAdd = (Button)findViewById(R.id.addTaskbutton);
buttonAdd.setOnClickListener(myClickListener);
recycleView = (RecyclerView)findViewById(R.id.recycleView);
controller = new ToDoListController(1);
recycleView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
recycleView.setLayoutManager(mLayoutManager);
mAdapter = new ToDoListBaseAdapter(controller.GetTask());
recycleView.setAdapter(mAdapter);
}
/* @Override
protected void onResume() {
super.onResume();
}
*/
private View.OnClickListener myClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(getApplicationContext(),AddTask.class),1);
//startActivity(new Intent(getApplicationContext(),AddTask.class));
}
};
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode ==1 && resultCode == 1) {
String result = data.getStringExtra("Task");
if(!result.isEmpty()) {
controller.AddTask(result);
}
}
mAdapter.notifyDataSetChanged();
super.onActivityResult(requestCode, resultCode, data);
}
}
| 807509e490372fca51d9fe714ab0daba88191c68 | [
"Java"
] | 2 | Java | lully1008/ViewList_Task | e36348a5db258defc437728690ba67a635ccb419 | d7bacef6f777ea3ec68e0642fe5c4f434957bf9e |
refs/heads/master | <file_sep>module EY
VERSION = '1.4.23.pre'
end
| bce251e236a9a7350c055f6995a22e5a8b139f84 | [
"Ruby"
] | 1 | Ruby | jmartelletti/engineyard | 319a83af6074becd4a0c43f1dd0d8983ced296cc | d87f7b231229843690d1f713ed0f93be08de36b2 |
refs/heads/master | <repo_name>PaulSpuzello/DogDaycare<file_sep>/DDCare/src/Dog.java
public class Dog {
String fName = "", lName = "", dogName = "", dogBreed = "";
public Dog() {
fName = "";
lName = "";
dogName = "";
dogBreed = "";
}
public Dog(String fname, String lname, String dogname, String dogbreed) {
fName = fname;
lName = lname;
dogName = dogname;
dogBreed = dogbreed;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getDogName() {
return dogName;
}
public void setDogName(String dogName) {
this.dogName = dogName;
}
public String getDogBreed() {
return dogBreed;
}
public void setDogBreed(String dogBreed) {
this.dogBreed = dogBreed;
}
public String print() {
return " Owner's name: " + fName + " " + lName + "\n" + " Pet name: " + dogName
+ "\n" + " Breed: " + dogBreed + "\n";
}
}
<file_sep>/README.md
# DogDaycare
A Java application I made in my spare time that acts as a list of dogs at the daycare. You can add/remove/view/sort the dog name or the owner's name. Used the local host and MySQL Workbench for the Database.
| 6077793a9e755b1c255aa896cb5b3b25efbff3b1 | [
"Markdown",
"Java"
] | 2 | Java | PaulSpuzello/DogDaycare | fb17a3de3f80897be8e6b2dc4462ed644fe27346 | 4209494bf6f5bf244fa07af1a91e9fac2ab157b4 |
refs/heads/master | <file_sep>
class Solution(object):
def main(self):
if __name__ == "__main__":
main(object) | 7914c488faab6f2e925c0cb2e9b724485a577b35 | [
"Python"
] | 1 | Python | PreethamMadupuri91/PrincipalComponents | 3053c7f80a10b5404b5aba61d0b74484846514c6 | 51f4e67bbc0ca73b68cc7a91ead8f5db5eb0cd1d |
refs/heads/master | <repo_name>qadahtm/rdma-nnmsg<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
project(rdma-nnmsg)
set(CMAKE_CXX_STANDARD 11)
#set(CMAKE_BUILD_TYPE RelWithDebInfo)
set(CMAKE_BUILD_TYPE Debug)
# Organize built files
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
# Include and link libraries
include_directories(.)
include_directories(./nanomsg-1.1.4/include)
link_directories(./nanomsg-1.1.4/lib)
link_libraries(ibverbs nanomsg pthread)
# Configuration + Scripts files
configure_file(ifconfig.txt ifconfig.txt COPYONLY)
configure_file(run_resilient_db.py run_resilient_db.py COPYONLY)
# Build executable
add_executable(trans trans.cpp)
<file_sep>/run_resilient_db.py
import os
import sys
import time
cpu = [3,6,7,10,11]
def __main__(cpu,replica=5):
create_ifconfig(cpu,replica)
time.sleep(5)
create_bash_scripts(cpu, replica)
command = ''
for x in range(replica - 1):
command += 'sbatch s' + str(x) + '.sh && sleep 2 &&'
command += 'sbatch s' + str(replica - 1) + '.sh'
num = 0
# for y in range(replica,replica+client - 1):
# command += 'sbatch c' + str(y-replica) + '.sh && '
# num += 1
# command += 'sbatch c' + str(num) + '.sh'
#print(command)
stream = os.popen(command)
stream = stream.read()
print(stream)
def create_ifconfig(cpu, replica):
IP = []
for index in range(replica):
var = cpu[index]
ip = "172.19.4."+str(var + 1)+"\n"
IP.append(ip)
PATH = './ifconfig.txt'
f = open(PATH,'w')
f.writelines(IP)
f.close()
return True
def create_bash_scripts(cpu, replica):
for r in range(replica):
lines = []
lines.append("#!/bin/bash\n")
lines.append("#SBATCH --time=01:00:00\n")
lines.append("#SBATCH --nodelist=cpu-" + str(cpu[r]) + "\n")
lines.append("#SBATCH --account=cpu-s2-moka_blox-0"+"\n")
lines.append("#SBATCH --partition=cpu-s2-core-0"+"\n")
lines.append("#SBATCH --reservation=cpu-s2-moka_blox-0_18"+"\n")
lines.append("#SBATCH --mem=2G"+"\n")
lines.append("#SBATCH -o out" + str(r) + ".txt"+"\n")
lines.append("#SBATCH -e err" + str(r) + ".txt"+"\n")
lines.append("sbcast -f ifconfig.txt ifconfig.txt"+"\n")
lines.append("sleep 5"+"\n")
#lines.append("sbcast -f config.h config.h"+"\n")
lines.append("srun --nodelist=cpu-" + str(cpu[r]) + " sleep 10" + "\n")
lines.append("srun --exclusive --ntasks=1 --cpus-per-task=16 --nodelist=cpu-" + str(cpu[r]) + " singularity exec ../resilient ./bin/trans " + str(r)+"\n")
PATH = './s' + str(r) + '.sh'
f = open(PATH,'w')
f.writelines(lines)
f.close()
# for c in range(replica,replica + client):
# lines = []
# lines.append("#!/bin/bash\n")
# lines.append("#SBATCH --time=01:00:00\n")
# lines.append("#SBATCH --nodelist=cpu-" + str(cpu[c]) + "\n")
# lines.append("#SBATCH --account=cpu-s2-moka_blox-0"+"\n")
# lines.append("#SBATCH --partition=cpu-s2-core-0"+"\n")
# lines.append("#SBATCH --reservation=cpu-s2-moka_blox-0_18"+"\n")
# lines.append("#SBATCH --mem=2G"+"\n")
# lines.append("#SBATCH -o out" + str(c) + ".txt"+"\n")
# lines.append("#SBATCH -e err" + str(c) + ".txt"+"\n")
# lines.append("sbcast -f ifconfig.txt ifconfig.txt"+"\n")
# lines.append("sleep 5"+"\n")
# #lines.append("sbcast -f config.h config.h"+"\n")
# lines.append("srun --nodelist=cpu-" + str(cpu[c]) + " sleep 10" + "\n")
# lines.append("srun --exclusive --ntasks=1 --cpus-per-task=16 --nodelist=cpu-" + str(cpu[c]) + " singularity exec resilient ./trans " + str(c)+"\n")
# PATH = './c' + str(c-replica) + '.sh'
# f = open(PATH,'w')
# f.writelines(lines)
# f.close()
return True
if(len(sys.argv) == 2):
print("Warning: rundb & runcl must be complied with correct values in config.h")
__main__(cpu,int(sys.argv[1]))
else:
print("argv={}".format(sys.argv))
print("Command line arguments absent or invalid, please retry. \n Format: python run_resilient_db <replica> <client>")<file_sep>/README.md
# rdma-nnmsg
Nanomsg and ibverbs based implementation of RDMA for Distributed Communication
Specify NODE_CNT in rsupport.cpp
Implement desired functionalities in trans.cpp
# Requirements:
nanomsg, ibverbs libraries installed
# Compilation and Execution:
1. Install nanomsg and ibverbs library
2. Create ifconfig.txt file with all the IP addresses
g++ trans.cpp -o trans -pthread -lnanomsg -libverbs &&
./trans <NODE_ID>
# Features
1. Supports RDMA_Send and RDMA_Recv
2. Supports RDMA_Remote_Write and RDMA_Remote_Reads
3. Now supports Multi Memory Registrations and tested with Multi-threading
## Dependencies
CMake (version >=3.5)
## Build instruction using
Uncompress `nanomsg` into the source directory
Create a build directory and change into it
Run to `cmake path/to/source_directory`
Run `make` to build binaries
Ensure that the singularity image `resilient` is at `../` relative to the build directory
Run `python run_resilient_db.py 5` | ec81b5055323b680a5cf4c287cde3883831a14ca | [
"Markdown",
"Python",
"CMake"
] | 3 | CMake | qadahtm/rdma-nnmsg | 67d5696e8622d4b60a1620af65fbd704cbd503ee | b28a8ccce6c562b126be7b0d381d5d3ab252ba1d |
refs/heads/master | <file_sep>import React, { useReducer } from 'react'
import { reducer, initialState } from '../reducers/Reducer'
import Moment from 'react-moment'
import AddTodoForm from './AddTodoForm'
const Todos = () => {
//STATE AND REDUCER
const [state, dispatch] = useReducer(reducer, initialState)
//ADD TODO
const addTodo = (item, date) => {
const newTodo = {
item: item,
completed: false,
id: Date.now(),
completeBy: date
}
dispatch({ type: 'ADD_TODO', todo: newTodo })
}
//TOGGLE COMPLETED
const toggleCompleted = (id) => {
dispatch({ type: 'TOGGLE_COMPLETED', id: id })
}
//CLEAR COMPLETED
const clearCompleted = () => {
dispatch({ type: 'CLEAR_COMPLETED' })
}
return (
<div>
<AddTodoForm addTodo={addTodo}/>
<h2>Todos</h2>
{state.todos.map(todo => {
return <div className="todo" key={todo.id} onClick={() => toggleCompleted(todo.id)} >
{todo.completeBy < Date.now() ? <h6>OVERDUE</h6> : null}
<h3 className={todo.completed === true ? 'completed' : null}>{todo.item}</h3>
<h6>Complete by: {<Moment format="MMM Do YYYY" date={todo.completeBy}/>}</h6>
</div>
})}
<button onClick={() => clearCompleted()}>Clear Completed</button>
</div>
)
}
export default Todos<file_sep>import React, { useState } from 'react'
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
const AddTodoForm = ({ addTodo }) => {
const [item, setItem] = useState("")
const [date, setDate] = useState(Date.now())
//HANDLE INPUT CHANGE
const handleChange = (e) => {
setItem(e.target.value)
}
//HANDLE FORM SUBMIT
const handleSubmit = (e) => {
e.preventDefault();
addTodo(item, date);
setItem("");
}
//HANDLE DATE CHANGE
const handleDateChange = newDate => {
setDate(newDate)
}
return (
<div>
<form onSubmit={e => handleSubmit(e)}>
<h3>Add new todo</h3>
<input name="title" type="text" value={item} onChange={e => handleChange(e)} placeholder="Todo Title"/>
<h5>Complete By:</h5>
<DatePicker selected={date} onChange={handleDateChange} minDate={Date.now()}/>
<button type="submit">Add Todo</button>
</form>
</div>
)
}
export default AddTodoForm<file_sep>export const initialState = {
todos: [
{
item: 'Learn about reducers',
completed: false,
id: 3892987589,
completeBy: new Date('2020-01-28')
}
]
}
export const reducer = (state, action) => {
switch(action.type) {
//ADD TODO
case 'ADD_TODO':
return { todos: [...state.todos, action.todo] }
//TOGGLE COMPLETED
case 'TOGGLE_COMPLETED':
let newTodos = state.todos.map(todo => {
if(todo.id === action.id) {
todo.completed = !todo.completed;
return todo;
}
return todo;
})
return { todos: newTodos }
//CLEAR COMPLETED
case 'CLEAR_COMPLETED':
let notCompletedTodos = state.todos.filter(todo => {
return todo.completed === false;
})
return { todos: notCompletedTodos }
//DEFAULT CASE
default:
return state;
}
} | 7dfa507e43f4c9678130be2b31567840f5f15984 | [
"JavaScript"
] | 3 | JavaScript | DustinG98/reducer-todo | 4395e25a02e63216015f4cb657ab7dbbbe1bfdfe | ed80562708b74771672d15221736761327d3240b |
refs/heads/master | <file_sep><!DOCTYPE html>
<html>
<head>
<title>CRUD Petani Kode</title>
<link rel="icon" href="http://www.petanikode.com/favicon.ico" />
</head>
<body>
<h3>CRUD Sederhana</h3>
<a href="tambah.php">+ Tambah data Categori</a> |
<a href="tambahpenulis.php">+ Tambah data Penulis</a>
<br/>
<br/>
<table border="1">
<tr>
<th>NO</th>
<th>Nama Buku</th>
<th>Categori</th>
<th>Penulis</th>
<th>Tahun Publikasi</th>
<th>Gambar</th>
<th>OPSI</th>
</tr>
<?php
// --- koneksi ke database
$koneksi = mysqli_connect("localhost","root","root","dbdumbways") or die(mysqli_error());
$query = "SELECT book_tb.name as nmbook, category_tb.name as nmcategory, writer_tb.name as nmwriter, publication_year, img from book_tb
left join category_tb on book_tb.category_id = category_tb.id
left join writer_tb on book_tb.writer_id = writer_tb.id";
$no = 1;
$data = mysqli_query($koneksi,$query);
while($d = mysqli_fetch_array($data)){
?>
<tr>
<td><?php echo $no++; ?></td>
<td><?php echo $d['nmbook']; ?></td>
<td><?php echo $d['nmcategory']; ?></td>
<td><?php echo $d['nmwriter']; ?></td>
<td><?php echo $d['publication_year']; ?></td>
<td><?php echo $d['img']; ?></td>
<td>To Do list</td>
</tr>
<?php
}
?>
</table>
</body>
</html> | a01899267edbf090d2f48283d1b54d80c76124e8 | [
"PHP"
] | 1 | PHP | cahyowijaya/dumbways | 2f73dd52587423a06539e287ba1b4ff7ecfe81d0 | cbdee5531354413bf7ca67fa9bff85f5d96ca24c |
refs/heads/master | <file_sep>var ObstacleCircle = function(x, y, size){
this.x = x;
this.y = y;
this.size = size;
this.color = "#000000"
}
ObstacleCircle.prototype.draw = function(){
cm.gc.ctx.beginPath();
cm.gc.ctx.arc(this.x, this.y, 50*Math.abs(this.size), 0, 2 * Math.PI, false);
cm.gc.ctx.fillStyle = this.color;
cm.gc.ctx.fill();
cm.gc.ctx.closePath();
}
var UnplacedObstacleCircle = function(x,y,size){
this.x = x;
this.y = y;
this.size = size;
}
UnplacedObstacleCircle.prototype.draw = function(){
cm.ui.ctx.beginPath();
cm.ui.ctx.arc(this.x, this.y, 50*Math.abs(this.size), 0, 2 * Math.PI, false);
cm.ui.ctx.fillStyle = 'black';
cm.ui.ctx.fill();
cm.ui.ctx.closePath();
}
<file_sep>// var canvasWidth = $(window).width() * .77
// var canvasHeight = $(window).height() * 1
var Canvas = function(elementId){
this.mycanvas = document.getElementById(elementId);
this.ctx = document.getElementById(elementId).getContext('2d');
}
// var cv = {
// mycanvas: document.getElementById('mycanvas'),
// ctx: document.getElementById('mycanvas').getContext('2d'),
// width: canvasWidth,
// height: canvasHeight
// }
// var ui = {
// mycanvas: document.getElementById('uicanvas'),
// ctx: document.getElementById('uicanvas').getContext('2d'),
// width: canvasWidth,
// height: canvasHeight
// }
// var gc = {
// mycanvas: document.getElementById('gravitycanvas'),
// ctx: document.getElementById('gravitycanvas').getContext('2d'),
// width: canvasWidth,
// height: canvasHeight
// }
// var resizeCanvas = function(){
// var canvasWidth = $(window).width() * .77
// var canvasHeight = $(window).height() * 1
// ui.width = canvasWidth;
// ui.height = canvasHeight;
// cv.width = canvasWidth;
// cv.height = canvasHeight;
// gc.width = canvasWidth;
// gc.height = canvasHeight;
// ui.mycanvas.width = ui.width;
// ui.mycanvas.height = ui.height;
// cv.mycanvas.width = cv.width;
// cv.mycanvas.height = cv.height;
// gc.mycanvas.width = gc.width;
// gc.mycanvas.height = gc.height;
// }
<file_sep>var preset2 = function(){
cm.infinite = true;
clearInterval(cm.infiniteLoop)
cm.infiniteLoop = setInterval(addBall, cm.spread);
cm.noGravity = true;
cm.gravity = 0;
$(".disable-gravity").prop("checked", false)
$("#background-color-picker").spectrum("set", "rgb(0,0,0)");
$("ball-max-color").spectrum("set", "rgb(255,255,255)");
$("ball-min-color").spectrum("set", "rgb(255,255,255)");
$("#fade").val(0)
getSliderValues()
cm.maxColor = "#ffffff"
cm.minColor = "#ffffff"
cm.backgroundColor = parseBackgroundColor($("#background-color-picker").spectrum("get"));
cm.cv.ctx.fillStyle = '#000000';
cm.cv.ctx.fillRect(0,0,cm.canvasWidth, cm.canvasHeight)
cm.centersOfGravity.push(new gravityCenter(cm.canvasWidth/2, cm.canvasHeight/2, 10));
cm.obstaclesCircles.push(new ObstacleCircle(cm.canvasWidth/2, cm.canvasHeight/2, 4))
cm.startX = cm.canvasWidth/2;
cm.startY = cm.canvasHeight/2 - 300;
var func1 = setTimeout(function(){cm.obstaclesCircles = [];}, 7000)
var funct2 = setTimeout(function(){cm.infinite = false;
clearInterval(cm.infiniteLoop)}, 16000)
cm.timeoutArray.push(func1)
cm.timeoutArray.push(func2)
}
<file_sep>$(document).ready(function(){
// reset();
// clearInterval(cm.gameLoop);
// clearInterval(cm.fadeLoop);
var backgroundPicker = $("#background-color-picker").spectrum({
preferredFormat: "rgb",
showInput: true,
showButtons: false,
color: "#000000"
})
var ballMaxPicker = $("#ball-max-color").spectrum({
preferredFormat: "hex",
showInput: true,
showButtons: false,
color: "#000000"
})
var ballMinPicker = $("#ball-min-color").spectrum({
preferredFormat: "hex",
showInput: true,
showButtons: false,
color: "#000000"
})
// getSliderValues();
// cm.start();
// cm.infinite = true;
// cm.spread = $("#spread").val();
// cm.infiniteLoop = setInterval(addBall, spread);
$(".add-ball").on("click", function(event){
event.preventDefault();
updateSettings();
addBall();
})
$(".update-settings").on("click", function(event){
event.preventDefault();
updateSettings();
})
$(".clear").on('click', function(event){
event.preventDefault();
cm.balls = [];
})
$(".quick-add").on("click", function(event){
event.preventDefault();
updateSettings();
var times = parseInt($(this).attr("balls"));
var spread = $("#spread").val();
for(var i = 0; i < times;i++){
setTimeout(function(){cm.balls.push(new Ball(cm.forceX, cm.forceY))}, spread*i);
}
})
$(".infinite").on("click", function(event){
event.preventDefault();
cm.infinite = !cm.infinite;
updateSettings();
clearInterval(cm.infiniteLoop);
if(cm.infinite){
var spread = $("#spread").val();
cm.infiniteLoop = setInterval(addBall, spread);
$(".infinite").html("Infinite Flow (on)")
} else {
$(".infinite").html("Infinite Flow (off)")
}
})
$("#uicanvas").on("click", function(e){
var rect = this.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
if(cm.placingGravs === true){
var strength = ($(".gravity-well-strength").val() * .05);
if($(".gravity-well-static").is(":checked")){
// var absorb = $(".gravity-well-absorb").is(":checked");
cm.centersOfGravity.push(new gravityCenter(x,y, strength))
}else{
cm.centersOfGravity.push(new MoveableGravityCenter(x,y,strength))
}
} else if(cm.placingClusters){
var density = 10 - parseInt($(".cluster-density").val());
cm.uiElement.execute(density, 5, 5);
}else if(cm.placingSpawn){
cm.startX = x;
cm.startY = y;
// applyImpulse(x, y);
}else if(cm.placingObstacles){
var size = parseInt($(".obstacle-size").val());
cm.obstaclesCircles.push(new ObstacleCircle(x,y,size))
}
})
$("#uicanvas").on("mouseenter", function(e){
var rect = this.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
if(cm.placingGravs){
var strength = ($(".gravity-well-strength").val() * .05);
cm.uiElement = new UnplacedGrav(x,y, strength);
cm.uiElement.draw()
cm.drawUiElement = true;
} else if(cm.placingClusters) {
var size = parseInt($(".cluster-size").val());
cm.uiElement = new UnplacedCluster(x,y,size);
cm.uiElement.draw();
cm.drawUiElement = true;
} else if(cm.placingObstacles) {
var size = parseInt($(".obstacle-size").val());
cm.uiElement = new UnplacedObstacleCircle(x,y,size)
cm.uiElement.draw()
cm.drawUiElement = true;
}
})
$("#uicanvas").on("mousemove", function(e){
var rect = this.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
if(cm.placingGravs){
var strength = ($(".gravity-well-strength").val() * .05);
cm.uiElement.x = x;
cm.uiElement.y = y;
cm.uiElement.strength = strength;
} else if(cm.placingClusters) {
var size = (parseInt($(".cluster-size").val()));
cm.uiElement.x = x;
cm.uiElement.y = y;
cm.uiElement.size = size;
} else if(cm.placingObstacles) {
var size = parseInt($(".obstacle-size").val());
cm.uiElement.x = x;
cm.uiElement.y = y;
cm.uiElement.size = size;
}
})
$("#uicanvas").on("mouseleave", function(e){
cm.ui.ctx.clearRect(0,0,cm.canvasWidth, cm.canvasHeight)
cm.drawUiElement = false;
cm.uiElement = null;
})
// Not Working Yet
$(window).on("scroll", function(event){
// event.preventDefault()
console.log("SCROLLING")
if(cm.placingGravs){
var currentVal = $(".gravity-well-strength").val();
$(".gravity-well-strength").val(currentVal + 1)
}
})
$("#gravity-settings").on("click", function(event){
event.preventDefault();
clearTools();
hideAllSettings();
$(".gravity-settings").addClass("visible")
cm.placingGravs = true;
})
$(".clear-gravity-wells").on("click", function(event){
event.preventDefault();
cm.centersOfGravity = [];
})
$(".hide-gravs").on("click", function(event){
event.preventDefault();
cm.showGravs = !cm.showGravs
if($(this).html() === "Hide Gravity Wells"){
$(this).html("Show Gravity Wells")
}else{
$(this).html("Hide Gravity Wells")
}
})
$(".disable-gravity").on("change", function(event){
event.preventDefault();
cm.gravity = 0;
cm.noGravity = !cm.noGravity;
})
$(".border-toggle").change(function(){
cm.borderOn = !cm.borderOn;
})
backgroundPicker.on("move.spectrum", function(e, color) {
cm.backgroundColor = parseBackgroundColor(color)
// var backgroundChoice = color.toRgbString().split("");
// backgroundChoice.splice(3,0,"a")
// backgroundChoice.splice(-1,1,", 0.1)")
// backgroundColor = backgroundChoice.join("");
// backgroundColor = ["rgba(", color._r.toFixed() + ", ", + color._g.toFixed() + ", ", + color._b.toFixed() + ", ", + "0.1", ")"]
})
ballMinPicker.on("move.spectrum", function(e, color) {
cm.minColor = "#" + color.toHex()
})
ballMaxPicker.on("move.spectrum", function(e, color) {
cm.maxColor = "#" + color.toHex()
})
$(window).on("resize", function(){
cm.resizeCanvas();
})
// $(".gravity-well-strength").on('input propertychange paste', function() {
// if(parseInt($(this).val()) > 10){ $(this).val(10) }
// if(parseInt($(this).val()) < 1 ){ $(this).val(1) }
// });
$("#cluster-holder").on("click", function(event){
event.preventDefault();
clearTools();
hideAllSettings();
$(".cluster-holder").addClass("visible")
cm.placingClusters = true;
})
$(".tool").on("click", function(){
$(".tool").removeClass("active-tool")
$(this).addClass("active-tool")
})
$("#spawn-settings").on("click", function(event){
event.preventDefault();
clearTools();
hideAllSettings();
$(".spawn-settings").addClass("visible")
cm.placingSpawn = true;
})
$("#color-schema").on("click", function(event){
event.preventDefault();
clearTools();
hideAllSettings();
$(".color-schema").addClass("visible")
})
$(".preset-launch").on("click", function(){
clearCanvas();
var presetNum = $(".preset-select").val();
window['preset' + presetNum]()
})
$("input[type=range], input[type=checkbox]").on("change", function(){
updateSettings();
})
$("input[type=checkbox]").on("change", function(){
updateSettings()
})
$("#spread").on("change", function(){
updateSettings();
if(cm.infinite){
clearInterval(cm.infiniteLoop);
cm.infiniteLoop = setInterval(addBall, cm.spread);
console.log(cm.spread)
}
})
$("#obstacles-holder").on("click", function(){
clearTools();
hideAllSettings();
$(".obstacles-holder").addClass("visible");
cm.placingObstacles = true;
})
$(".clear-obstacle-circles").on("click", function(){
cm.obstaclesCircles = []
})
$(".disable-fade").on("change", function(event){
event.preventDefault();
cm.noFade = !cm.noFade;
if(cm.noFade){clearInterval(cm.fadeLoop)}
updateSettings()
})
$(".reset").on("click", function(event){
event.preventDefault();
clearCanvas();
})
})
var getSliderValues = function(){
var gravityModifier = $("#gravity").val();
var dragModifier = $("#drag").val();
var forceXModifier = $("#forceX").val();
var forceYModifier = $("#forceY").val();
var thicknessModifier = $("#thickness").val();
cm.spread = $("#spread").val();
cm.threshold = $("#threshold").val() / 10;
cm.fade = (Math.abs($("#fade").val()) * .01).toString();
cm.dampX = 1 - ($("#dampX").val() * .01);
cm.dampY = -1 - ($("#dampY").val() * -.01);
cm.variation = $("#variation").val() * .01;
cm.lifetime = parseInt($("#lifetime").val());
cm.forceX = forceXModifier/12.5;
cm.forceY = forceYModifier/12.5;
cm.drag = dragModifier/15 * .001;
cm.thickness = thicknessModifier;
if(!cm.noGravity){cm.gravity = gravityModifier/25 * 0.04;}
}
var updateSettings = function(){
clearInterval(cm.fadeLoop);
// reset();
getSliderValues();
// if(!noFade){fadeLoop = setInterval(fadeOut, fade)};
}
var addBall = function(){
// updateSettings();
var ball = new Ball(cm.forceX, cm.forceY)
cm.balls.push(ball);
}
var clearTools = function(){
cm.placingSpawn = false;
cm.placingClusters = false;
cm.placingGravs = false;
cm.placingObstacles = false;
}
var hideAllSettings = function(){
$(".settings").removeClass("visible")
}
<file_sep># Cascading Pixels
This project began by experimenting with the JavaScript canvas and has turned into an experiment in basic physics simulation.
The aim is to provide the user with a meaningful set of tools to interact with the physics sandbox.











<file_sep>var preset3 = function(){
cm.infinite = false;
clearInterval(cm.infiniteLoop)
$("#background-color-picker").spectrum("set", "rgb(0,0,0)");
$("ball-max-color").spectrum("set", "rgb(255,0,0)");
$("ball-min-color").spectrum("set", "rgb(255,255,255)");
cm.borderOn = false;
$(".border-toggle").prop("checked", false)
cm.maxColor = "#ff0000"
cm.minColor = "#ffffff"
cm.backgroundColor = parseBackgroundColor($("#background-color-picker").spectrum("get"));
cm.cv.ctx.fillStyle = '#000000';
cm.cv.ctx.fillRect(0,0,cm.canvasWidth, cm.canvasHeight)
var x = 0
var y = (cm.canvasHeight)
var size = cm.canvasWidth/140;
cm.obstaclesCircles.push(new ObstacleCircle(x,y, size))
x = cm.canvasWidth
y = cm.canvasHeight
cm.obstaclesCircles.push(new ObstacleCircle(x,y, size))
x = cm.canvasWidth/2
y = cm.canvasHeight/2 - 100
size = cm.canvasWidth/400;
cm.obstaclesCircles.push(new ObstacleCircle(x,y, size))
x = cm.canvasWidth/8
y = cm.canvasHeight/4
size = cm.canvasWidth/1000;
cm.obstaclesCircles.push(new ObstacleCircle(x,y, size))
x = 7*(cm.canvasWidth/8)
y = cm.canvasHeight/4
cm.obstaclesCircles.push(new ObstacleCircle(x,y, size))
x = cm.canvasWidth/2
y = 7*(cm.canvasHeight/8)
cm.obstaclesCircles.push(new ObstacleCircle(x,y, size))
for(var i = 0; i < 10; i++){
var place = setTimeout(function(){
var unplaced = new UnplacedCluster((cm.canvasWidth * Math.random()), -100, 10)
unplaced.execute(5, 5, 5);
}, 4000*i)
cm.timeoutArray.push(place);
}
}
<file_sep>var Ball = function(forceX, forceY, x, y){
this.x = x || cm.startX;
this.y = y || cm.startY;
this.gravity = cm.gravity * Math.random();
this.speedX = 0;
this.speedY = 0;
this.forceX = forceX + Math.random() * .05;
this.forceY = forceY + Math.random() * .05;
this.lastX = this.x;
this.lastY = this.y;
// this.lifetime = lifetime;
}
Ball.prototype.draw = function(){
if(Math.abs(this.speedX) < .1 && Math.abs(this.y - cm.canvasHeight) < 1 && Math.abs(this.speedY) < 1){
this.die();
}
var speed = Math.sqrt(Math.pow(this.speedX,2) + Math.pow(this.speedY,2));
this.gravity = cm.gravity * Math.random();
//Initial Force
if(this.forceX != 0){
this.speedX += this.forceX;
this.forceX = 0;
}
if(this.forceY != 0){
this.speedY += this.forceY;
this.forceY = 0;
}
//Reduce horizontal speed
if(this.speedX > 0){
this.speedX -= cm.drag;
} else {
this.speedX += cm.drag;
}
for(var i in cm.obstaclesCircles){
var obs = cm.obstaclesCircles[i]
var x = obs.x - this.x
var y = obs.y - this.y
var distance = Math.floor(Math.sqrt( x*x + y*y ))
if(distance < 50 * obs.size){
var normalizeFactor = Math.max(Math.abs(this.speedX), Math.abs(this.speedY))
var noramlizedX = (this.speedX / normalizeFactor)
var noramlizedY = (this.speedY / normalizeFactor)
while(distance < 50 * obs.size){
this.x -= noramlizedX
this.y -= noramlizedY
x = obs.x - this.x
y = obs.y - this.y
distance = Math.floor(Math.sqrt( x*x + y*y ))
}
var xFactor = (this.x - obs.x)/obs.size
var yFactor = (this.y - obs.y)/obs.size
var dot = -math.dot([this.speedX, this.speedY], [xFactor, yFactor])/42
this.speedX += (xFactor*(dot / 35 ) )
this.speedY += (yFactor*(dot / 35 ) )
}
}
//Apply Gravity
for(var i in cm.centersOfGravity){
var x = Math.floor(cm.centersOfGravity[i].x) - this.x
var y = Math.floor(cm.centersOfGravity[i].y) - this.y
var distance = Math.max(Math.floor(Math.sqrt( x*x + y*y )), 1);
if(distance < 1000 * cm.centersOfGravity[i].strength){
if(distance < 50 * cm.centersOfGravity[i].strength && cm.centersOfGravity[i].absorb){
cm.centersOfGravity[i].strength += .001;
this.die();
}else{
this.speedX += x/(distance*10) * cm.centersOfGravity[i].strength
this.speedY += y/(distance*10) * cm.centersOfGravity[i].strength
}
}
}
this.speedY += this.gravity;
//Bounce Off Walls
if(cm.borderOn){
if(this.x > cm.canvasWidth){
this.x = cm.canvasWidth;
this.speedX *= -1;
}
if(this.x < 0){
this.x = 0
this.speedX *= -1;
}
if(this.y >= cm.canvasHeight){
this.y = cm.canvasHeight;
this.speedY *= cm.dampY;
this.speedX *= cm.dampX;
}
if(this.y <= 0){
this.y = 0;
this.speedY *= cm.dampY;
this.speedX *= cm.dampX;
}
} else {
if(this.x > cm.canvasWidth*2 || this.x < -(cm.canvasWidth*2) || this.y >= cm.canvasHeight*2 || this.y < -(cm.canvasHeight*2)){
this.die()
}
}
//Apply speeds to coordinates
this.x += this.speedX;
this.y += this.speedY;
// Color based on speed
var colorFactor = (Math.min(speed, 8) / 8) * cm.threshold;
// console.log(colorFactor)
// console.log(Math.min(speed, 8) / 8)
var color = mixColor(cm.minColor, cm.maxColor, colorFactor);
cm.cv.ctx.strokeStyle = color;
// Circular front - Looks good but is resource intensive
// cv.ctx.beginPath();
// cv.ctx.arc(this.x, this.y, thickness/2, 0, 2 * Math.PI, false);
// cv.ctx.fillStyle = color;
// cv.ctx.fill();
// Draw path
cm.cv.ctx.beginPath();
cm.cv.ctx.moveTo(this.lastX, this.lastY);
cm.cv.ctx.lineTo(this.x, this.y);
cm.cv.ctx.stroke();
cm.cv.ctx.closePath();
this.lastX = this.x;
this.lastY = this.y;
};
Ball.prototype.die = function(){
cm.balls.splice(cm.balls.indexOf(this), 1);
}
<file_sep>var mixColor = function(hex1, hex2, factor) {
var col1, col2;
col1 = parseInt(hex1.replace(/^[#]/, ''), 16);
col2 = parseInt(hex2.replace(/^[#]/, ''), 16);
var r1, g1, b1, r2, g2, b2;
r1 = col1 >> 16 & 0xFF;
g1 = col1 >> 8 & 0xFF;
b1 = col1 & 0xFF;
r2 = col2 >> 16 & 0xFF;
g2 = col2 >> 8 & 0xFF;
b2 = col2 & 0xFF;
var nr, ng, nb;
nr = Math.round(r1 + (r2 - r1) * factor);
ng = Math.round(g1 + (g2 - g1) * factor);
nb = Math.round(b1 + (b2 - b1) * factor);
var colorInt = (nr << 16 | ng << 8 | nb)
return '#'+ ('000000' + (colorInt & 0xFFFFFF).toString(16)).slice(-6).toUpperCase();
}
var parseBackgroundColor = function(color){
// var backgroundChoice = color.toRgbString().split("");
// backgroundChoice.splice(3,0,"a")
// backgroundChoice.splice(-1,1,", 0.1)")
// return backgroundChoice.join("");
var backgroundChoice = color.toRgbString().split("");
return ["rgba(", color._r.toFixed() + ", ", + color._g.toFixed() + ", ", + color._b.toFixed() + ", ", + "0.1", ")"]
}
<file_sep>var UnplacedCluster = function(x,y,size){
this.x = x;
this.y = y;
this.size = size;
}
UnplacedCluster.prototype.draw = function(){
cm.ui.ctx.beginPath();
cm.ui.ctx.strokeStyle = 'black';
cm.ui.ctx.strokeRect(this.x - (this.size * 5), this.y - (this.size * 5), this.size * 10, this.size * 10)
}
UnplacedCluster.prototype.execute = function(density, width, height){
var leftBound = this.x - (this.size * width);
var rightBound = this.x + (this.size * width);
var upperBound = this.y - (this.size * height);
var lowerBound = this.y + (this.size * height);
for(var i = leftBound; i < rightBound; i += density){
for(var j = upperBound; j < lowerBound; j += density){
var ball = new Ball(0,0,i,j);
cm.balls.push(ball);
}
}
}
<file_sep>var preset1 = function(){
cm.infinite = false;
clearInterval(cm.infiniteLoop)
cm.noGravity = true;
cm.gravity = 0;
$(".disable-gravity").prop("checked", false)
$("#background-color-picker").spectrum("set", "rgb(0,0,0)");
$("ball-max-color").spectrum("set", "rgb(255,255,255)");
$("ball-min-color").spectrum("set", "rgb(255,255,255)");
cm.maxColor = "#ffffff"
cm.minColor = "#ffffff"
cm.backgroundColor = parseBackgroundColor($("#background-color-picker").spectrum("get"));
cm.cv.ctx.fillStyle = '#000000';
cm.cv.ctx.fillRect(0,0,cm.canvasWidth, cm.canvasHeight)
var x1 = (cm.canvasWidth/2) - (525/2)
var y1 = (cm.canvasHeight/2)
var x2 = (cm.canvasWidth/2) + (525/2)
var y2 = (cm.canvasHeight/2)
cm.centersOfGravity.push(new gravityCenter(x1,y1,10));
cm.centersOfGravity.push(new gravityCenter(x2,y2,10));
var unplaced = new UnplacedCluster(cm.canvasWidth/2 + 50, cm.canvasHeight/2 - 10, 5)
unplaced.execute(5, 20, 15);
var unplaced = new UnplacedCluster(cm.canvasWidth/2 - 50, cm.canvasHeight/2 + 10, 5)
unplaced.execute(5, 20, 15);
}
| 701f1ce1006ce823b302c95faa2f90546975d43c | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | DavidMcLaughlin208/cascading-pixels | 08d49d675d1771ec37d7c1093ca3b48b6ff8a8fe | 7a00a71f1a308af9790cf658f6e9e500ef32e5ce |
refs/heads/master | <file_sep>// login-popup-realisation
var openlink = document.querySelector('.popup-login-open-btn');
var popup = document.querySelector('.popup-login');
var closelink = popup.querySelector('.popup-login-close-btn');
var loginfield = popup.querySelector('.login-field');
var passwordfield = popup.querySelector('.password-field');
var form = popup.querySelector('#popup-login-form');
openlink.addEventListener('click', function() {
event.preventDefault();
popup.classList.add('popup-login-open');
loginfield.focus();
});
closelink.addEventListener('click', function() {
event.preventDefault();
popup.classList.remove('popup-login-open');
popup.classList.remove('popup-login-error');
})
form.addEventListener('submit', function() {
event.preventDefault();
if (!loginfield.value || !passwordfield.value) {
popup.classList.add('popup-login-error');
}
})
// end of login-popup-realisation
// sidebar-checkbox visual realisation
checkbox = document.getElementsByClassName('producers-checkbox');
for (var i=0; i < checkbox.length; i++) {
checkbox[i].addEventListener('click', function() {
event.preventDefault();
if (!this.classList.contains('producers-checkbox-checked')) {
this.classList.add('producers-checkbox-checked');
} else {
this.classList.remove('producers-checkbox-checked');
}
});
}
//end of sidebar-checkbox visual realisation
// sidebar-product-groups-selector realisation
selector = document.getElementsByClassName('product-groups-selector');
for (var i=0; i < selector.length; i++) {
selector[i].addEventListener('click', function () {
event.preventDefault();
if (!this.classList.contains('product-groups-selector-checked')) {
this.classList.add('product-groups-selector-checked');
} else {
this.classList.remove('product-groups-selector-checked');
}
})
}
// end of sidebar-product-groups-selector realisation | a385dd45b286ce03acd274ab96c5552efc24b3a9 | [
"JavaScript"
] | 1 | JavaScript | bloodflood/barbershop | dcf84042de530c8bb2ba6aa167f28f616b72a724 | 02979b64d5664a41d15b127e1e42bbbbca8ba118 |
refs/heads/master | <file_sep>package com.mattkuo.wheredatbus.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.mattkuo.wheredatbus.R;
import com.mattkuo.wheredatbus.protobuff.ProtoStop;
import java.util.ArrayList;
public class SearchListAdapter extends ArrayAdapter<ProtoStop> {
Context mContext;
public SearchListAdapter (Context context, ArrayList<ProtoStop> routes) {
super(context, 0, routes);
mContext = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context
.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_search_list_row, null);
}
ProtoStop ps = getItem(position);
TextView text = (TextView) convertView.findViewById(R.id.adapter_search_list_row_text);
text.setText(ps.stop_code + " - " + ps.stop_name);
return convertView;
}
}
<file_sep>package com.mattkuo.wheredatbus.data;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.mattkuo.wheredatbus.model.Stop;
import java.lang.reflect.Type;
public class StopDeserializer implements JsonDeserializer<Stop> {
@Override
public Stop deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
final JsonObject jsonObject = json.getAsJsonObject();
final int stopCode = jsonObject.get("StopNo").getAsInt();
final String name = jsonObject.get("Name").getAsString();
final double latitude = jsonObject.get("Latitude").getAsDouble();
final double longitude = jsonObject.get("Longitude").getAsDouble();
final int wheelChair = jsonObject.get("WheelchairAccess").getAsInt();
boolean isWheelChairAccessable = wheelChair == 1;
String[] stringRoutes = jsonObject.get("Routes").getAsString().split(", ");
return new Stop(stopCode, name, latitude, longitude, isWheelChairAccessable, stringRoutes);
}
}<file_sep>package com.mattkuo.wheredatbus.data;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mattkuo.wheredatbus.interfaces.Translink;
import com.mattkuo.wheredatbus.model.Bus;
import com.mattkuo.wheredatbus.model.Stop;
import com.mattkuo.wheredatbus.model.StopSchedule;
import retrofit.RestAdapter;
import retrofit.converter.GsonConverter;
// TODO: Find a better way to create services
final public class TranslinkService {
private final static String URL = "http://api.translink.ca";
private static Translink mBusService = null;
private static Translink mStopScheduleService = null;
private static Translink mStopService = null;
private TranslinkService() {}
public static Translink getBusService() {
if (mBusService == null) {
Gson gson = new GsonBuilder().registerTypeAdapter(Bus.class,
new BusDeserializer()).create();
mBusService = new RestAdapter.Builder().setEndpoint(URL).setConverter(new GsonConverter
(gson)).build().create(Translink.class);
}
return mBusService;
}
public static Translink getStopScheduleService() {
if (mStopScheduleService == null) {
Gson gson = new GsonBuilder().registerTypeAdapter(StopSchedule.class,
new StopScheduleDeserializer()).create();
RestAdapter.Builder builder = new RestAdapter.Builder();
builder.setLogLevel(RestAdapter.LogLevel.FULL).setLog(new RestAdapter.Log() {
public void log(String msg) {
Log.d("TranslinkService", msg);
}
});
mStopScheduleService = builder.setEndpoint(URL).setConverter(new GsonConverter
(gson)).build().create(Translink.class);
}
return mStopScheduleService;
}
public static Translink getStopService() {
if (mStopService == null) {
Gson gson = new GsonBuilder().registerTypeAdapter(Stop.class, new StopDeserializer()).create();
RestAdapter.Builder builder = new RestAdapter.Builder();
builder.setLogLevel(RestAdapter.LogLevel.FULL).setLog(new RestAdapter.Log() {
public void log(String msg) {
Log.d("getStopService", msg);
}
});
mStopService = builder.setEndpoint(URL).setConverter(new GsonConverter(gson)).build().create(Translink.class);
}
return mStopService;
}
}
<file_sep>package com.mattkuo.wheredatbus.model;
import java.io.Serializable;
public class Stop implements Serializable {
private int mStopCode;
private String mStopName;
private double mLatitude;
private double mLongitude;
private String[] mRoutes;
private boolean mIsWheelchairAccessable;
public Stop(int stopCode, String stopName, double latitude, double longitude, boolean isWheelchairAccessable, String[] routes) {
this.mLatitude = latitude;
this.mStopCode = stopCode;
this.mStopName = stopName;
this.mLongitude = longitude;
this.mIsWheelchairAccessable = isWheelchairAccessable;
this.mRoutes = routes;
}
public int getStopCode() {
return mStopCode;
}
public void setStopCode(int stopCode) {
mStopCode = stopCode;
}
public String getStopName() {
return mStopName;
}
public void setStopName(String stopName) {
mStopName = stopName;
}
public double getLatitude() {
return mLatitude;
}
public void setLatitude(double latitude) {
mLatitude = latitude;
}
public double getLongitude() {
return mLongitude;
}
public void setLongitude(double longitude) {
mLongitude = longitude;
}
public String[] getRoutes() {
return mRoutes;
}
public void setRoutes(String[] routes) {
this.mRoutes = routes;
}
public boolean isIsWheelchairAccessable() {
return mIsWheelchairAccessable;
}
public void setIsWheelchairAccessable(boolean isWheelchairAccessable) {
this.mIsWheelchairAccessable = isWheelchairAccessable;
}
@Override
public String toString() {
return String.valueOf(mStopCode);
}
}
<file_sep>package com.mattkuo.wheredatbus.data;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.mattkuo.wheredatbus.model.ApiError;
import java.lang.reflect.Type;
public class ApiErrorDeserializer implements JsonDeserializer<ApiError>{
@Override
public ApiError deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext
context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
String code = jsonObject.get("Code").getAsString();
String message = jsonObject.get("Message").getAsString();
return new ApiError(code, message);
}
}
<file_sep>package com.mattkuo.wheredatbus.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.mattkuo.wheredatbus.R;
import com.mattkuo.wheredatbus.model.Bus;
import java.util.ArrayList;
/**
* Adapter to hold a list of buses
*/
public class BusListAdapter extends ArrayAdapter<Bus> {
private Context mContext;
public BusListAdapter(Context context, ArrayList<Bus> buses) {
super(context, 0, buses);
mContext = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context
.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_bus_list_row, null);
}
// Configure the view for this Bus
Bus bus = getItem(position);
TextView routeNoTextView = (TextView) convertView.findViewById(R.id
.route_list_item_route_no);
routeNoTextView.setText(bus.getRouteNumber());
TextView directionTextView = (TextView) convertView.findViewById(R.id
.route_list_item_direction);
directionTextView.setText(bus.getDirection());
TextView destinationTextView = (TextView) convertView.findViewById(R.id
.route_list_item_destination);
destinationTextView.setText(bus.getDestination());
TextView timeTextView = (TextView) convertView.findViewById(R.id
.route_list_item_recorded_time);
timeTextView.setText("Last Update: " + bus.getRecordedTime());
return convertView;
}
}
<file_sep>Kê¤î¤ï¤ð¤ñ¤ò¤ó¤ô¤õ¤ö¤ü߷⪞©Ÿ„¤…¤ö¤÷¤ú¤û¤ü¤„Ξڟںâ<file_sep>include ':WhereDatBus'
<file_sep>package com.mattkuo.wheredatbus.model;
import com.google.android.gms.maps.model.LatLng;
public class Bus {
private String mVehicleNo;
private String mRouteNumber;
private String mDirection;
private String mDestination;
private LatLng mLatLng;
private String mRecordedTime;
public Bus(String vehicleNo, String routeNumber, String direction, String destination, LatLng latLng,
String recordedTime) {
mVehicleNo = vehicleNo;
mRouteNumber = routeNumber;
mDirection = direction;
mDestination = destination;
mLatLng = latLng;
mRecordedTime = recordedTime;
}
public String getVehicleNo() {
return this.mVehicleNo;
}
public void setVehicleNo(String vehicleNo) {
mVehicleNo = vehicleNo;
}
public String getRouteNumber() {
return this.mRouteNumber;
}
public void setRouteNumber(String routeNumber) {
mRouteNumber = routeNumber;
}
public String getDirection() {
return this.mDirection;
}
public void setDirection(String direction) {
mDirection = direction;
}
public String getDestination() {
return mDestination;
}
public void setDestination(String destination) {
mDestination = destination;
}
public LatLng getLatLng() {
return mLatLng;
}
public void setLatLng(LatLng latLng) {
mLatLng = latLng;
}
public String getRecordedTime() {
return mRecordedTime;
}
public void setRecordedTime(String recordedTime) {
mRecordedTime = recordedTime;
}
@Override
public String toString() {
return mVehicleNo;
}
}
<file_sep>package com.mattkuo.wheredatbus.activities;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SearchView;
import com.mattkuo.wheredatbus.R;
import com.mattkuo.wheredatbus.data.TranslinkService;
import com.mattkuo.wheredatbus.fragments.RouteDirectoryFragment;
import com.mattkuo.wheredatbus.fragments.SearchBusStopFragment;
import com.mattkuo.wheredatbus.fragments.TransitDataMapFragment;
import com.mattkuo.wheredatbus.model.Stop;
import com.mattkuo.wheredatbus.util.Util;
import java.util.ArrayList;
import java.util.List;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class MainActivity extends Activity implements TransitDataMapFragment.MapsLoadedListener {
private SearchBusStopFragment mSearchFragment;
private RouteDirectoryFragment mRouteDirectoryFragment;
private TransitDataMapFragment mTransitDataMapFragment;
private Location mCurrentLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTransitDataMapFragment = TransitDataMapFragment.newInstance();
this.swapFragment(mTransitDataMapFragment, "NEARBY_MAP");
this.handleIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
this.handleIntent(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_routes:
if (mRouteDirectoryFragment == null) {
mRouteDirectoryFragment = RouteDirectoryFragment.newInstance();
}
this.swapFragment(mRouteDirectoryFragment, "ROUTE");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onMapsLoaded() {
}
@Override
public void onLocationUpdate(Location location) {
boolean isFirstLocationAcquired = false;
if (mCurrentLocation == null) {
mCurrentLocation = location;
isFirstLocationAcquired = true;
}
double movedDistance = Util.distance(mCurrentLocation.getLatitude(),
mCurrentLocation.getLongitude(),
location.getLatitude(),
location.getLongitude());
if (movedDistance < 250 && !isFirstLocationAcquired) return;
plotListOfStops(location.getLatitude(), location.getLongitude());
mCurrentLocation = location;
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
if (mSearchFragment == null) {
mSearchFragment = SearchBusStopFragment.newInstance(query);
} else {
mSearchFragment.search(query);
}
swapFragment(mSearchFragment, "SEARCH");
}
}
private void swapFragment(Fragment fragment, String tag) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content_frame, fragment);
if (!isTagInBackStack(tag)) transaction.addToBackStack(tag);
transaction.commit();
}
private boolean isTagInBackStack(String tag) {
if (getFragmentManager().getBackStackEntryCount() == 0) return false;
getFragmentManager().executePendingTransactions();
for (int i = 0; i < getFragmentManager().getBackStackEntryCount(); i++) {
if (getFragmentManager().getBackStackEntryAt(i).getName().equals(tag)) return true;
}
return false;
}
private void plotListOfStops(double lat, double lng) {
//Get Stops within a 800m radius
TranslinkService.getStopService().listOfStopsForLatLng(800,
Util.roundToNDecimals(lat, 6),
Util.roundToNDecimals(lng, 6),
getResources().getString(R.string.translink),
new Callback<List<Stop>>() {
@Override
public void success(List<Stop> stops, Response response) {
ArrayList<Stop> stopsList = new ArrayList<Stop>();
stopsList.addAll(stops);
mTransitDataMapFragment.plotStops(stopsList);
}
@Override
public void failure(RetrofitError error) {
// TODO: Add error checking
}
});
}
}
<file_sep>l┅血要营元摘知转鬲侏讵密栖擒溶绍剔锚莫弄篇仟泉瑟湿霜酞密受塑誊剔肘诗肘<file_sep>// Code generated by Wire protocol buffer compiler, do not edit.
// Source file: protos/Stop.proto
package com.mattkuo.wheredatbus.protobuff;
import com.squareup.wire.Message;
import com.squareup.wire.ProtoField;
import static com.squareup.wire.Message.Datatype.INT32;
import static com.squareup.wire.Message.Datatype.STRING;
public final class ProtoStop extends Message {
public static final Integer DEFAULT_STOP_CODE = 0;
public static final String DEFAULT_STOP_NAME = "";
@ProtoField(tag = 1, type = INT32)
public final Integer stop_code;
@ProtoField(tag = 2, type = STRING)
public final String stop_name;
@ProtoField(tag = 3)
public final ProtoCoordinate coordinate;
public ProtoStop(Integer stop_code, String stop_name, ProtoCoordinate coordinate) {
this.stop_code = stop_code;
this.stop_name = stop_name;
this.coordinate = coordinate;
}
private ProtoStop(Builder builder) {
this(builder.stop_code, builder.stop_name, builder.coordinate);
setBuilder(builder);
}
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (!(other instanceof ProtoStop)) return false;
ProtoStop o = (ProtoStop) other;
return equals(stop_code, o.stop_code)
&& equals(stop_name, o.stop_name)
&& equals(coordinate, o.coordinate);
}
@Override
public int hashCode() {
int result = hashCode;
if (result == 0) {
result = stop_code != null ? stop_code.hashCode() : 0;
result = result * 37 + (stop_name != null ? stop_name.hashCode() : 0);
result = result * 37 + (coordinate != null ? coordinate.hashCode() : 0);
hashCode = result;
}
return result;
}
public static final class Builder extends Message.Builder<ProtoStop> {
public Integer stop_code;
public String stop_name;
public ProtoCoordinate coordinate;
public Builder() {
}
public Builder(ProtoStop message) {
super(message);
if (message == null) return;
this.stop_code = message.stop_code;
this.stop_name = message.stop_name;
this.coordinate = message.coordinate;
}
public Builder stop_code(Integer stop_code) {
this.stop_code = stop_code;
return this;
}
public Builder stop_name(String stop_name) {
this.stop_name = stop_name;
return this;
}
public Builder coordinate(ProtoCoordinate coordinate) {
this.coordinate = coordinate;
return this;
}
@Override
public ProtoStop build() {
return new ProtoStop(this);
}
}
}
<file_sep>package com.mattkuo.wheredatbus.fragments;
import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.mattkuo.wheredatbus.R;
import com.mattkuo.wheredatbus.activities.BusStopMapActivity;
import com.mattkuo.wheredatbus.adapters.SearchListAdapter;
import com.mattkuo.wheredatbus.model.Stops;
import com.mattkuo.wheredatbus.protobuff.ProtoStop;
import java.util.ArrayList;
public class SearchBusStopFragment extends ListFragment {
private static final String TAG = "com.mattkuo.SearchBusStopFragment";
private static final String SEARCH_QUERY = "SEARCH_QUERY";
private Context mContext;
public SearchBusStopFragment() {}
public static SearchBusStopFragment newInstance(String query) {
SearchBusStopFragment fragment = new SearchBusStopFragment();
Bundle bundle = new Bundle();
bundle.putString(SEARCH_QUERY, query);
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getActivity().getApplicationContext();
String query = getArguments().getString(SEARCH_QUERY, "");
this.search(query);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search_bus_stop, container, false);
return view;
}
@Override
public void onListItemClick(ListView l, View view, int position, long id) {
int selectedStopCode = ((ProtoStop) getListAdapter().getItem(position)).stop_code;
Intent intent = new Intent(getActivity(), BusStopMapActivity.class);
intent.putExtra(BusStopMapActivity.EXTRA_BUSSTOP, selectedStopCode);
startActivity(intent);
}
public void search(String query) {
if (query.length() == 0) { return; }
Stops stops = Stops.getInstance(mContext);
ArrayList<ProtoStop> foundStops = stops.getStopsMatching(query);
ArrayAdapter<ProtoStop> stopsAdapter = new SearchListAdapter(mContext, foundStops);
setListAdapter(stopsAdapter);
}
}
<file_sep>W¼ČµŃŅÓŌÕÖ×ŲŁŚÓŹēÉ“¦ŚŪÜŻŽßąįÓŹ<file_sep>package com.mattkuo.wheredatbus.fragments;
import android.app.ListFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.mattkuo.wheredatbus.R;
import com.mattkuo.wheredatbus.activities.RouteMapActivity;
import com.mattkuo.wheredatbus.adapters.RouteListAdapter;
import com.mattkuo.wheredatbus.model.Routes;
import com.mattkuo.wheredatbus.protobuff.ProtoRoute;
import java.util.ArrayList;
import java.util.List;
public class RouteDirectoryFragment extends ListFragment {
private static final String TAG = "RouteDirectoryFragment";
public RouteDirectoryFragment() {}
public static RouteDirectoryFragment newInstance() {
return new RouteDirectoryFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Routes routes = Routes.getInstance(getActivity().getApplicationContext());
List<ProtoRoute> routeList = routes.getRoutes();
ArrayAdapter<ProtoRoute> routesAdapter = new RouteListAdapter(getActivity()
.getApplication(), new ArrayList<ProtoRoute>(routeList));
setListAdapter(routesAdapter);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_route_directory, container, false);
}
@Override
public void onListItemClick(ListView l, View view, int position, long id) {
String selectedRouteShortName = ((ProtoRoute) getListAdapter().getItem(position)).route_short;
Log.d(TAG, "SelectedID - " + selectedRouteShortName);
Intent i = new Intent(getActivity(), RouteMapActivity.class);
i.putExtra(RouteMapActivity.EXTRA_SHORT_ROUTE_NAME, selectedRouteShortName);
startActivity(i);
}
}
<file_sep>~ΡΫΚΛΜΝΞϊΟΠΤΤΤΤΰΉΖΤΤΨΤή
ΠΤγΡικ
θΤΤΤΤ½ξΤηΤΧΤ<file_sep>package com.mattkuo.wheredatbus.interfaces;
import com.mattkuo.wheredatbus.model.Bus;
import com.mattkuo.wheredatbus.model.Stop;
import com.mattkuo.wheredatbus.model.StopSchedule;
import java.util.List;
import retrofit.Callback;
import retrofit.http.GET;
import retrofit.http.Headers;
import retrofit.http.Path;
import retrofit.http.Query;
public interface Translink {
@Headers("accept: application/JSON")
@GET("/rttiapi/v1/buses")
void listOfBusForRoute(
@Query("routeNo") String routeNo,
@Query("apikey") String apiKey,
Callback<List<Bus>> callback
);
@Headers("accept: application/JSON")
@GET("/rttiapi/v1/stops/{stopCode}/estimates")
void timesForRoute(
@Path("stopCode") int stopCode,
@Query("apikey") String apiKey,
Callback<List<StopSchedule>> callback
);
@Headers("accept: application/JSON")
@GET("/rttiapi/v1/stops")
void listOfStopsForLatLng(
@Query("radius") int radius,
@Query("lat") double lat,
@Query("long") double lng,
@Query("apikey") String apiKey,
Callback<List<Stop>> callback
);
}
<file_sep>package com.mattkuo.wheredatbus.model;
import android.content.Context;
import android.util.Log;
import com.mattkuo.wheredatbus.data.WireProtoBuf;
import com.mattkuo.wheredatbus.protobuff.ProtoStop;
import com.mattkuo.wheredatbus.protobuff.ProtoStops;
import com.squareup.wire.Wire;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Stops {
private static final String TAG = "com.mattkuo.model.Stops";
private static Stops mStops;
HashMap<Integer, ProtoStop> mProtoStopHashMap = new HashMap<Integer, ProtoStop>();
private ProtoStops mProtoStops;
private Stops(Context context) {
Wire wire = WireProtoBuf.getInstance();
try {
setStops(wire.parseFrom(context.getAssets().open("stops"), ProtoStops.class));
for (ProtoStop stop : getStops().stops) {
mProtoStopHashMap.put(stop.stop_code, stop);
}
} catch (Exception localException) {
Log.e(TAG, "Cant open stops file! " + localException.getMessage(), localException);
}
}
public static Stops getInstance(Context context) {
if (mStops == null || mStops.mProtoStops == null) {
mStops = new Stops(context);
}
return mStops;
}
public ProtoStop getStop(Integer id) {
return mProtoStopHashMap.get(Integer.valueOf(id));
}
public ProtoStops getStops() {
return mProtoStops;
}
public ArrayList<ProtoStop> getStopsMatching(String id) {
ArrayList<ProtoStop> array = new ArrayList<>();
for (Map.Entry<Integer, ProtoStop> e : mProtoStopHashMap.entrySet()) {
if (e.getKey().toString().contains(id)) {
array.add(e.getValue());
}
}
return array;
}
public void setStops(ProtoStops paramStops) {
mProtoStops = paramStops;
}
}
<file_sep>9 Ô¤Ô¥Ô¼ÔµÔªÔÕ•Ô•¨ —’›’ Ô¡Ô¦Ô¥Ô˜’‹áÅã‰ã | df1e9da6ff12d685018fb167ff8e4f71ea958c76 | [
"Java",
"R",
"Gradle"
] | 19 | Java | mattkuo/wheredatbus | c5b257284d37ad719df0d8177656e09ffb170c5b | 4390ab1fb064ce1c287647b4049a922d9cfc7416 |
refs/heads/main | <file_sep>"""
@Time : 2021-01-12 16:04:23
@File : dataset.py
@Author : Abtion
@Email : <EMAIL>
"""
import torch
from torch.utils.data import Dataset, DataLoader
from .utils import load_json
class CorrectorDataset(Dataset):
def __init__(self, fp):
self.data = load_json(fp)
def __len__(self):
return len(self.data)
def __getitem__(self, index):
return self.data[index]['original_text'], self.data[index]['correct_text'], self.data[index]['wrong_ids']
def get_corrector_loader(fp, tokenizer, **kwargs):
def _collate_fn(data):
ori_texts, cor_texts, wrong_idss = zip(*data)
encoded_texts = [tokenizer.tokenize(t) for t in ori_texts]
max_len = max([len(t) for t in encoded_texts]) + 2
det_labels = torch.zeros(len(ori_texts), max_len).long()
for i, (encoded_text, wrong_ids) in enumerate(zip(encoded_texts, wrong_idss)):
for idx in wrong_ids:
margins = []
for word in encoded_text[:idx]:
if word == '[UNK]':
break
if word.startswith('##'):
margins.append(len(word) - 3)
else:
margins.append(len(word) - 1)
margin = sum(margins)
move = 0
while (abs(move) < margin) or (idx + move >= len(encoded_text)) or encoded_text[idx + move].startswith(
'##'):
move -= 1
det_labels[i, idx + move + 1] = 1
return ori_texts, cor_texts, det_labels
dataset = CorrectorDataset(fp)
loader = DataLoader(dataset, collate_fn=_collate_fn, **kwargs)
return loader
<file_sep>lxml
transformers
opencc
tqdm
<file_sep>"""
@Time : 2021-01-12 15:10:43
@File : utils.py
@Author : Abtion
@Email : <EMAIL>
"""
import json
import os
import sys
def compute_corrector_prf(results):
"""
copy from https://github.com/sunnyqiny/Confusionset-guided-Pointer-Networks-for-Chinese-Spelling-Check/blob/master/utils/evaluation_metrics.py
"""
TP = 0
FP = 0
FN = 0
all_predict_true_index = []
all_gold_index = []
for item in results:
src, tgt, predict = item
gold_index = []
each_true_index = []
for i in range(len(list(src))):
if src[i] == tgt[i]:
continue
else:
gold_index.append(i)
all_gold_index.append(gold_index)
predict_index = []
for i in range(len(list(src))):
if src[i] == predict[i]:
continue
else:
predict_index.append(i)
for i in predict_index:
if i in gold_index:
TP += 1
each_true_index.append(i)
else:
FP += 1
for i in gold_index:
if i in predict_index:
continue
else:
FN += 1
all_predict_true_index.append(each_true_index)
# For the detection Precision, Recall and F1
detection_precision = TP / (TP + FP) if (TP + FP) > 0 else 0
detection_recall = TP / (TP + FN) if (TP + FN) > 0 else 0
if detection_precision + detection_recall == 0:
detection_f1 = 0
else:
detection_f1 = 2 * (detection_precision * detection_recall) / (detection_precision + detection_recall)
print("The detection result is precision={}, recall={} and F1={}".format(detection_precision, detection_recall,
detection_f1))
TP = 0
FP = 0
FN = 0
for i in range(len(all_predict_true_index)):
# we only detect those correctly detected location, which is a different from the common metrics since
# we wanna to see the precision improve by using the confusionset
if len(all_predict_true_index[i]) > 0:
predict_words = []
for j in all_predict_true_index[i]:
predict_words.append(results[i][2][j])
if results[i][1][j] == results[i][2][j]:
TP += 1
else:
FP += 1
for j in all_gold_index[i]:
if results[i][1][j] in predict_words:
continue
else:
FN += 1
# For the correction Precision, Recall and F1
correction_precision = TP / (TP + FP) if (TP + FP) > 0 else 0
correction_recall = TP / (TP + FN) if (TP + FN) > 0 else 0
if correction_precision + correction_recall == 0:
correction_f1 = 0
else:
correction_f1 = 2 * (correction_precision * correction_recall) / (correction_precision + correction_recall)
print("The correction result is precision={}, recall={} and F1={}".format(correction_precision,
correction_recall,
correction_f1))
return detection_f1, correction_f1
def load_json(fp):
if not os.path.exists(fp):
return dict()
with open(fp, 'r', encoding='utf8') as f:
return json.load(f)
def dump_json(obj, fp):
try:
fp = os.path.abspath(fp)
if not os.path.exists(os.path.dirname(fp)):
os.makedirs(os.path.dirname(fp))
with open(fp, 'w', encoding='utf8') as f:
json.dump(obj, f, ensure_ascii=False, indent=4, separators=(',', ':'))
print(f'json文件保存成功,{fp}')
return True
except Exception as e:
print(f'json文件{obj}保存失败, {e}')
return False
def get_main_dir():
# 如果是使用pyinstaller打包后的执行文件,则定位到执行文件所在目录
if hasattr(sys, 'frozen'):
return os.path.join(os.path.dirname(sys.executable))
# 其他情况则定位至项目根目录
return os.path.join(os.path.dirname(__file__), '..')
def get_abs_path(*name):
return os.path.abspath(os.path.join(get_main_dir(), *name))
def compute_sentence_level_prf(results):
"""
自定义的句级prf,设定需要纠错为正样本,无需纠错为负样本
:param results:
:return:
"""
TP = 0.0
FP = 0.0
FN = 0.0
TN = 0.0
total_num = len(results)
for item in results:
src, tgt, predict = item
# 负样本
if src == tgt:
# 预测也为负
if tgt == predict:
TN += 1
# 预测为正
else:
FP += 1
# 正样本
else:
# 预测也为正
if tgt == predict:
TP += 1
# 预测为负
else:
FN += 1
acc = (TP + TN) / total_num
precision = TP / (TP + FP)
recall = TP / (TP + FN)
f1 = 2 * precision * recall / (precision + recall) if precision + recall != 0 else 0
print(f'Sentence Level: acc:{acc:.6f}, precision:{precision:.6f}, recall:{recall:.6f}, f1:{f1:.6f}')
return acc, precision, recall, f1
| b643c75fb4fb002f84c798ef56edb0b2e483fdc8 | [
"Python",
"Text"
] | 3 | Python | 240400968/SoftMaskedBert-PyTorch | 50cdd74ea7101f0043fdb532bfdd2381e1630105 | 47793f1fc0946ff81f6a7b6df19c5fc548a417c8 |
refs/heads/main | <file_sep># Valid-Anagram
A leet code problem to find whether given two strings are valid anagrams or not
A simple array based solution.
Runtime: 4 ms, faster than 98.79% of C++ online submissions for Valid Anagram.
Memory Usage: 7.2 MB, less than 95.68% of C++ online submissions for Valid Anagram.
- <NAME>
<file_sep>class Solution {
public:
bool isAnagram(string s, string t) {
bool ret = true;
int str1Arr[26] = {0};
int str2Arr[26] = {0};
for (int i = 0; i < s.size(); ++i) {
str1Arr[s[i] - 'a']++;
}
for (int i = 0; i < t.size(); ++i) {
str2Arr[t[i] - 'a']++;
}
for (int i = 0; i < 26; ++i) {
if (str1Arr[i] != str2Arr[i]) {
ret = false;
break;
}
}
return ret;
}
};
| 311b58ff768ef0dfc39b841062cda8a43374884a | [
"Markdown",
"C++"
] | 2 | Markdown | dgirdhar/Valid-Anagram | 642f206f88ea91318ea44c6d6aa4947592497438 | b1e5effd3ddde3509c359d0d04810ff4beb1ca54 |
refs/heads/main | <repo_name>MohanDevarajan01/SLP01<file_sep>/file01.py
print('first change')
print('error')
print('change 03'
print('change 04')
print('change 05')
<file_sep>/file2.py
print('change02')
| 3fdb5badcff5e152f72d61b591c3c0305b3cfa2a | [
"Python"
] | 2 | Python | MohanDevarajan01/SLP01 | 126abff66f722b54b61317dc473375265c43c5b6 | fe903a0e5ff12e971c5eb45373ad6019ef5f9692 |
refs/heads/master | <repo_name>elliottmyers2002/arrays<file_sep>/arrays.js
const dragons = [
{name: "draco", type: "fire", size: "large"},
{name: "neptune", type: "ice", size: "medium"},
{name: "zygor", type: "water", size: "small"},
{name: "draz", type: "fire", size: "small"},
{name: "toothless", type: "fire", size: "small"},
{name: "hydro", type: "water", size: "large"}
];
const firstDragon = dragons[0];
console.log(firstDragon.name);
//map returns a new array of the same length but with different values
const alteredDragons = dragons.map(function(dragon){
});
//filter is going to filter an array
const fireDragons = dragons.filter(function(dragon){
return dragon.type === "fire"
});
const queryURL = "user.name.firstName="
const thirdDragon = dragons[2]
console.log(thirdDragon);
<file_sep>/rockPaperScissors.js
function playRockPaperScissors(userInput){
let choices = [
"rock", "paper", "scissors"
]
let randomNum = Math.floor(Math.random()*choices.length);
const compChoice = choices[randomNum];
const potentialOutcomes = [
{user: "rock", comp: "rock", res: "tie"},
{user: "rock", comp: "paper", res: "lose"},
{user: "rock", comp: "scissors", res: "win"},
{user: "paper", comp: "rock", res: "win"},
{user: "paper", comp: "paper", res: "tie"},
{user: "paper", comp: "scissors", res: "lose"},
{user: "scissors", comp: "rock", res: "lose"},
{user: "scissors", comp: "paper", res: "win"},
{user: "scissors", comp: "scissors", res: "tie"}
]
let r = "";
potentialOutcomes.forEach(function(outcome){
if (outcome.user === userInput && outcome.comp === compChoice){
r = `user picks ${userInput} and the computer picks ${compChoice}, you ${outcome.res}`
}
});
return r;
};
const result = playRockPaperScissors("rock");
console.log(result); | da19f7fb7b1e2fe67c4e6b4c148b54d5f4748237 | [
"JavaScript"
] | 2 | JavaScript | elliottmyers2002/arrays | 9179860f58f8b9dca9f85e9ecb33d05999434146 | df95f6e71807609a97d5d3e502259f6799d43d16 |
refs/heads/master | <file_sep>using UnityEngine;
public class GameMaster : MonoBehaviour
{
[Header("Prefabs")]
public GameObject Grid_Tile_Prefab;
public GameObject Grid_Border_Prefab;
public GameObject Tetromino_Block_Prefab;
private readonly GameObject[] tetrominos = new GameObject[7];
private readonly int grid_Width = 12;
private readonly int grid_Height = 18;
private GameObject[] grid;
private bool isGameOver;
private void Start()
{
CreateTetrominos();
CreateGrid();
}
private void Update()
{
if(isGameOver)
return;
}
private void CreateTetrominos()
{
var tetrominosParent = new GameObject("Tetrominos").transform;
var I_tetromino = new GameObject("I").transform;
I_tetromino.SetParent(tetrominosParent);
tetrominos[0] = SpawnPrefabInstnace(Tetromino_Block_Prefab, I_tetromino, new Vector2(0, 0));
tetrominos[0] = SpawnPrefabInstnace(Tetromino_Block_Prefab, I_tetromino, new Vector2(0, 0));
tetrominos[0] = SpawnPrefabInstnace(Tetromino_Block_Prefab, I_tetromino, new Vector2(0, 0));
tetrominos[0] = SpawnPrefabInstnace(Tetromino_Block_Prefab, I_tetromino, new Vector2(0, 0));
var O_tetromino = new GameObject("O").transform;
O_tetromino.SetParent(tetrominosParent);
tetrominos[1] = SpawnPrefabInstnace(Tetromino_Block_Prefab, O_tetromino, new Vector2(0, 0));
tetrominos[1] = SpawnPrefabInstnace(Tetromino_Block_Prefab, O_tetromino, new Vector2(0, 0));
tetrominos[1] = SpawnPrefabInstnace(Tetromino_Block_Prefab, O_tetromino, new Vector2(0, 0));
tetrominos[1] = SpawnPrefabInstnace(Tetromino_Block_Prefab, O_tetromino, new Vector2(0, 0));
var T_tetromino = new GameObject("T").transform;
T_tetromino.SetParent(tetrominosParent);
tetrominos[2] = SpawnPrefabInstnace(Tetromino_Block_Prefab, T_tetromino, new Vector2(0, 0));
tetrominos[2] = SpawnPrefabInstnace(Tetromino_Block_Prefab, T_tetromino, new Vector2(0, 0));
tetrominos[2] = SpawnPrefabInstnace(Tetromino_Block_Prefab, T_tetromino, new Vector2(0, 0));
tetrominos[2] = SpawnPrefabInstnace(Tetromino_Block_Prefab, T_tetromino, new Vector2(0, 0));
var J_tetromino = new GameObject("J").transform;
J_tetromino.SetParent(tetrominosParent);
tetrominos[3] = SpawnPrefabInstnace(Tetromino_Block_Prefab, J_tetromino, new Vector2(0, 0));
tetrominos[3] = SpawnPrefabInstnace(Tetromino_Block_Prefab, J_tetromino, new Vector2(0, 0));
tetrominos[3] = SpawnPrefabInstnace(Tetromino_Block_Prefab, J_tetromino, new Vector2(0, 0));
tetrominos[3] = SpawnPrefabInstnace(Tetromino_Block_Prefab, J_tetromino, new Vector2(0, 0));
var L_tetromino = new GameObject("L").transform;
L_tetromino.SetParent(tetrominosParent);
tetrominos[4] = SpawnPrefabInstnace(Tetromino_Block_Prefab, tetrominosParent, new Vector2(0, 0));
tetrominos[4] = SpawnPrefabInstnace(Tetromino_Block_Prefab, tetrominosParent, new Vector2(0, 0));
tetrominos[4] = SpawnPrefabInstnace(Tetromino_Block_Prefab, tetrominosParent, new Vector2(0, 0));
tetrominos[4] = SpawnPrefabInstnace(Tetromino_Block_Prefab, tetrominosParent, new Vector2(0, 0));
var S_tetromino = new GameObject("S").transform;
S_tetromino.SetParent(tetrominosParent);
tetrominos[5] = SpawnPrefabInstnace(Tetromino_Block_Prefab, S_tetromino, new Vector2(0, 0));
tetrominos[5] = SpawnPrefabInstnace(Tetromino_Block_Prefab, S_tetromino, new Vector2(0, 0));
tetrominos[5] = SpawnPrefabInstnace(Tetromino_Block_Prefab, S_tetromino, new Vector2(0, 0));
tetrominos[5] = SpawnPrefabInstnace(Tetromino_Block_Prefab, S_tetromino, new Vector2(0, 0));
var Z_tetromino = new GameObject("Z").transform;
Z_tetromino.SetParent(tetrominosParent);
tetrominos[6] = SpawnPrefabInstnace(Tetromino_Block_Prefab, Z_tetromino);
tetrominos[6] = SpawnPrefabInstnace(Tetromino_Block_Prefab, Z_tetromino);
tetrominos[6] = SpawnPrefabInstnace(Tetromino_Block_Prefab, Z_tetromino);
tetrominos[6] = SpawnPrefabInstnace(Tetromino_Block_Prefab, Z_tetromino);
}
private void CreateGrid()
{
grid = new GameObject[grid_Width * grid_Height];
var gridParent = new GameObject("Grid").transform;
gridParent.SetParent(transform);
for(int x = 0; x < grid_Width; x++)
{
for(int y = 0; y < grid_Height; y++)
{
grid[y * grid_Width + x] = SpawnPrefabInstnace(
(x == 0 || x == grid_Width - 1 || y == 0) ? Grid_Border_Prefab : Grid_Tile_Prefab,
gridParent,
new Vector2(x, y),
Quaternion.identity);
}
}
}
private GameObject SpawnPrefabInstnace(GameObject Prefab, Transform parent = null, Vector2 position = new Vector2(), Quaternion rotation = new Quaternion())
{
var newPrefabInstance = Instantiate(Prefab, position, rotation, parent);
newPrefabInstance.name = Prefab.name + " (" + position.x + " , " + position.y + " )";
return newPrefabInstance;
}
}
| f885fba835c7776cfc23ac356d0461f3095006e2 | [
"C#"
] | 1 | C# | sweet-and-salty-studios/Tetris | f24428b7aeb19afc8d9667604316a1310ff68941 | d9a37ed6c18e2477544174e6fea29b608f587740 |
refs/heads/master | <file_sep># PLOT DENSITIES
plotDensities<-function(object,log=TRUE,arrays=NULL,singlechannels=NULL,groups=NULL,col=NULL)
# Plot empirical single-channel densities
# Original version by <NAME>, 9 September 2003
# Modified by <NAME>. Last modified 1 June 2005.
{
matDensities<-function(X){
densXY<-function(Z){
zd<-density(Z,na.rm=TRUE)
x<-zd$x
y<-zd$y
cbind(x,y)
}
out<-apply(X,2,densXY)
outx<-out[(1:(nrow(out)/2)),]
outy<-out[(((nrow(out)/2)+1):nrow(out)),]
list(X=outx,Y=outy)
}
if(is(object,"MAList")) {
R <- object$A+object$M/2
G <- object$A-object$M/2
if(!log) {
R <- 2^R
G <- 2^G
}
} else {
R <- object$R
G <- object$G
if(!is.null(object$Rb)) R <- R-object$Rb
if(!is.null(object$Gb)) G <- G-object$Gb
if(log) {
R[R <= 0] <- NA
G[G <= 0] <- NA
R <- log(R,2)
G <- log(G,2)
}
}
if( is.null(arrays) & is.null(singlechannels) ){
arrays <- 1:(ncol(R))
x <- cbind(R,G)
if(is.null(groups)) {
groups <- c(length(arrays),length(arrays))
if(is.null(col))
cols <- rep(c("red","green"),groups)
if(!is.null(col)) {
if(length(col)!=2) {
warning("number of groups=2 not equal to number of col")
cols<-"black"
} else {
cols<-rep(col,groups)
}
}
} else {
if(!is.null(col)) {
if(length(as.vector(table(groups)))!=length(col)) {
warning("number of groups not equal to number of col")
cols <- col
} else {
cols <- col[groups]
}
} else {
warning("warning no cols in col specified for the groups")
cols <- "black"
}
}
}else{
if(!is.null(singlechannels)) {
if(!is.null(arrays)) warning("cannot index using arrays AND singlechannels")
x <- cbind(R,G)[,singlechannels]
if(is.null(groups)) {
groups <- c(length(intersect((1:ncol(R)),singlechannels)),
length(intersect(((ncol(R)+1):ncol(cbind(G,R))),
singlechannels)))
if(is.null(col)) cols <- rep(c("red","green"),groups)
if(!is.null(col)) {
if(length(col)!=2) {
warning("number of groups=2 not equal to number of col")
cols<-"black"
} else {
cols<-rep(col,groups)
}
}
} else {
if(!is.null(col)) {
if(length(as.vector(table(groups)))!=length(col)) {
warning("number of groups not equal to number of col")
cols <- col
} else {
cols <- col[groups]
}
} else {
print("warning no cols in col specified for the groups")
cols <- "black"
}
}
}else{
if(!is.null(arrays)) {
if(!is.null(singlechannels)) warning("cannot index using arrays AND singlechannels")
x <- cbind(R[,arrays],G[,arrays])
if(is.null(groups)) {
groups <- c(length(arrays),length(arrays))
if(is.null(col))
cols <- rep(c("red","green"),groups)
if(!is.null(col)) {
if(length(col)!=2) {
warning("number of groups=2 not equal to number of col")
cols<-"black"
} else {
cols <- rep(col,groups)
}
}
}else{
if(!is.null(col)) {
if(length(as.vector(table(groups)))!=length(col)){
warning("number of groups not equal to number of col")
cols <- "black"
}else{
cols <- col[groups]
}
}else{
warning("warning no cols in col specified for the groups")
cols <- "black"
}
}
}
}
}
dens.x<-matDensities(x)
matplot(dens.x$X,dens.x$Y,xlab="Intensity",ylab="Density",main="RG densities",type="l",col=cols,lwd=2,lty=1)
}
<file_sep>\name{blockDiag}
\alias{blockDiag}
\title{Block Diagonal Matrix}
\description{Form a block diagonal matrix from the given blocks.}
\usage{
blockDiag(...)
}
\arguments{
\item{...}{numeric matrices}
}
\value{A block diagonal matrix with dimensions equal to the sum of the input dimensions}
\examples{
a <- matrix(1,3,2)
b <- matrix(2,2,2)
blockDiag(a,b)
}
\author{<NAME>}
\seealso{
\link{10.Other}
}
\keyword{array}
<file_sep>\name{predFCm}
\alias{predFCm}
\alias{predFCm}
\title{Predictive log fold change for microarrays}
\description{
Calculates the predictive log fold change for a particular coefficient from a fit object.
}
\usage{
predFCm(fit,coef=2,prob=TRUE,VarRel=NULL)
}
\arguments{
\item{fit}{an \code{MArrayLM} fitted model object produced by \code{lmFit} or \code{contrasts.fit} and followed by \code{eBayes}}
\item{coef}{integer indicating which contrasts/columns in the fit object are to be used}
\item{prob}{logical, whether the probability that the gene is differentially expressed should be taken into account}
\item{VarRel}{string, options are "Independent" or "Increasing"}
}
\details{
The predictive log fold changes are calculated as the posterior log fold changes in the empirical Bayes hierarchical model. The log fold changes are shrunk towards zero depending on how variable they are. The \code{VarRel} argument specifies whether the prior belief is that the log fold changes are independent of the variability of the genes (option "Independent"), or whether the log fold changes increase with increasing variability of the genes (option "Increasing"). The \code{prob} argument is a logical argument indicating whether the probability that a particular gene is differentially expressed should be taken into account.
}
\value{
\code{predFCm} produces a numeric vector corresponding to the predictive or posterior log fold changes of the specified contrast
}
\seealso{
\code{\link{lmFit}}, \code{\link{eBayes}}, \code{\link{contrasts.fit}}
}
\author{<NAME> and <NAME>}
\references{
<NAME>. (2013).
\emph{Empirical Bayes modelling of expression profiles and their associations}.
PhD Thesis. University of Melbourne, Australia.
\url{http://repository.unimelb.edu.au/10187/17614}
}
\examples{
library(limma)
# Simulate gene expression data,
# 6 microarrays with 1000 genes on each array
set.seed(2004)
y<-matrix(rnorm(6000),ncol=6)
# two experimental groups and one control group with two replicates each
group<-factor(c("A","A","B","B","control","control"))
design<-model.matrix(~0+group)
colnames(design)<-c("A","B","control")
# fit a linear model
fit<-lmFit(y,design)
contrasts<-makeContrasts(A-control,B-control,levels=design)
fit2<-contrasts.fit(fit,contrasts)
fit2<-eBayes(fit2)
# output predictive log fold changes for first contrast for first 5 genes
pfc<-predFCm(fit2,coef=1,prob=FALSE)
cbind(pfc[1:5],fit2$coeff[1:5,1])
}<file_sep># SUBSET DATA SETS
assign("[.RGList",
function(object, i, j, ...) {
# Subsetting for RGList objects
# <NAME>
# 29 June 2003. Last modified 22 December 2005.
if(nargs() != 3) stop("Two subscripts required",call.=FALSE)
oc <- names(object$other)
if(missing(i))
if(missing(j))
return(object)
else {
object$R <- object$R[,j,drop=FALSE]
object$G <- object$G[,j,drop=FALSE]
object$Rb <- object$Rb[,j,drop=FALSE]
object$Gb <- object$Gb[,j,drop=FALSE]
object$weights <- object$weights[,j,drop=FALSE]
object$targets <- object$targets[j,,drop=FALSE]
for(k in oc) object$other[[k]] <- object$other[[k]][,j,drop=FALSE]
}
else {
if(is.character(i)) {
i <- match(i,rownames(object))
i <- i[!is.na(i)]
}
if(missing(j)) {
object$R <- object$R[i,,drop=FALSE]
object$G <- object$G[i,,drop=FALSE]
object$Rb <- object$Rb[i,,drop=FALSE]
object$Gb <- object$Gb[i,,drop=FALSE]
object$weights <- object$weights[i,,drop=FALSE]
object$genes <- object$genes[i,,drop=FALSE]
for(k in oc) object$other[[k]] <- object$other[[k]][i,,drop=FALSE]
} else {
object$R <- object$R[i,j,drop=FALSE]
object$G <- object$G[i,j,drop=FALSE]
object$Rb <- object$Rb[i,j,drop=FALSE]
object$Gb <- object$Gb[i,j,drop=FALSE]
object$weights <- object$weights[i,j,drop=FALSE]
object$genes <- object$genes[i,,drop=FALSE]
object$targets <- object$targets[j,,drop=FALSE]
for(k in oc) object$other[[k]] <- object$other[[k]][i,j,drop=FALSE]
}
}
object
})
assign("[.MAList",
function(object, i, j, ...) {
# Subsetting for MAList objects
# <NAME>
# 29 June 2003. Last modified 22 Dec 2005.
if(nargs() != 3) stop("Two subscripts required",call.=FALSE)
other <- names(object$other)
if(missing(i))
if(missing(j))
return(object)
else {
object$M <- object$M[,j,drop=FALSE]
object$A <- object$A[,j,drop=FALSE]
object$weights <- object$weights[,j,drop=FALSE]
object$targets <- object$targets[j,,drop=FALSE]
if(!is.null(object$design)) {
object$design <- as.matrix(object$design)[j,,drop=FALSE]
if(!is.fullrank(object$design)) warning("subsetted design matrix is singular",call.=FALSE)
}
for(a in other) object$other[[a]] <- object$other[[a]][,j,drop=FALSE]
}
else {
if(is.character(i)) {
i <- match(i,rownames(object))
i <- i[!is.na(i)]
}
if(missing(j)) {
object$M <- object$M[i,,drop=FALSE]
object$A <- object$A[i,,drop=FALSE]
object$weights <- object$weights[i,,drop=FALSE]
object$genes <- object$genes[i,,drop=FALSE]
for(a in other) object$other[[a]] <- object$other[[a]][i,,drop=FALSE]
} else {
object$M <- object$M[i,j,drop=FALSE]
object$A <- object$A[i,j,drop=FALSE]
object$weights <- object$weights[i,j,drop=FALSE]
object$genes <- object$genes[i,,drop=FALSE]
object$targets <- object$targets[j,,drop=FALSE]
if(!is.null(object$design)) {
object$design <- as.matrix(object$design)[j,,drop=FALSE]
if(!is.fullrank(object$design)) warning("subsetted design matrix is singular",call.=FALSE)
}
for(a in other) object$other[[a]] <- object$other[[a]][i,j,drop=FALSE]
}
}
object
})
assign("[.EList",
function(object, i, j, ...) {
# Subsetting for EList objects
# <NAME>
# 23 February 2009. Last modified 21 October 2010.
if(nargs() != 3) stop("Two subscripts required",call.=FALSE)
other <- names(object$other)
if(missing(i))
if(missing(j))
return(object)
else {
object$E <- object$E[,j,drop=FALSE]
object$Eb <- object$Eb[,j,drop=FALSE]
object$weights <- object$weights[,j,drop=FALSE]
object$targets <- object$targets[j,,drop=FALSE]
if(!is.null(object$design)) {
object$design <- as.matrix(object$design)[j,,drop=FALSE]
if(!is.fullrank(object$design)) warning("subsetted design matrix is singular",call.=FALSE)
}
for(a in other) object$other[[a]] <- object$other[[a]][,j,drop=FALSE]
}
else {
if(is.character(i)) {
i <- match(i,rownames(object))
i <- i[!is.na(i)]
}
if(missing(j)) {
object$E <- object$E[i,,drop=FALSE]
object$Eb <- object$Eb[i,,drop=FALSE]
object$weights <- object$weights[i,,drop=FALSE]
object$genes <- object$genes[i,,drop=FALSE]
for(a in other) object$other[[a]] <- object$other[[a]][i,,drop=FALSE]
} else {
object$E <- object$E[i,j,drop=FALSE]
object$Eb <- object$Eb[i,j,drop=FALSE]
object$weights <- object$weights[i,j,drop=FALSE]
object$genes <- object$genes[i,,drop=FALSE]
object$targets <- object$targets[j,,drop=FALSE]
if(!is.null(object$design)) {
object$design <- as.matrix(object$design)[j,,drop=FALSE]
if(!is.fullrank(object$design)) warning("subsetted design matrix is singular",call.=FALSE)
}
for(a in other) object$other[[a]] <- object$other[[a]][i,j,drop=FALSE]
}
}
object
})
assign("[.EListRaw", get("[.EList"))
assign("[.MArrayLM",
function(object, i, j, ...)
# Subsetting for MArrayLM objects
# <NAME>
# 26 April 2005. Last modified 28 September 2013.
{
if(nargs() != 3) stop("Two subscripts required",call.=FALSE)
if(!is.null(object$coefficients)) object$coefficients <- as.matrix(object$coefficients)
if(!is.null(object$stdev.unscaled)) object$stdev.unscaled <- as.matrix(object$stdev.unscaled)
if(!is.null(object$weights)) object$weights <- as.matrix(object$weights)
if(!is.null(object$p.value)) object$p.value <- as.matrix(object$p.value)
if(!is.null(object$lods)) object$lods <- as.matrix(object$lods)
if(!is.null(object$targets)) object$targets <- as.data.frame(object$targets)
if(!is.null(object$cov.coefficients)) object$cov.coefficients <- as.matrix(object$cov.coefficients)
if(!is.null(object$contrasts)) object$contrasts <- as.matrix(object$contrasts)
if(is.null(object$contrasts) && !is.null(object$coefficients)) {
object$contrasts <- diag(ncol(object$coefficients))
rownames(object$contrasts) <- colnames(object$contrasts) <- colnames(object$coefficients)
}
if(!is.null(object$genes)) object$genes <- as.data.frame(object$genes)
if(missing(i)) {
if(missing(j))
return(object)
else {
object$coefficients <- object$coefficients[,j,drop=FALSE]
object$stdev.unscaled <- object$stdev.unscaled[,j,drop=FALSE]
object$t <- object$t[,j,drop=FALSE]
object$weights <- object$weights[,j,drop=FALSE]
object$p.value <- object$p.value[,j,drop=FALSE]
object$lods <- object$lods[,j,drop=FALSE]
object$cov.coefficients <- object$cov.coefficients[j,j,drop=FALSE]
object$contrasts <- object$contrasts[,j,drop=FALSE]
object$var.prior <- object$var.prior[j]
}
} else {
if(is.character(i)) {
i <- match(i,rownames(object))
i <- i[!is.na(i)]
}
if(missing(j)) {
object$coefficients <- object$coefficients[i,,drop=FALSE]
object$stdev.unscaled <- object$stdev.unscaled[i,,drop=FALSE]
object$t <- object$t[i,,drop=FALSE]
object$weights <- object$weights[i,,drop=FALSE]
object$p.value <- object$p.value[i,,drop=FALSE]
object$lods <- object$lods[i,,drop=FALSE]
object$genes <- object$genes[i,,drop=FALSE]
} else {
object$coefficients <- object$coefficients[i,j,drop=FALSE]
object$stdev.unscaled <- object$stdev.unscaled[i,j,drop=FALSE]
object$t <- object$t[i,j,drop=FALSE]
object$weights <- object$weights[i,j,drop=FALSE]
object$p.value <- object$p.value[i,j,drop=FALSE]
object$lods <- object$lods[i,j,drop=FALSE]
object$genes <- object$genes[i,,drop=FALSE]
object$cov.coefficients <- object$cov.coefficients[j,j,drop=FALSE]
object$contrasts <- object$contrasts[,j,drop=FALSE]
object$var.prior <- object$var.prior[j]
}
object$df.residual <- object$df.residual[i]
if(length(object$df.prior)>1) object$df.prior <- object$df.prior[i]
object$df.total <- object$df.total[i]
object$sigma <- object$sigma[i]
object$s2.post <- object$s2.post[i]
object$Amean <- object$Amean[i]
}
if(!is.null(object$F))
if(missing(j)) {
object$F <- object$F[i]
object$F.p.value <- object$F.p.value[i]
} else {
F.stat <- classifyTestsF(object,fstat.only=TRUE)
object$F <- as.vector(F.stat)
df1 <- attr(F.stat,"df1")
df2 <- attr(F.stat,"df2")
if (df2[1] > 1e+06)
object$F.p.value <- pchisq(df1*object$F,df1,lower.tail=FALSE)
else
object$F.p.value <- pf(object$F,df1,df2,lower.tail=FALSE)
}
object
})
<file_sep>\title{Individual-channel Densities Plot}
\name{plotDensities}
\alias{plotDensities}
\description{
Plots the densities of individual-channel intensities for two-color microarray data.
}
\usage{
plotDensities(object, log=TRUE, arrays=NULL, singlechannels=NULL, groups=NULL, col=NULL)
}
\arguments{
\item{object}{an \code{RGList} or \code{MAList} object. \code{RGList} objects containing logged or unlogged intensities can be accommodated using the \code{log.transform} argument.}
\item{log}{logical, should densities be formed and plotted for the log-intensities (\code{TRUE}) or raw intensities (\code{FALSE})?}
\item{arrays}{vector of integers giving the arrays from which the
individual-channels will be selected to be plotted.
Corresponds to columns of \code{M}
and \code{A} (or \code{R} and \code{G}). Defaults to all arrays.}
\item{singlechannels}{vector of integers indicating which
individual-channels will be selected to be plotted. Values correspond
to the columns of the matrix of \code{cbind(R,G)} and range
between \code{1:ncol(R)} for red channels and
\code{( (ncol(R)+1):(ncol(R)+ncol(G)) )} for the green
channels in \code{object}.
Defaults to all channels.}
\item{groups}{vector of consecutive integers beginning at 1 indicating
the groups of arrays or individual-channels (depending on which of
\code{arrays} or \code{singlechannels} are non \code{NULL}). This is used
to color any groups of the individual-channel densities.
If \code{NULL} (default), \code{groups} correspond to the
red and green channels. If both \code{arrays} and
\code{singlechannels} are \code{NULL} all arrays are selected and
groups (if specified) must correspond to the arrays.}
\item{col}{vector of colors of the same length as the number of
different groups. If \code{NULL} (default) the \code{col} equals
\code{c("red","green")}. See details for more specifications.}
}
\details{
This function is used as a data display technique associated with between-array normalization, especially individual-channel normalization methods such as quantile-normalization.
See the section on between-array normalization in the LIMMA User's Guide.
If no \code{col} is specified, the default is to color individual channels
according to red and green. If both \code{arrays} and \code{groups} are
non-\code{NULL}, then the length of \code{groups} must equal the length
of \code{arrays} and the maximum of \code{groups} (i.e. the number of
groups) must equal the length of \code{col} otherwise the default color
of black will be used for all individual-channels.
If \code{arrays} is \code{NULL} and both \code{singlechannels} and
\code{groups} are non-\code{NULL}, then the length of \code{groups} must
equal the length of \code{singlechannels} and the maximum of \code{groups}
(i.e. the number of groups) must equal the length of \code{col}
otherwise the default color of black will be used for all individual-channels.
}
\value{A plot is created on the current graphics device.}
\author{<NAME>}
\seealso{
An overview of diagnostic plots in LIMMA is given in \link{09.Diagnostics}.
There is a section using \code{plotDensities} in conjunction with between-array normalization
in the \link[=limmaUsersGuide]{LIMMA User's Guide}.
}
\examples{
\dontrun{
# Default settings for plotDensities.
plotDensities(MA)
# One can reproduce the default settings.
plotDensities(MA,arrays=c(1:6),groups=c(rep(1,6),rep(2,6)),
col=c("red","green"))
# Color R and G individual-channels by blue and purple.
plotDensities(MA,arrays=NULL,groups=NULL,col=c("blue","purple"))
# Indexing individual-channels using singlechannels (arrays=NULL).
plotDensities(MA,singlechannels=c(1,2,7))
# Change the default colors from c("red","green") to c("pink","purple")
plotDensities(MA,singlechannels=c(1,2,7),col=c("pink","purple"))
# Specified too many colors since groups=NULL defaults to two groups.
plotDensities(MA,singlechannels=c(1,2,7),col=c("pink","purple","blue"))
# Three individual-channels, three groups, three colors.
plotDensities(MA,singlechannels=c(1,2,7),groups=c(1,2,3),
col=c("pink","purple","blue"))
# Three individual-channels, one group, one color.
plotDensities(MA,singlechannels=c(1,2,7),groups=c(1,1,1),
col=c("purple"))
# All individual-channels, three groups (ctl,tmt,reference), three colors.
plotDensities(MA,singlechannels=c(1:12),
groups=c(rep(1,3),rep(2,3),rep(3,6)),col=c("darkred","red","green"))
}
}
\keyword{hplot}
<file_sep>\name{subsetting}
\alias{subsetting}
\alias{[.RGList}
\alias{[.MAList}
\alias{[.EListRaw}
\alias{[.EList}
\alias{[.MArrayLM}
\title{Subset RGList, MAList, EList or MArrayLM Objects}
\description{
Extract a subset of an \code{RGList}, \code{MAList}, \code{EList} or \code{MArrayLM} object.
}
\usage{
\method{[}{RGList}(object, i, j, \ldots)
}
\arguments{
\item{object}{object of class \code{RGList}, \code{MAList}, \code{EList} or \code{MArrayLM}}
\item{i,j}{elements to extract. \code{i} subsets the probes or spots while \code{j} subsets the arrays}
\item{\ldots}{not used}
}
\details{
\code{i,j} may take any values acceptable for the matrix components of \code{object}.
See the \link[base]{Extract} help entry for more details on subsetting matrices.
}
\value{
An object of the same class as \code{object} holding data from the specified subset of genes and arrays.
}
\author{<NAME>}
\seealso{
\code{\link[base]{Extract}} in the base package.
\link{03.ReadingData} gives an overview of data input and manipulation functions in LIMMA.
}
\examples{
M <- A <- matrix(11:14,4,2)
rownames(M) <- rownames(A) <- c("a","b","c","d")
colnames(M) <- colnames(A) <- c("A","B")
MA <- new("MAList",list(M=M,A=A))
MA[1:2,]
MA[1:2,2]
MA[,2]
}
\keyword{manip}
<file_sep>### treat.R
treat <- function(fit, lfc=0, trend=FALSE)
# Moderated t-statistics with threshold
# <NAME>, <NAME>
# 25 July 2008. Last revised 7 April 2013.
{
# Check fit
if(!is(fit,"MArrayLM")) stop("fit must be an MArrayLM object")
if(is.null(fit$coefficients)) stop("coefficients not found in fit object")
if(is.null(fit$stdev.unscaled)) stop("stdev.unscaled not found in fit object")
coefficients <- as.matrix(fit$coefficients)
stdev.unscaled <- as.matrix(fit$stdev.unscaled)
sigma <- fit$sigma
df.residual <- fit$df.residual
if (is.null(coefficients) || is.null(stdev.unscaled) || is.null(sigma) ||
is.null(df.residual))
stop("No data, or argument is not a valid lmFit object")
if (all(df.residual == 0))
stop("No residual degrees of freedom in linear model fits")
if (all(!is.finite(sigma)))
stop("No finite residual standard deviations")
if(trend) {
covariate <- fit$Amean
if(is.null(covariate)) stop("Need Amean component in fit to estimate trend")
} else {
covariate <- NULL
}
sv <- squeezeVar(sigma^2, df.residual, covariate=covariate)
fit$df.prior <- sv$df.prior
fit$s2.prior <- sv$var.prior
fit$s2.post <- sv$var.post
df.total <- df.residual + sv$df.prior
df.pooled <- sum(df.residual,na.rm=TRUE)
df.total <- pmin(df.total,df.pooled)
fit$df.total <- df.total
lfc <- abs(lfc)
acoef <- abs(coefficients)
se <- stdev.unscaled*sqrt(fit$s2.post)
tstat.right <- (acoef-lfc)/se
tstat.left <- (acoef+lfc)/se
fit$t <- array(0,dim(coefficients),dimnames=dimnames(coefficients))
fit$p.value <- pt(tstat.right, df=df.total,lower.tail=FALSE) + pt(tstat.left,df=df.total,lower.tail=FALSE)
tstat.right <- pmax(tstat.right,0)
fc.up <- (coefficients > lfc)
fc.down <- (coefficients < -lfc)
fit$t[fc.up] <- tstat.right[fc.up]
fit$t[fc.down] <- -tstat.right[fc.down]
fit
}
topTreat <- function(fit,coef=1,number=10,genelist=fit$genes,adjust.method="BH",sort.by="p",resort.by=NULL,p.value=1)
# Summary table of top genes by treat
# <NAME>
# 15 June 2009. Last modified 20 April 2013.
{
# Check fit object
M <- as.matrix(fit$coefficients)
rn <- rownames(M)
A <- fit$Amean
if(is.null(A)) {
if(sort.by=="A") stop("Cannot sort by A-values as these have not been given")
} else {
if(NCOL(A)>1) A <- rowMeans(A,na.rm=TRUE)
}
# Check coef is length 1
if(length(coef)>1) {
coef <- coef[1]
warning("Treat is for single coefficients: only first value of coef being used")
}
# Ensure genelist is a data.frame
if(!is.null(genelist) && is.null(dim(genelist))) genelist <- data.frame(ID=genelist,stringsAsFactors=FALSE)
# Check rownames
if(is.null(rn))
rn <- 1:nrow(M)
else
if(anyDuplicated(rn)) {
if(is.null(genelist))
genelist <- data.frame(ID=rn,stringsAsFactors=FALSE)
else
if("ID" %in% names(genelist))
genelist$ID0 <- rn
else
genelist$ID <- rn
rn <- 1:nrow(M)
}
# Check sort.by
sort.by <- match.arg(sort.by,c("logFC","M","A","Amean","AveExpr","P","p","T","t","none"))
if(sort.by=="M") sort.by="logFC"
if(sort.by=="A" || sort.by=="Amean") sort.by <- "AveExpr"
if(sort.by=="T") sort.by <- "t"
if(sort.by=="p") sort.by <- "P"
# Check resort.by
if(!is.null(resort.by)) {
resort.by <- match.arg(resort.by,c("logFC","M","A","Amean","AveExpr","P","p","T","t"))
if(resort.by=="M") resort.by <- "logFC"
if(resort.by=="A" || resort.by=="Amean") resort.by <- "AveExpr"
if(resort.by=="p") resort.by <- "P"
if(resort.by=="T") resort.by <- "t"
}
# Extract columns from fit
M <- M[,coef]
tstat <- as.matrix(fit$t)[,coef]
P.Value <- as.matrix(fit$p.value)[,coef]
# Apply multiple testing adjustment
adj.P.Value <- p.adjust(P.Value,method=adjust.method)
# Apply p.value threshold
if(p.value < 1) {
sig <- (adj.P.Value < p.value)
if(any(is.na(sig))) sig[is.na(sig)] <- FALSE
if(all(!sig)) return(data.frame())
genelist <- genelist[sig,,drop=FALSE]
M <- M[sig]
A <- A[sig]
tstat <- tstat[sig]
P.Value <- P.Value[sig]
adj.P.Value <- adj.P.Value[sig]
}
ord <- switch(sort.by,
logFC=order(abs(M),decreasing=TRUE),
AveExpr=order(A,decreasing=TRUE),
P=order(P.Value,decreasing=FALSE),
t=order(abs(tstat),decreasing=TRUE),
none=1:length(M)
)
# Enough rows left?
if(length(M) < number) number <- length(M)
if(number < 1) return(data.frame())
# Assemble data.frame of top genes
top <- ord[1:number]
if(is.null(genelist))
tab <- data.frame(logFC=M[top])
else {
tab <- data.frame(genelist[top,,drop=FALSE],logFC=M[top],stringsAsFactors=FALSE)
}
if(!is.null(A)) tab <- data.frame(tab,AveExpr=A[top])
tab <- data.frame(tab,t=tstat[top],P.Value=P.Value[top],adj.P.Val=adj.P.Value[top])
rownames(tab) <- rn[top]
# Resort
if(!is.null(resort.by)) {
ord <- switch(resort.by,
logFC=order(tab$logFC,decreasing=TRUE),
AveExpr=order(tab$AveExpr,decreasing=TRUE),
P=order(tab$P.Value,decreasing=FALSE),
t=order(tab$t,decreasing=TRUE)
)
tab <- tab[ord,]
}
tab
}
<file_sep># SCORE.R
zscore <- function(q, distribution=NULL, ...)
# Z-score equivalents for deviates from specified distribution
# <NAME>
# 13 June 2012
{
z <- q
n <- length(q)
pdist <- get(paste("p",as.character(distribution),sep=""))
pupper <- pdist(q,...,lower.tail=FALSE,log.p=TRUE)
plower <- pdist(q,...,lower.tail=TRUE,log.p=TRUE)
up <- pupper<plower
if(any(up)) z[up] <- qnorm(pupper[up],lower.tail=FALSE,log.p=TRUE)
if(any(!up)) z[!up] <- qnorm(plower[!up],lower.tail=TRUE,log.p=TRUE)
z
}
zscoreGamma <- function(q, shape, rate = 1, scale = 1/rate)
# Z-score equivalents for gamma deviates
# <NAME>
# 1 October 2003
{
z <- q
n <- length(q)
shape <- rep(shape,length.out=n)
scale <- rep(scale,length.out=n)
up <- (q > shape*scale)
if(any(up)) z[up] <- qnorm(pgamma(q[up],shape=shape[up],scale=scale[up],lower.tail=FALSE,log.p=TRUE),lower.tail=FALSE,log.p=TRUE)
if(any(!up)) z[!up] <- qnorm(pgamma(q[!up],shape=shape[!up],scale=scale[!up],lower.tail=TRUE,log.p=TRUE),lower.tail=TRUE,log.p=TRUE)
z
}
zscoreT <- function(x, df)
# Z-score equivalents for t distribution deviates
# <NAME>
# 24 August 2003
{
z <- x
df <- rep(df,length.out=length(x))
pos <- x>0
if(any(pos)) z[pos] <- qnorm(pt(x[pos],df=df[pos],lower.tail=FALSE,log.p=TRUE),lower.tail=FALSE,log.p=TRUE)
if(any(!pos)) z[!pos] <- qnorm(pt(x[!pos],df=df[!pos],lower.tail=TRUE,log.p=TRUE),lower.tail=TRUE,log.p=TRUE)
z
}
tZscore <- function(x, df)
# t-statistics equivalents for z-scores deviates
# <NAME>
# 1 June 2004
{
z <- x
df <- rep(df,length.out=length(x))
pos <- x>0
if(any(pos)) z[pos] <- qt(pnorm(x[pos],lower.tail=FALSE,log.p=TRUE),df=df[pos],lower.tail=FALSE,log.p=TRUE)
if(any(!pos)) z[!pos] <- qt(pnorm(x[!pos],lower.tail=TRUE,log.p=TRUE),df=df[!pos],lower.tail=TRUE,log.p=TRUE)
z
}
| fd2386d72bedb2935376e184d1afbba422f862c9 | [
"R"
] | 8 | R | ugerlevik/r-bioc-limma | 69cddbfe62ddc134224beb4030d598aba4fcd688 | 80e4a208e622f846232c5b665d98d72ad60cb6cf |
refs/heads/master | <repo_name>foolem/lamind-package-manager<file_sep>/README.md
# lamind-package-manager<file_sep>/manager.rb
class Gerenciador
require "socket"
def initialize
@server = TCPServer.open(5151)
@clients = []
main
end
def main
loop do
Thread.fork(@server.accept) do |client|
@clients.push client
send_command
client.close
end
end
end
def send_command
loop do
command = gets.chomp
@clients.each { |client| client.puts command }
end
end
end
Gerenciador.new.main
| 385cbbf04af7ba4305cbc78e2d70d3969de6444a | [
"Markdown",
"Ruby"
] | 2 | Markdown | foolem/lamind-package-manager | 39238aed9524fe0c7bcbff578b9394ff80075d3b | 67c628c78ea1618f2476f93ae6802436c9d05f11 |
refs/heads/master | <repo_name>kanishka8276/sharenlearn<file_sep>/myapp/views.py
import re
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from .models import *
from django.contrib.auth import authenticate, login, logout
from datetime import date
from django.views.decorators.csrf import csrf_exempt
from django.contrib import messages
from django.contrib.auth.hashers import make_password, check_password
import requests
from django.core.mail import send_mail
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
# Create your views here.
def about(request):
return render(request,'about.html')
def index(request) :
return render(request, 'index.html')
def contact(request) :
try:
if 'msg' in request.POST:
nameee = request.POST['name']
emailee = request.POST['mess']
subjectee = request.POST['sub']
messageee = request.POST['msg']
fmessage = "Name : "+nameee+"\n"+"Email : "+emailee+"\n"+"Subject : "+subjectee+"\n"+"Message : "+messageee
print(messageee)
send_mail('Contact Form',fmessage, settings.EMAIL_HOST_USER,['<EMAIL>'], fail_silently=False)
return render(request, 'contact.html')
except Exception as e:
print('post exception ')
print(e)
return render(request, 'contact.html')
def Logout(request) :
logout(request)
return redirect('index')
def userlogin(request) :
error=""
if request.method == 'POST':
u = request.POST['emailid']
p = request.POST['pwd']
# Retrieves reCAPTCHA token and verifies with the API
captcha_token = request.POST['g-recaptcha-response']
cap_url = "https://www.google.com/recaptcha/api/siteverify"
cap_data = {"secret": settings.GOOGLE_RECAPTCHA_SECRET_KEY,
"response": captcha_token}
cap_server_response = requests.post(url=cap_url, data=cap_data)
cap_json = cap_server_response.json()
if cap_json['success'] == False:
messages.error(request, "Invalid reCAPTCHA. Please try again.")
return redirect('login')
user = authenticate(username=u, password=p)
try:
if user:
login(request, user)
error = "no"
else:
error = "yes"
except:
error = "yes"
d = {'error':error}
return render(request, 'login.html',d)
def login_admin(request) :
error=""
if request.method == 'POST':
u = request.POST['uname']
p = request.POST['pwd']
user = authenticate(username=u, password=p)
try:
if user.is_staff:
login(request, user)
error = "no"
else:
error = "yes"
except:
error = "yes"
d = {'error':error}
return render(request, 'login_admin.html',d)
def signup1(request) :
error=""
if request.method=='POST':
f = request.POST['firstname']
l = request.POST['lastname']
c = request.POST['contact']
e = request.POST['emailid']
p = request.POST['password']
b = request.POST['branch']
r = request.POST['role']
try:
if not re.fullmatch(r'[A-Za-z0-9@#$%^&+=]{8,}', p):
raise Exception("Password not vaild add number, symbol, lowercase and uppercase letter")
user = User.objects.create_user(username=e,password=p,first_name=f,last_name=l)
Signup.objects.create(user=user,contact=c,branch=b,role=r)
error="no"
except:
error="yes"
d = {'error':error}
return render(request, 'signup.html',d)
@csrf_exempt
def Forgot_Password(request):
if(request.method=="POST"):
if User.objects.filter(username=request.POST["username"]).exists():
user= User.objects.filter(username=request.POST["username"])
for object in user:
if object.first_name==request.POST["first_name"]:
if object.last_name==request.POST["last_name"]:
if request.POST["password"]==request.POST["rpassword"]:
object.password=make_password(request.POST["password"])
object.save()
print('done')
messages.success(request,"Password Changed")
return redirect('login')
else:
context="Password confirmation doesn't match"
return render(request,'forgotpassword.html',{'ErrorFP':context})
else:
context="Wrong First Name"
return render(request,'forgotpassword.html',{'ErrorFN':context})
else:
context="Wrong Last Name"
return render(request,'forgotpassword.html',{'ErrorLN':context})
else:
context="Email not found"
return render(request,'forgotpassword.html',{'ErrorEmail':context})
else:
return render(request,'forgotpassword.html')
def admin_home(request) :
if not request.user.is_staff:
return redirect('login_admin')
pn = Notes.objects.filter(status="pending").count()
an = Notes.objects.filter(status="Accepted").count()
rn = Notes.objects.filter(status="Rejected").count()
aln = Notes.objects.all().count()
d={'pn':pn,'an':an,'rn':rn,'aln':aln}
return render(request, 'admin_home.html',d)
def profile(request):
if not request.user:
return redirect('login')
user = User.objects.get(id=request.user.id)
data = Signup.objects.get(user = user)
d = {'data':data,'user':user}
return render(request, 'profile.html',d)
def edit_profile(request) :
if not request.user:
return redirect('login')
user = User.objects.get(id=request.user.id)
data = Signup.objects.get(user = user)
error=False
if request.method=='POST':
f=request.POST['firstname']
l=request.POST['lastname']
c=request.POST['contact']
b=request.POST['branch']
user.first_name=f
user.last_name=l
datacontact=c
data.branch=b
user.save()
data.save()
error=True
d = {'data':data,'user':user,'error':error}
return render(request, 'edit_profile.html',d)
def changepassword(request):
if not request.user:
return redirect('login')
error=""
if request.method=="POST":
o=request.POST['old']
n=request.POST['new']
c=request.POST['confirm']
if c==n:
u=User.objects.get(username__exact=request.user.username)
u.set_password(n)
u.save()
error="no"
else:
error="yes"
d={'error':error}
return render(request, 'changepassword.html',d)
def upload_notes(request) :
if not request.user.is_authenticated:
return redirect('login')
error=""
if request.method == 'POST':
b = request.POST['branch']
s = request.POST['subject']
n = request.FILES['notesfile']
f = request.POST['filetype']
d = request.POST['description']
u = User.objects.filter(username=request.user.username).first()
try:
Notes.objects.create(user=u,uploadingdate=date.today(), branch=b, subject=s,
notesfile=n,filetype=f,description=d,status='pending')
error="no"
except:
error="yes"
d = {'error':error}
return render(request, 'upload_notes.html', d)
def view_usernotes(request) :
if not request.user:
return redirect('login')
user = User.objects.get(id=request.user.id)
notes = Notes.objects.filter(user = user)
d = {'notes':notes,}
return render(request, 'view_usernotes.html',d)
def delete_usernotes(request,pid) :
if not request.user:
return redirect('login')
notes = Notes.objects.get(id = pid)
notes.delete()
return redirect('view_usernotes')
def view_users(request) :
if not request.user.is_staff:
return redirect('login')
users = Signup.objects.all()
d = {'users':users}
return render(request, 'view_users.html', d)
def delete_users(request,pid) :
if not request.user:
return redirect('login')
users = User.objects.get(id = pid)
users.delete()
return redirect('view_users')
def pending_notes(request) :
if not request.user.is_authenticated:
return redirect('login_admin')
notes = Notes.objects.filter(status = "pending")
d = {'notes':notes,}
return render(request, 'pending_notes.html',d)
def assign_status(request,pid) :
if not request.user.is_authenticated:
return redirect('login')
notes = Notes.objects.get(id = pid)
error=""
if request.method=='POST':
s = request.POST['status']
try:
notes.status=s
notes.save()
error="no"
except:
error="yes"
d={'notes':notes,'error':error}
return render(request, 'assign_status.html',d)
def accepted_notes(request):
if not request.user.is_authenticated:
return redirect('login_admin')
notes = Notes.objects.filter(status="Accepted")
d = {'notes':notes}
return render(request, 'accepted_notes.html', d)
def rejected_notes(request):
if not request.user.is_authenticated:
return redirect('login_admin')
notes = Notes.objects.filter(status="Rejected")
d = {'notes':notes}
return render(request, 'rejected_notes.html', d)
def all_notes(request):
if not request.user.is_authenticated:
return redirect('login_admin')
notes = Notes.objects.all()
d = {'notes':notes}
return render(request, 'all_notes.html', d)
def delete_notes(request,pid) :
if not request.user:
return redirect('login')
notes = Notes.objects.get(id = pid)
notes.delete()
return redirect('all_notes')
def viewall_usernotes(request):
if not request.user.is_authenticated:
return redirect('login')
notes = Notes.objects.filter(status="Accepted")
d = {'notes':notes}
return render(request, 'viewall_usernotes.html', d)
#SMTP Backend in views.py
| 197790effe47ac0194767f15b2f82d2e71820a22 | [
"Python"
] | 1 | Python | kanishka8276/sharenlearn | 2625689cb19796d6add0b4aeb3b210b3def303e9 | f1b67237cbc49ee521412712eea20b2d6a3c4237 |
refs/heads/master | <repo_name>faleinshah/Guess<file_sep>/guess_number.rb
puts "What is your name?"
player = gets.chomp
puts "Hello " + player + ". Let's play Guess the Number Game."
def guess_number( player, random_number)
if player > random_number
puts "Too high! try again!"
elsif player < random_number
puts "Too low! try again!"
end
end
guesses = []
attempts = 6
random_number = rand(100) + 1
puts "Guess a number between 1 - 100. You only have 6 attempts!"
while attempts
player = gets.to_i
guesses.push( player )
if player == random_number
puts "Congratulations, you guessed the number! [#{random_number}]"
break;
end
puts "You've guessed #{guesses}"
guess_number(player, random_number)
attempts = attempts - 1
if attempts == 0
puts "Sorry, you're out of guesses, the number is [#{random_number}]"
break;
else
puts "Guess the number, you have #{attempts} tries left"
end
end
<file_sep>/README.md
# Guess the Number Game
Create a game as an exercise to gain experience with Ruby.
## Rules
Guess a random number between 1 to 100 within 6 tries.
## Game Instructions:
1. Key in player's name to start the game.
2. If you guess a number higher than the random number, the output will be displayed:
```
Too high! Try again!
```
3. If you guess a number lower than the random number, the output will be displayed:
```
"Too low! Try again!
```
4. If you guess correctly, the output will be displayed:
```
Congratulations, you guessed the number! (random number choosen).
```
5. If you guess the wrong answer within 6 tries, the output will be displayed:
```
Guess the number, you have (attempts) tries left.
```
6. If you run out of guesses, you lose the round and the output will be displayed:
```
Sorry, you're out of guesses, the number is (random_number).
```
## Ruby Version
2.3.7
## References
* Introduction to Programming with Ruby by Launch School
* Object Oriented Programming with Ruby by Launch School
* Google
| 771028ff4205e136ff18424d3b7bc493405b1d62 | [
"Markdown",
"Ruby"
] | 2 | Ruby | faleinshah/Guess | 63a528b7c0093e4d6537f2b6546004953ff027b9 | 33aa462e64ee276a5606ca7da5f3ddc8e8f0bb4e |
refs/heads/master | <file_sep>options(java.parameters = "-Xmx8000m")
library(openxlsx)
library(RecordLinkage)
curation <- read.csv("drugs_with_ids_new_new.csv")
curation <- curation[, -1]
drugs <- read.xlsx("nm.3954-S2.xlsx", sheet = 4)
curated_drugs <- data.frame(pdx.drugid=NA, unique.drugid=NA)[numeric(0), ]
drugs$Tumor.Type <- gsub("GC", "stomach", drugs$Tumor.Type)
drugs$Tumor.Type <- gsub("BRCA", "breast", drugs$Tumor.Type)
drugs$Tumor.Type <- gsub("CM", "skin", drugs$Tumor.Type)
drugs$Tumor.Type <- gsub("CRC", "large_intestine", drugs$Tumor.Type)
drugs$Tumor.Type <- gsub("NSCLC", "lung", drugs$Tumor.Type)
drugs$Tumor.Type <- gsub("PDAC", "pancreas", drugs$Tumor.Type)
for(d in unique(drugs$Treatment))
{
d2 <- data.frame(strsplit(d, " + ", fixed = TRUE))[,1]
for(ds in 1:length(d2))
{
unique_drug <- NA
found <- FALSE
if(d2[ds][[1]] %in% curated_drugs$pdx.drugid)
{
message("found previous entry")
d2[ds][[1]] <- curated_drugs[grep(ds, curated_drugs$pdx.drugid), "unique.drugid"]
found <- TRUE
}
}
if(!found)
{
message("not found")
seen <- c()
for(x in 1:nrow(curation))
{
for(y in 1:ncol(curation))
{
#message(paste(x,y, sep = " "))
if(!is.na(curation[x,y]) && !(curation[x,y] %in% seen))
{
for(ds in 1:length(d2))
{
if(levenshteinSim(d2[ds][[1]], curation[x,y]) == 1)
{
messge("found exact match")
d2[ds][[1]] <- curation[x,"unique.drugid"]
curated_drugs <- rbind(curated_drugs, data.frame(pdx.drugid=d2[ds][[1]], unique.drugid=curation[x,"unique.drugid"])[1, ])
found <- TRUE
}
else if(levenshteinSim(d2[ds][[1]], curation[x,y]) >= 0.4)
{
message(paste(d2[ds][[1]], curation[x,y], sep = " "))
z <- readline(prompt = "?????: ")
if(z == "y")
{
d2[ds][[1]] <- curation[x,"unique.drugid"]
curated_drugs <- rbind(curated_drugs, data.frame(pdx.drugid=d2[ds][[1]], unique.drugid=curation[x,"unique.drugid"])[1, ])
found <- TRUE
}
}
}
}
seen <- c(seen, curation[x,y])
}
}
if(!found)
{
curated_drugs <- rbind(curated_drugs, data.frame(pdx.drugid=d2[ds][[1]], unique.drugid=d2[ds][[1]]))
}
}
drugs$Treatment <- gsub(d, paste(d2, collapse = " + "), drugs$Treatment)
message("next drug")
}
| 4c9c4bf1dba73c450f5d70b7ffc119e7381695c5 | [
"R"
] | 1 | R | gosuzombie/PDX-analysis | 773a66f16d2233cad3223d3ae48fd4c22413ad3b | 72cce9265bebe3b16d30250eee1d11a0a0d50b80 |
refs/heads/main | <file_sep>'use strict';
// import mongoose
const mongoose = require("mongoose");
// declare schema and assign Schema class
const Schema = mongoose.Schema;
// create Schema instance and add schema properties
const smsSchema = new Schema({
from: {
type: Number,
required: true,
},
to: {
type: Number,
required: true,
},
text: {
type: String,
required: true,
},
});
// create and export model
module.exports = mongoose.model("model", smsSchema);<file_sep># ESA-Assignement4
## Microservice SMS API
Download the code into a zip file and then follow the following commands to run the code
## To Run the code
1. Change the MongoDb URL in the```config/db.js``` file
2. Initialize ```package.json``` file and install dependencies
## Run the following commands
- ``` npm init```
- ``` npm install mongoose express body-parser```
- ```npm install dotenv```
- ```npm install --save express-rate-limit```
- ```npm install memory-cache --save```
3. Running the server
Run the server by going to the folder where the file is saved and using node ```node server.js```
Output when code runs successfully
```
Server running at http://localhost:3000
Database connection established!
```
## Example test case
```
from : "1234567890"
to : "123456"
text : "hello"
output : "message": "Forbidden.... Authorization failed."
```
| f7f4fafd525874b0db71558943629a69d23e5fcd | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Aaliya201/ESA-Assignment4 | c12861d14176bbbb954b3394fc61d7c2c570a732 | 953cebffc938e06ce231b684eb1b9f31f199bec4 |
refs/heads/master | <file_sep>package com.bylaew.exytepokeapi.ui.info
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import com.bylaew.exytepokeapi.R
import com.bylaew.exytepokeapi.model.PokemonInfo.PokemonInfo
import com.bylaew.exytepokeapi.utils.Resource
import kotlinx.android.synthetic.main.fragment_about.*
class AboutFragment : Fragment() {
val viewModel: InfoViewModel by viewModels()
private var aboutPokemon: PokemonInfo? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_about, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initObservables()
}
private fun initObservables () {
viewModel.pokemonAbout.observe(viewLifecycleOwner, Observer { response ->
when (response) {
is Resource.Success -> {
response.data?.let { pokemonResponse ->
aboutPokemon = pokemonResponse
renderAbout()
}
}
is Resource.Error -> {
}
is Resource.Loading -> {
}
}
})
}
private fun renderAbout() {
if(aboutPokemon !== null) {
val descriptionText = aboutPokemon!!.flavor_text_entries[0].flavor_text.replace("\\s+".toRegex()," ")
tvDescription.text = descriptionText;
}
}
}<file_sep>package com.bylaew.exytepokeapi.model.Pokemon
import java.io.Serializable
data class PokemonResult (
val name: String,
val url: String
) : Serializable<file_sep>package com.bylaew.exytepokeapi.utils
import androidx.room.TypeConverter
import com.bylaew.exytepokeapi.model.PokemonById.*
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.lang.reflect.Type
class Converter {
private val gson = Gson()
private val type: Type = object : TypeToken<List<String>>() {}.type
@TypeConverter
fun storedStringToMyObjects(data: String?): List<Ability?>? {
val gson = Gson()
if (data == null) {
return emptyList<Ability>()
}
val listType = object : TypeToken<List<Ability?>?>() {}.type
return gson.fromJson<List<Ability?>>(data, listType)
}
@TypeConverter
fun storedStringToMyAny(data: String?): List<Any?>? {
val gson = Gson()
if (data == null) {
return emptyList<Any>()
}
val listType = object : TypeToken<List<Any?>?>() {}.type
return gson.fromJson<List<Any?>>(data, listType)
}
@TypeConverter
fun storedStringToMyForms(data: String?): List<Form?>? {
val gson = Gson()
if (data == null) {
return emptyList<Form>()
}
val listType = object : TypeToken<List<Form?>?>() {}.type
return gson.fromJson<List<Form?>>(data, listType)
}
@TypeConverter
fun storedStringToMyGameIndice(data: String?): List<GameIndice?>? {
val gson = Gson()
return gson.fromJson<List<GameIndice?>>(data, GameIndice::class.java.genericSuperclass)
}
@TypeConverter
fun storedStringToMyMove(data: String?): List<Move?>? {
val gson = Gson()
if (data == null) {
return emptyList<Move>()
}
val listType = object : TypeToken<List<Move?>?>() {}.type
return gson.fromJson<List<Move?>>(data, listType)
}
@TypeConverter
fun storedStringToMySpecies(data: String?): Species? {
val gson = Gson()
if (data == null) {
return Species("","")
}
val listType = object : TypeToken<Species?>() {}.type
return gson.fromJson<Species?>(data, listType)
}
@TypeConverter
fun storedStringToMySprites(data: String?): Sprites? {
val gson = Gson()
if (data == null) {
return null
}
val listType = object : TypeToken<Sprites?>() {}.type
return gson.fromJson<Sprites?>(data, listType)
}
@TypeConverter
fun storedStringToMyStats(data: String?): List<Stat?>? {
val gson = Gson()
if (data == null) {
return emptyList<Stat>()
}
return gson.fromJson<List<Stat?>>(data, Stat::class.java.genericSuperclass)
}
@TypeConverter
fun storedStringToMycomType(data: String?): List<com.bylaew.exytepokeapi.model.PokemonById.Type?>? {
val gson = Gson()
return gson.fromJson<List<com.bylaew.exytepokeapi.model.PokemonById.Type?>>(data, com.bylaew.exytepokeapi.model.PokemonById.Type::class.java.genericSuperclass)
}
@TypeConverter
fun fromString(json: String?): List<String> {
return gson.fromJson(json, type)
}
@TypeConverter
fun fromList(list: List<String?>?): String {
return gson.toJson(list, type)
}
@TypeConverter
fun fromAbilities(value: List<Ability>): String {
val gson = Gson()
val type = object : TypeToken<List<Ability>>() {}.type
return gson.toJson(value, type)
}
@TypeConverter
fun fromGameIndice(value: List<GameIndice>): List<String> {
val gson = Gson()
val type = object : TypeToken<List<GameIndice>>() {}.type
return listOf(gson.toJson(value, type))
}
@TypeConverter
fun fromForm(value: List<Form>): String {
val gson = Gson()
val type = object : TypeToken<List<Form>>() {}.type
return gson.toJson(value, type)
}
@TypeConverter
fun fromMove(value: List<Move>): String {
val gson = Gson()
val type = object : TypeToken<List<Move>>() {}.type
return gson.toJson(value, type)
}
@TypeConverter
fun fromAny(obj: List<Any>?): List<String> {
val type = object : TypeToken<List<Any>>() {}.type
return listOf(gson.toJson(obj, type))
}
@TypeConverter
fun fromSpecies(obj: Species?): String {
val type = object : TypeToken<Species>() {}.type
return gson.toJson(obj, type)
}
@TypeConverter
fun fromSprites(obj: Sprites?): String {
val type = object : TypeToken<Sprites>() {}.type
return gson.toJson(obj, type)
}
@TypeConverter
fun fromStat(obj: List<Stat>?): List<String> {
val type = object : TypeToken<List<Stat>>() {}.type
return listOf(gson.toJson(obj, type))
}
@TypeConverter
fun fromType(obj: List<com.bylaew.exytepokeapi.model.PokemonById.Type>?): List<String> {
val type = object : TypeToken<List<com.bylaew.exytepokeapi.model.PokemonById.Type>>() {}.type
return listOf(gson.toJson(obj, type))
}
}<file_sep>package com.bylaew.exytepokeapi.ui.info
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import com.bylaew.exytepokeapi.MainActivity
import com.bylaew.exytepokeapi.R
import com.bylaew.exytepokeapi.adapter.ViewPageAdapter
import com.bylaew.exytepokeapi.model.PokemonById.PokemonById
import com.bylaew.exytepokeapi.utils.Resource
import kotlinx.android.synthetic.main.fragment_stats.*
class StatsFragment : Fragment() {
val viewModel: InfoViewModel by viewModels()
private var pokemonDetails: Resource<PokemonById>? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_stats, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
pokemonDetails = viewModel.pokemonDetails.value
renderStats()
}
private fun renderStats () {
val pokeStats = pokemonDetails?.data?.stats;
if (pokeStats != null) {
for (stat in pokeStats){
val typeStat = stat.stat.name
val valueStat = stat.base_stat;
when(typeStat){
"hp" -> progressBarHP.progress = valueStat
"attack" -> progressBarAttack.progress = valueStat
"defense" -> progressBarDefense.progress = valueStat
"special-attack" -> progressBarSpAtk.progress = valueStat
"special-defense" -> progressBarSpDef.progress = valueStat
"speed" -> progressBarSpeed.progress = valueStat
}
}
}
}
}<file_sep>package com.bylaew.exytepokeapi.ui.favorite
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import com.bylaew.exytepokeapi.MainActivity
import com.bylaew.exytepokeapi.R
import com.bylaew.exytepokeapi.adapter.FavouritePokemonAdapter
import kotlinx.android.synthetic.main.favorite_fragment.favourPokemonItems
import kotlinx.android.synthetic.main.favorite_fragment.no_fav_view
class FavoriteFragment : Fragment() {
private lateinit var pokAdapter: FavouritePokemonAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.favorite_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val viewModel: FavoriteViewModel by viewModels { FavouriteViewModelFactory(context!!) }
initAdapter()
(activity as MainActivity).supportActionBar?.setDisplayHomeAsUpEnabled(false)
viewModel.pokAll.observe(viewLifecycleOwner, {
pokAdapter.differ.submitList(it.toList())
if (it.isEmpty()) {
favourPokemonItems.visibility = View.INVISIBLE
no_fav_view.visibility = View.VISIBLE
} else {
favourPokemonItems.visibility = View.VISIBLE
no_fav_view.visibility = View.INVISIBLE
}
})
pokAdapter.setOnItemClickListener {currentPokemon ->
val bundle = Bundle().apply {
putInt("id",currentPokemon)
}
findNavController().navigate(
R.id.action_favoriteFragment_to_infoFragment,
bundle
)
}
}
private fun initAdapter() {
pokAdapter = FavouritePokemonAdapter(requireContext())
favourPokemonItems.apply {
adapter = pokAdapter
layoutManager = GridLayoutManager(context,2)
}
}
}<file_sep>package com.bylaew.exytepokeapi.model.PokemonById
data class GenerationV(
val black_white: BlackWhite
)<file_sep>package com.bylaew.exytepokeapi.model.PokemonInfo
data class EvolutionChain(
val url: String
)<file_sep>package com.bylaew.exytepokeapi.model.PokemonById
import androidx.annotation.NonNull
import androidx.room.*
import com.bylaew.exytepokeapi.utils.Converter
@Entity
data class PokemonById(
val abilities: List<Ability>,
val base_experience: Int,
val forms: List<Form>,
val game_indices: List<GameIndice>,
val height: Int,
val held_items: List<Any>,
@PrimaryKey
@ColumnInfo(name = "id")
@NonNull
val id: Int = 0,
val is_default: Boolean,
val location_area_encounters: String,
val moves: List<Move>,
val name: String,
val order: Int,
val past_types: List<Any>,
val species: Species,
val sprites: Sprites,
val stats: List<Stat>,
val types: List<Type>,
val weight: Int
)<file_sep>package com.bylaew.exytepokeapi.service
import com.bylaew.exytepokeapi.model.Pokemon.PokemonResponse
import com.bylaew.exytepokeapi.model.PokemonById.PokemonById
import com.bylaew.exytepokeapi.model.PokemonInfo.PokemonInfo
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface PokemonAPi {
@GET("pokemon")
suspend fun getAllPokemons(
@Query("limit")
limit: Int = 10,
@Query("offset")
offset: Int = 0
): Response<PokemonResponse>
@GET("https://pokeapi.co/api/v2/pokemon/{id}")
suspend fun getPokemonById(
@Path("id") id: Int
): Response<PokemonById>
@GET("https://pokeapi.co/api/v2/pokemon-species/{id}")
suspend fun getInfoPokemon(
@Path("id") id: Int
) : Response<PokemonInfo>
}<file_sep>package com.bylaew.exytepokeapi.model.PokemonInfo
data class Variety(
val is_default: Boolean,
val pokemon: Pokemon
)<file_sep>package com.bylaew.exytepokeapi.ui.favorite
import android.app.Application
import android.content.Context
import androidx.lifecycle.*
import com.bylaew.exytepokeapi.database.PokemonDB
import com.bylaew.exytepokeapi.model.PokemonById.PokemonById
import com.bylaew.exytepokeapi.repository.PokemonRepository
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
class FavoriteViewModel(contexto: Context): ViewModel() {
private val repository: PokemonRepository
var pokAll: LiveData<List<PokemonById>>
init {
val pokDB = PokemonDB.getDatabase(contexto)!!.pokemonDAO()
repository = PokemonRepository(pokDB)
pokAll = repository.getAllLocPoks()!!
}
fun insert(word: PokemonById) = viewModelScope.launch {
repository.insert(word)
}
}
class FavouriteViewModelFactory(private val contexto: Context) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(FavoriteViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return FavoriteViewModel(contexto) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}<file_sep>package com.bylaew.exytepokeapi.adapter
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bylaew.exytepokeapi.R
import com.bylaew.exytepokeapi.model.PokemonById.PokemonById
import com.bylaew.exytepokeapi.utils.Constants
import kotlinx.android.synthetic.main.pokemon_item.view.*
class FavouritePokemonAdapter(
private val context: Context
) :
RecyclerView.Adapter<FavouritePokemonAdapter.FavouriteViewHolder>() {
private lateinit var favoriteList: List<PokemonById>
inner class FavouriteViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
private val differCallback = object : DiffUtil.ItemCallback<PokemonById>(){
override fun areItemsTheSame(oldItem: PokemonById, newItem: PokemonById): Boolean {
return oldItem.name == newItem.name
}
override fun areContentsTheSame(oldItem: PokemonById, newItem: PokemonById): Boolean {
return oldItem == newItem
}
}
val differ = AsyncListDiffer(this,differCallback)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FavouriteViewHolder {
val view =
LayoutInflater.from(context).inflate(R.layout.pokemon_item, parent, false)
return FavouriteViewHolder(view)
}
override fun onBindViewHolder(holder: FavouriteViewHolder, position: Int) {
favoriteList = differ.currentList
val favouritePokemon = differ.currentList[position]
holder.itemView.apply {
Glide.with(this)
.load(Constants.BASE_IMG_URL + "${favouritePokemon.id}.png")
.thumbnail(0.25f)
.into(holder.itemView.imageView)
tvName.text = favouritePokemon.name
}
//TODO unlike -> remove from database!!
}
override fun getItemCount(): Int {
return differ.currentList.size
}
private var onItemClickListener: ((Int) -> Unit)? = null
fun setOnItemClickListener(listener: (Int) -> Unit) {
onItemClickListener = listener
}
}<file_sep>package com.bylaew.exytepokeapi.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bylaew.exytepokeapi.R
import com.bylaew.exytepokeapi.model.Pokemon.PokemonResult
import com.bylaew.exytepokeapi.utils.Constants.Companion.BASE_IMG_URL
import kotlinx.android.synthetic.main.pokemon_item.view.*
import java.util.*
class PokemonAdapter(val context: Context) : RecyclerView.Adapter<PokemonAdapter.PokemonViewHolder>() {
inner class PokemonViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
private val differCallback = object : DiffUtil.ItemCallback<PokemonResult>(){
override fun areItemsTheSame(oldItem: PokemonResult, newItem: PokemonResult): Boolean {
return oldItem.url == newItem.url
}
override fun areContentsTheSame(oldItem: PokemonResult, newItem: PokemonResult): Boolean {
return oldItem == newItem
}
}
val differ = AsyncListDiffer(this,differCallback)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PokemonViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.pokemon_item,parent,false)
return PokemonViewHolder(view)
}
override fun getItemCount(): Int {
return differ.currentList.size
}
override fun onBindViewHolder(holder: PokemonViewHolder, position: Int) {
val currentPokemonItem = differ.currentList[position]
holder.itemView.apply {
tvName.text = currentPokemonItem.name.replaceFirstChar {
if (it.isLowerCase()) it.titlecase(
Locale.getDefault()
) else it.toString()
}
Glide.with(this)
.load(BASE_IMG_URL+"${position+1}.png")
.thumbnail(0.25f)
.into(imageView)
setOnClickListener {
onItemClickListener?.let { it(position) }
}
holder.itemView.saveButton.setOnClickListener {
it.saveButton.setImageResource(R.drawable.ic_baseline)
}
}
}
private var onItemClickListener: ((Int) -> Unit)? = null
fun setOnItemClickListener(listener: (Int) -> Unit) {
onItemClickListener = listener
}
}<file_sep>package com.bylaew.exytepokeapi.model.PokemonById
data class GenerationViii(
val icons: IconsX
)<file_sep>package com.bylaew.exytepokeapi.ui.main
import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bylaew.exytepokeapi.database.PokemonDB
import com.bylaew.exytepokeapi.model.Pokemon.PokemonResponse
import com.bylaew.exytepokeapi.model.PokemonById.PokemonById
import com.bylaew.exytepokeapi.repository.PokemonRepository
import com.bylaew.exytepokeapi.utils.Resource
import kotlinx.coroutines.launch
import retrofit2.Response
class MainViewModel : ViewModel(){
var pokemonRepository: PokemonRepository = PokemonRepository()
val pokemonList : MutableLiveData<Resource<PokemonResponse>> = MutableLiveData()
var pokemonResponse : PokemonResponse? = null
val pokemonDetails : MutableLiveData<Resource<PokemonById>> = MutableLiveData()
var pokemonByIdResult : PokemonById? = null
var pokemonPages = 0
private var offset = 0
private var limit = 10
init {
getAllPokemons()
}
suspend fun putLike(context: Context, pok: PokemonById) {
pokemonRepository = PokemonRepository(PokemonDB.getDatabase(context)!!.pokemonDAO())
pokemonRepository.insert(pok)
}
fun getPokemonById(id: Int ) = viewModelScope.launch{
pokemonDetails.postValue(Resource.Loading())
val response = pokemonRepository.getPokemonById(id)
pokemonDetails.postValue(handlePokemonByIdResponse(response))
}
fun getAllPokemons() = viewModelScope.launch{
pokemonList.postValue(Resource.Loading())
val response = pokemonRepository.getAllPokemons(limit,offset)
pokemonList.postValue(handlegetAllPokemonsResponse(response))
}
private fun handlePokemonByIdResponse(response: Response<PokemonById>): Resource<PokemonById>? {
if(response.isSuccessful){
response.body()?.let {resultResponse->
return Resource.Success(pokemonByIdResult ?: resultResponse)
}
}
return Resource.Error(response.message())
}
private fun handlegetAllPokemonsResponse(response: Response<PokemonResponse>) : Resource<PokemonResponse> {
if(response.isSuccessful){
response.body()?.let {resultResponse ->
pokemonPages++
offset = pokemonPages * 10
limit = 10
if(pokemonResponse == null){
pokemonResponse = resultResponse
}else{
val oldPokemons = pokemonResponse?.results
val newPokemons = resultResponse.results
oldPokemons?.addAll(newPokemons)
}
return Resource.Success(pokemonResponse ?: resultResponse)
}
}
return Resource.Error(response.message())
}
}<file_sep>package com.bylaew.exytepokeapi.database
import androidx.lifecycle.LiveData
import androidx.room.*
import com.bylaew.exytepokeapi.model.*
import com.bylaew.exytepokeapi.model.PokemonById.PokemonById
import com.bylaew.exytepokeapi.model.PokemonInfo.Pokemon
import com.bylaew.exytepokeapi.utils.Converter
@Dao
interface PokemonDAO {
@Query("SELECT * FROM pokemonbyid WHERE id = :id")
fun getById(id: String?): LiveData<PokemonById>
@Query("SELECT * FROM pokemonbyid WHERE id IN(:evolutionIds)")
fun getEvolutionsByIds(evolutionIds: List<String>): LiveData<List<PokemonById>>
@Query("SELECT * FROM pokemonbyid")
fun all(): LiveData<List<PokemonById>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun add(pokemon: List<PokemonById>)
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun addOne(pokemon: PokemonById)
@Query("DELETE FROM pokemonbyid")
fun deleteAll()
@Delete
fun delete(model: PokemonById)
}<file_sep>package com.bylaew.exytepokeapi.ui.info
import android.annotation.SuppressLint
import android.icu.text.IDNA
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import com.bumptech.glide.Glide
import com.bylaew.exytepokeapi.MainActivity
import com.bylaew.exytepokeapi.R
import com.bylaew.exytepokeapi.adapter.ViewPageAdapter
import com.bylaew.exytepokeapi.model.PokemonById.PokemonById
import com.bylaew.exytepokeapi.utils.Constants
import com.bylaew.exytepokeapi.utils.Resource
import com.google.android.material.tabs.TabLayoutMediator
import kotlinx.android.synthetic.main.fragment_info.*
import java.util.*
class InfoFragment : Fragment() {
lateinit var pokemonDetails : PokemonById
val viewModel: InfoViewModel by viewModels()
var pokemonId : Int = 0
private val adapter by lazy { activity?.let { ViewPageAdapter(it) } }
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_info, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(activity as MainActivity).supportActionBar?.setDisplayHomeAsUpEnabled(true)
pokemonId = requireArguments().getInt("id")
viewModel.getPokemonById(pokemonId+1)
viewModel.getDescriptionPokemon(pokemonId+1)
viewModel.pokemonDetails.observe(viewLifecycleOwner, Observer { response ->
when(response){
is Resource.Success -> {
hideProgressBar()
response.data?.let { pokemonResponse ->
pokemonDetails = pokemonResponse
initUI()
}
}
is Resource.Error -> {
hideProgressBar()
}
is Resource.Loading -> {
showProgressBar()
}
}
})
initViewPagerAdapter()
}
private fun hideProgressBar () {
progressBar.visibility = View.INVISIBLE
layout.visibility = View.VISIBLE
}
private fun showProgressBar() {
progressBar.visibility = View.VISIBLE
layout.visibility = View.INVISIBLE
}
private fun initViewPagerAdapter(){
pager.adapter = adapter
val tabLayoutMediator = TabLayoutMediator(tabLayout, pager) { tab, position ->
when(position){
0 -> {
tab.text ="About"
}
1 -> {
tab.text ="Stats"
}
}
}
tabLayoutMediator.attach()
}
@SuppressLint("SetTextI18n")
private fun initUI() {
tvName.text = pokemonDetails.name?.replaceFirstChar {
if (it.isLowerCase()) it.titlecase(
Locale.getDefault()
) else it.toString()
}
tvNumberPokedex.text = "#${pokemonDetails.id}"
tvWeight.text = "Weight: ${pokemonDetails.weight}"
Glide.with(this)
.load(Constants.BASE_IMG_URL +"${pokemonDetails.id}.png")
.thumbnail(0.25f)
.into(ivPokemon)
for (type in pokemonDetails.types) {
if(type.slot == 1) tvType1.text = type.type.name
if(type.slot == 2) tvType2.text = type.type.name
}
}
}<file_sep>package com.bylaew.exytepokeapi.model.PokemonById
data class Emerald(
val front_default: String,
val front_shiny: String
)<file_sep>package com.bylaew.exytepokeapi.service
import java.io.Serializable
data class Pokemon(val name: String) : Serializable {}<file_sep>package com.bylaew.exytepokeapi.model.PokemonInfo
data class Genera(
val genus: String,
val language: LanguageX
)<file_sep>package com.bylaew.exytepokeapi.model.PokemonById
data class Ability(
val ability: AbilityX,
val is_hidden: Boolean,
val slot: Int
)<file_sep>package com.bylaew.exytepokeapi.model.PokemonById
data class GenerationI(
val red_blue: RedBlue,
val yellow: Yellow
)<file_sep>package com.bylaew.exytepokeapi.utils
class Constants {
companion object{
const val BASE_URL = "https://pokeapi.co/api/v2/"
const val BASE_IMG_URL = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/"
}
}<file_sep>package com.bylaew.exytepokeapi.repository
import androidx.annotation.WorkerThread
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.bylaew.exytepokeapi.database.PokemonDAO
import com.bylaew.exytepokeapi.database.PokemonDB
import com.bylaew.exytepokeapi.model.PokemonById.PokemonById
import com.bylaew.exytepokeapi.service.ServiceInstance
import kotlinx.coroutines.flow.Flow
class PokemonRepository(private val pokDao: PokemonDAO? = null) {
val allPoks: LiveData<List<PokemonById>>? = pokDao?.all()
@WorkerThread
suspend fun insert(pok: PokemonById) {
pokDao?.addOne(pok)
}
fun getAllLocPoks() = pokDao?.all()
suspend fun getAllPokemons(limit: Int,offset:Int) =
ServiceInstance.api.getAllPokemons(limit,offset)
suspend fun getPokemonById(id : Int) =
ServiceInstance.api.getPokemonById(id)
suspend fun getDescriptionPokemon(id: Int) =
ServiceInstance.api.getInfoPokemon(id)
}<file_sep>package com.bylaew.exytepokeapi.model.Pokemon
data class PokemonResponse(
val count: Int,
val next: String,
val previous: Any,
val results: MutableList<PokemonResult>
)<file_sep>package com.bylaew.exytepokeapi.model.PokemonInfo
data class Name(
val language: LanguageXX,
val name: String
)<file_sep>package com.bylaew.exytepokeapi.adapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.bylaew.exytepokeapi.ui.info.AboutFragment
import com.bylaew.exytepokeapi.ui.info.StatsFragment
class ViewPageAdapter(fa: FragmentActivity) : FragmentStateAdapter(fa) {
override fun getItemCount(): Int = 2
override fun createFragment(position: Int): Fragment {
return when(position){
0 -> {
return AboutFragment()
}
1 -> {
return StatsFragment()
}
else -> StatsFragment()
}
}
}<file_sep>package com.bylaew.exytepokeapi.ui.info
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bylaew.exytepokeapi.model.PokemonById.PokemonById
import com.bylaew.exytepokeapi.model.PokemonInfo.PokemonInfo
import com.bylaew.exytepokeapi.repository.PokemonRepository
import com.bylaew.exytepokeapi.utils.Resource
import kotlinx.coroutines.launch
import retrofit2.Response
class InfoViewModel : ViewModel() {
val pokemonRepository: PokemonRepository = PokemonRepository()
val pokemonDetails : MutableLiveData<Resource<PokemonById>> = MutableLiveData()
val pokemonAbout : MutableLiveData <Resource<PokemonInfo>> = MutableLiveData()
var pokemonByIdResult : PokemonById? = null
var pokemonDescriptionResult : PokemonInfo? = null
fun getPokemonById(id: Int ) = viewModelScope.launch{
pokemonDetails.postValue(Resource.Loading())
val response = pokemonRepository.getPokemonById(id)
pokemonDetails.postValue(handlePokemonByIdResponse(response))
}
fun getDescriptionPokemon(id:Int) = viewModelScope.launch{
pokemonAbout.postValue(Resource.Loading())
val response = pokemonRepository.getDescriptionPokemon(id)
pokemonAbout.postValue(handlePokemonDescriptionResponse(response))
}
private fun handlePokemonByIdResponse(response: Response<PokemonById>): Resource<PokemonById>? {
if(response.isSuccessful){
response.body()?.let {resultResponse->
return Resource.Success(pokemonByIdResult ?: resultResponse)
}
}
return Resource.Error(response.message())
}
private fun handlePokemonDescriptionResponse(response: Response<PokemonInfo>): Resource<PokemonInfo>? {
if(response.isSuccessful){
response.body()?.let {resultResponse->
return Resource.Success(pokemonDescriptionResult ?: resultResponse)
}
}
return Resource.Error(response.message())
}
}<file_sep>package com.bylaew.exytepokeapi
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Window
import android.view.WindowManager
import android.widget.Toast
import androidx.appcompat.app.ActionBar
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.NavHostFragment.findNavController
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.NavigationUI
import androidx.navigation.ui.setupWithNavController
import com.bylaew.exytepokeapi.ui.favorite.FavoriteFragment
import com.bylaew.exytepokeapi.ui.main.MainFragment
import com.bylaew.exytepokeapi.ui.search.SearchFragment
import com.google.android.material.navigation.NavigationBarView
import kotlinx.android.synthetic.main.main_activity.*
class MainActivity : AppCompatActivity() {
lateinit var mainFragment: MainFragment
lateinit var favoriteFragment: FavoriteFragment
lateinit var searchFragment: SearchFragment
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.AppTheme)
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
// doing bad deprecated things
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.statusBarColor = ContextCompat.getColor(this,R.color.colorPrimary)
// probably end of doing bad things
initCustomToolbar()
bottomNavigationView.setupWithNavController(appNavHostFragment.findNavController())
bottomNavigationView?.setOnItemSelectedListener {
when (it.itemId) {
R.id.mainFragment -> {
appNavHostFragment.findNavController().navigate(R.id.mainFragment)
return@setOnItemSelectedListener true
}
R.id.savedFragment -> {
appNavHostFragment.findNavController().navigate(R.id.favoriteFragment)
return@setOnItemSelectedListener true
}
R.id.searchFragment -> {
appNavHostFragment.findNavController().navigate(R.id.searchFragment2)
return@setOnItemSelectedListener true
}
}
false
}
}
override fun onSupportNavigateUp(): Boolean {
return findNavController(R.id.appNavHostFragment).navigateUp()
}
private fun initCustomToolbar() {
supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM;
supportActionBar?.setCustomView(R.layout.custom_toolbar)
}
}<file_sep>package com.bylaew.exytepokeapi.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.bylaew.exytepokeapi.model.PokemonById.PokemonById
import com.bylaew.exytepokeapi.utils.Converter
@Database(entities = [PokemonById::class], version = 5, exportSchema = false)
@TypeConverters(Converter::class)
abstract class PokemonDB : RoomDatabase() {
abstract fun pokemonDAO(): PokemonDAO
companion object {
private var instance: PokemonDB? = null
fun getDatabase(context: Context): PokemonDB? {
if (instance == null) {
instance = buildDatabase(context)
}
return instance
}
private fun buildDatabase(context: Context) =
Room.databaseBuilder(
context.applicationContext,
PokemonDB::class.java,
"PokemonsRoom.db"
).build()
}
} | e290894b94a7680334578ccc0851f0f43701024e | [
"Kotlin"
] | 30 | Kotlin | Bylaew/ExytePokeApi | 81fd4588d6d077934fa501e25660f6599a493837 | a88f2befef1fa56f6c723eb6f980cf743bed33ab |
refs/heads/main | <repo_name>WMFaiz/Quality-Software-System<file_sep>/script.js
var counter = 0,
check1 = 0,
check2 = 0,
check3 = 0,
totalPT = 0,
totalPR = 0,
totalPO = 0;
$(document).ready(function () {
$('.content3').hide();
$("div > input[type=radio]").click(function () {
var thisParent = $(this).closest(".option");
var prevClicked = thisParent.find(":checked");
var currentObj = $(this);
prevClicked.each(function () {
if (!$(currentObj).is($(this))) {
$(this).prop("checked", false);
}
});
});
$('.radio').change(function () {
counter++
var parent = "." + $(this).closest('.option').parent().prop('className');
var superParent = $(this).closest('.option').parent().parent();
var supremeParent = $(this).closest('.option').parent().closest('.qc').parent().parent().prop('className');
var supersupremeParent = "." + $(this).closest('.option').parent().closest('.qc').parent().parent().parent().prop('className');
if ($(supersupremeParent).attr("class") === "PT_ul") {
totalPT = parseFloat(totalPT) + parseFloat($(this).val());
} else if ($(supersupremeParent).attr("class") === "PO_ul") {
totalPO = parseFloat(totalPO) + parseFloat($(this).val());
} else if ($(supersupremeParent).attr("class") === "PR_ul") {
totalPR = parseFloat(totalPR) + parseFloat($(this).val());
}
compileQuestion(counter);
$(parent).attr("name", "answered");
$(parent).hide('5000');
$(superParent).hide('6000');
switcher(supremeParent);
});
// window.addEventListener("keydown", function (event) {
// if (event.defaultPrevented) {
// return;
// }
// switch (event.key) {
// case "a":
// $("#yes").prop('checked', true);
// $("#maybe").prop('checked', false);
// $("#probably").prop('checked', false);
// $("#barely").prop('checked', false);
// $("#no").prop('checked', false);
// break;
// case "s":
// $("#yes").prop('checked', false);
// $("#maybe").prop('checked', true);
// $("#probably").prop('checked', false);
// $("#barely").prop('checked', false);
// $("#no").prop('checked', false);
// break;
// case "d":
// $("#yes").prop('checked', false);
// $("#maybe").prop('checked', false);
// $("#probably").prop('checked', true);
// $("#barely").prop('checked', false);
// $("#no").prop('checked', false);
// break;
// case "f":
// $("#yes").prop('checked', false);
// $("#maybe").prop('checked', false);
// $("#probably").prop('checked', false);
// $("#barely").prop('checked', true);
// $("#no").prop('checked', false);
// break;
// case "g":
// $("#yes").prop('checked', false);
// $("#maybe").prop('checked', false);
// $("#probably").prop('checked', false);
// $("#barely").prop('checked', false);
// $("#no").prop('checked', true);
// break;
// default:
// break;
// }
// });
TurnOff();
});
function compileQuestion(input) {
if (counter >= 0 && counter <= 3) {
$(".PT_Title").show();
$(".PO_Title").hide();
$(".PR_Title").hide();
} else if (counter > 3 && counter < 17) {
$(".PT_Title").hide();
$(".PO_Title").show();
$(".PR_Title").hide();
} else if (counter >= 18) {
$(".PT_Title").hide();
$(".PO_Title").hide();
$(".PR_Title").show();
}
if ($("." + input).attr("name") === "") {
$("." + input).closest(".qc").show();
}
if (input >= 24) {
$(".PR_Title").hide('5000');
$('.content3').show();
drawWithInputValue(this.totalPR, this.totalPO, this.totalPR);
}
}
function switcher(input) {
switch (input) {
case "portability_qc":
if (check1 >= 3) {
$(".PT_Title").hide('5000');
} else {
check1++;
}
break;
case "reusability_qc":
if (check1 >= 3) {
$(".PT_Title").hide('5000');
} else {
check1++;
}
break;
case "interoperability_qc":
if (check1 >= 3) {
$(".PT_Title").hide('5000');
} else {
check1++;
}
break;
case "correctness_qc":
if (check2 >= 14) {
$(".PO_Title").hide('5000');
} else {
check2++;
}
break;
case "reliability_qc":
if (check2 >= 14) {
$(".PO_Title").hide('5000');
} else {
check2++;
}
break;
case "efficiency_qc":
if (check2 >= 14) {
$(".PO_Title").hide('5000');
} else {
check2++;
}
break;
case "integrity_qc":
if (check2 >= 14) {
$(".PO_Title").hide('5000');
} else {
check2++;
}
break;
case "usability_qc":
if (check2 >= 14) {
$(".PO_Title").hide('5000');
} else {
check2++;
}
break;
case "maintainability_qc":
if (check3 >= 6) {
$(".PR_Title").hide('5000');
} else {
check3++;
}
break;
case "flexibility_qc":
if (check3 >= 6) {
$(".PR_Title").hide('5000');
} else {
check3++;
}
break;
case "testability_qc":
if (check3 >= 6) {
$(".PR_Title").hide('5000');
} else {
check3++;
}
break;
default:
break;
}
}
function TurnOff() {
for (var i = 0; i < 24; i++) {
var qc = $('.' + i).closest('.qc').prop('className');
$('.' + qc).hide();
}
$(".PO_Title").hide();
$(".PR_Title").hide();
if ($(".0").attr("name") === "") {
$(".0").closest('.qc').show();
}
}
function moveToPage(name) {
var checker = false;
for (var i = 0; i < 24; i++) {
if ($("." + i).attr("name") === "") {
checker = true;
i = 24;
} else if ($("." + i).attr("name") !== "") {
checker = false;
i = 24;
}
}
if (checker === true) {
localStorage.clear();
localStorage.setItem('setId', name);
passValuePage();
} else if (checker === false) {
alert("Refresh the page then choose your Test");
}
}
function passValuePage() {
var getId = localStorage.getItem('setId');
if (getId !== "") {
// $('html,body').animate({
// scrollTop: $("." + getId).offset().top
// }, 'smooth');
titleChecker(getId);
}
localStorage.clear();
}
function titleChecker(input) {
switch (input) {
case "PT_Title":
$(".PT_Title").show('5000');
$(".PO_Title").hide('5000');
$(".PR_Title").hide('5000');
$(".0").closest('.qc').show('5000');
$(".4").closest('.qc').hide('5000');
$(".18").closest('.qc').hide('5000');
counter = 0;
break;
case "PO_Title":
$(".PO_Title").show('5000');
$(".PT_Title").hide('5000');
$(".PR_Title").hide('5000');
$(".0").closest('.qc').hide('5000');
$(".4").closest('.qc').show('5000');
$(".18").closest('.qc').hide('5000');
counter = 4;
break;
case "PR_Title":
$(".PR_Title").show('5000');
$(".PO_Title").hide('5000');
$(".PT_Title").hide('5000');
$(".0").closest('.qc').hide('5000');
$(".4").closest('.qc').hide('5000');
$(".18").closest('.qc').show('5000');
counter = 18;
break;
default:
break;
}
} | 32a32d736b4ac2a382bdb6b56c6f7023d04ad018 | [
"JavaScript"
] | 1 | JavaScript | WMFaiz/Quality-Software-System | 82e31ca6d9f5707e7dcab12624968d19c82d605a | 7210fd1d7d6a04aeb264ead3e2bbfb599bc68cb6 |
refs/heads/master | <file_sep># ds18b20-arduino-testing
* First we need to download and install the libraries OneWire and DallasTemperature from below links:
- https://www.arduinolibraries.info/libraries/one-wire
- https://www.arduinolibraries.info/libraries/dallas-temperature
* To install libraries go to: Arduino IDE -> Sketch -> Include Library -> Add .ZIP Library..., and select downloaded libraries.
* Open Serial Monitor window: Tools -> Serial Monitor.
* Enter the ambient temperature in Serial Monitor.
* The program will display sensor/sensors number, address and current temperature reading in 'Readings' section.
* If the sensor detects temperature that is 2 degrees (or more) different than the ambient temperature, the sensor data and time since program start (in minutes) will be displayed in 'Errors' section.
<file_sep>#include <OneWire.h>
#include <DallasTemperature.h>
//Pin 2
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
struct error{
int number;
unsigned char* address;
float temperature;
unsigned long timeFromStart;
};
int currentError = 0;
float realTemp;
int numberOfDevices; // Number of temperature devices found
DeviceAddress tempDeviceAddress; // We'll use this variable to store a found device address
void setup() {
// Start serial port
Serial.begin(9600);
// Start up the library
sensors.begin();
numberOfDevices = sensors.getDeviceCount();
Serial.print("Locating devices...");
Serial.print(" Found ");
Serial.print(numberOfDevices);
Serial.println(" devices.");
Serial.print("Enter the ambient temperature: ");
while (Serial.available() == 0)
realTemp = Serial.parseFloat();
if (Serial.available() > 0)
Serial.println(realTemp);
}
void loop () {
numberOfDevices = sensors.getDeviceCount();
while (Serial.available() > 0){
for(int i = 0; i < numberOfDevices; i++) {
// Search the wire for address
if(!sensors.getAddress(tempDeviceAddress, i)) {
Serial.print("Found ghost device at ");
Serial.print(i+1);
Serial.print(" but could not detect address. Check power and cabling.");
}
}
if (numberOfDevices > 0){
Serial.println("Readings:");
Serial.println("Sensor | Address | Temperature");
}
else
Serial.print("Sensor cannot be checked.");
sensors.requestTemperatures(); // Send the command to get temperatures
float tempC;
float tempe[numberOfDevices];
unsigned char* addr[numberOfDevices];
unsigned long time = millis();
struct error errors[100];
// Loop through each device
for ( int i = 0; i < numberOfDevices; i++ ) {
// Search the wire for address
if(sensors.getAddress(tempDeviceAddress, i)){
tempC = sensors.getTempC(tempDeviceAddress);
tempe[i] = tempC;
addr[i] = tempDeviceAddress;
Serial.print(" ");
Serial.print(i+1);
Serial.print(" ");
printAddress(addr[i]);
Serial.print(" ");
Serial.println(tempe[i]);
}
}
Serial.println("______________________________________");
Serial.println("Errors:");
Serial.print("Sensor | Address | Temperature | Time[min]");
Serial.println();
for (int j = 0; j < numberOfDevices; j++){
if(sensors.getAddress(tempDeviceAddress, j) && abs(realTemp - tempe[j]) > 2){
currentError++;
errors[currentError].number = j;
errors[currentError].address = addr[j];
errors[currentError].temperature= tempe[j];
errors[currentError].timeFromStart = (time/60000);
}
for (int l = 0; l < currentError; l++){
if(j == errors[l+1].number){
Serial.print(" ");
Serial.print(j+1);
Serial.print(" ");
printAddress(errors[l+1].address);
Serial.print(" ");
Serial.print(errors[l+1].temperature);
Serial.print(" ");
Serial.println(errors[l+1].timeFromStart);
}
}
}
Serial.println();
delay(5000);
}
}
// function to print a device address
void printAddress(DeviceAddress deviceAddress) {
for (uint8_t i = 0; i < 8; i++) {
if (deviceAddress[i] < 16) Serial.print("0");
Serial.print(deviceAddress[i], HEX);
}
}
| de2696925ea83203aec2a7e958fb7714b4fceb85 | [
"Markdown",
"C++"
] | 2 | Markdown | iot-toolkit/ds18b20-arduino-testing | 85cb0926e63980c374c8e008e83c119db6d303b9 | 14b1b0cacd171297436cd5781f6913cd76a8f236 |
refs/heads/main | <repo_name>adarshshivhar/Spring-boot<file_sep>/SpringBootRestBook/src/main/java/com/api/book/services/BookServices.java
package com.api.book.services;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.stereotype.Component;
import com.api.book.modal.Book;
@Component
public class BookServices {
private static List<Book> list = new ArrayList<>();
static {
list.add(new Book(11, "abcd", "efgh"));
list.add(new Book(12, "abcde", "efghe"));
list.add(new Book(13, "abcdg", "efghg"));
}
//get all books
public List<Book> getBooks() {
return list;
}
//get specific book
public Book getBookById(int id) {
Book book = null;
book = list.stream().filter(e -> e.getId()==id).findFirst().get();
return book;
}
//Add book to list
public Book addBookToList(Book book) {
list.add(book);
return book;
}
public void deleteBookById(int id) {
list = list.stream().filter(e -> e.getId() != id).collect(Collectors.toList());
}
public void updateBook(Book book, int id) {
list.stream().map(e -> {
if(e.getId() == id) {
e.setTitle(book.getTitle());
e.setAuthor(book.getAuthor());
}
return e;
}).collect(Collectors.toList());
}
}
<file_sep>/README.md
# Spring-boot
- Jackson is used to convert object to JSON and vice-versa.
| e8729df283b86eee4e97fd6ecfceb1a09604f4e3 | [
"Markdown",
"Java"
] | 2 | Java | adarshshivhar/Spring-boot | e758c2ea352264619505d89a4fe7ddc158a64390 | 80ed64f7d023a6d1ce3b5b3afc7ed664a44a7fe2 |
refs/heads/master | <repo_name>masa-kunikata/carta_reader<file_sep>/data/3nenkanji/Gemfile
source 'https://rubygems.org'
gem 'rake'
gem 'rest-client'
gem 'oga'<file_sep>/data/hyakuninisshu/Rakefile
require 'json'
task default: :text_to_json
DATA_FILE = 'hyakuninisshu_data.txt'
OUT_JSON = '../hyakuninisshu.json'
#property 上の句 上の句カナ 下の句 下の句カナ 作者
LINE_REGEX = /
(?<no>[0-9]+?)\t
(?<kami>.+?)\t
(?<kamikana>.+?)\t
(?<shimo>.+?)\t
(?<shimokana>.+?)\t
(?<author>.+?)\Z
/x
desc "data text to json"
task :text_to_json do
content = File.read(DATA_FILE, encoding: Encoding::UTF_8)
json_data = []
content.each_line do |line|
next if line =~ /^#/ # comment line
m = LINE_REGEX.match(line)
json_data << "#{m['kamikana']} #{m['shimokana']}"
end
File.write(OUT_JSON, json_data.to_json, encoding: Encoding::UTF_8)
end
def category_out(prefixes, out_path)
content = File.read(DATA_FILE, encoding: Encoding::UTF_8)
json_data = []
content.each_line do |line|
next if line =~ /^#/ # comment line
m = LINE_REGEX.match(line)
next unless prefixes.include?(m['kamikana'])
json_data << {
text: "#{m['kami']} #{m['shimo']}",
read: "#{m['kamikana']}、、、#{m['shimokana']}",
}
end
File.write(out_path, json_data.to_json, encoding: Encoding::UTF_8)
end
BLUE_PREFIXES = [
"アシビキノ ヤマドリノオノ シダリオノ",
"アリアケノ ツレナクミエシ ワカレヨリ",
"アラシフク ミムロノヤマノ モミジバワ",
"オクヤマニ モミジフミワケ ナクシカノ",
"アサボラケ アリアケノツキト ミルマデニ",
"サビシサニ ヤドオタチイデテ ナガムレバ",
"カササギノ ワタセルハシニ オクシモノ",
"キミガタメ オシカラザリシ イノチサエ",
"ウカリケル ヒトオハツセノ ヤマオロシヨ",
"アマツカゼ クモノカヨイジ フキトジヨ",
"メグリアイテ ミシヤソレトモ ワカヌマニ",
"ワタノハラ コギイデテミレバ ヒサカタノ",
"ミチノクノ シノブモジズリ タレユエニ",
"イニシエノ ナラノミヤコノ ヤエザクラ",
"キリギリス ナクヤシモヨノ サムシロニ",
"コノタビワ ヌサモトリアエズ タムケヤマ",
"ヨオコメテ トリノソラネワ ハカルトモ",
"モモシキヤ フルキノキバノ シノブニモ",
"チギリオキシ サセモガツユオ イノチニテ",
"オモイワビ サテモイノチワ アルモノオ",
]
RED_PREFIXES = %w<
ナゲケトテ ツキヤワモノオ オモワスル
コヌヒトオ マツオノウラノ ユーナギニ
モロトモニ アワレトオモエ ヤマザクラ
オトニキク タカシノハマノ アダナミワ
タカサゴノ オノエノサクラ サキニケリ
ナガカラン ココロモシラズ クロカミノ
カクトダニ エヤワイブキノ サシモグサ
アリマヤマ イナノササハラ カゼフケバ
ウラミワビ ホサヌソデダニ アルモノオ
タレオカモ シルヒトニセン タカサゴノ
シノブレド イロニイデニケリ ワガコイワ
カゼオイタミ イワウツナミノ オノレノミ
タチワカレ イナバノヤマノ ミネニオール
フクカラニ アキノクサキノ シオルレバ
ヤマザトワ フユゾサビシサ マサリケル
アキノタノ カリオノイオノ トマオアラミ
タゴノウラニ ウチイデテミレバ シロタエノ
ツクバネノ ミネヨリオツル ミナノガワ
ヨノナカヨ ミチコソナケレ オモイイル
ナガラエバ マタコノゴロヤ シノバレン
>
YELLOW_PREFIXES = %w<
ハルスギテ ナツキニケラシ シロタエノ
アマノハラ フリサケミレバ カスガナル
コレヤコノ ユクモカエルモ ワカレテワ
スミノエノ キシニヨルナミ ヨルサエヤ
ヤマガワニ カゼノカケタル シガラミワ
ヒサカタノ ヒカリノドケキ ハルノヒニ
シラツユニ カゼノフキシク アキノノワ
アサジウノ オノノシノハラ シノブレド
ユラノトオ ワタルフナビト カジオタエ
ヤエムグラ シゲレルヤドノ サビシキニ
タキノオトワ タエテヒサシク ナリヌレド
オーエヤマ イクノノミチノ トーケレバ
アワジシマ カヨーチドリノ ナクコエニ
アキカゼニ タナビククモノ タエマヨリ
ホトトギス ナキツルカタオ ナガムレバ
ムラサメノ ツユモマダヒヌ マキノハニ
ミヨシノノ ヤマノアキカゼ サヨフケテ
ハナサソー アラシノニワノ ユキナラデ
ヨモスガラ モノオモーコロワ アケヤラデ
タマノオヨ タエナバタエネ ナガラエバ
>
GREEN_PREFIXES = %w<
ワガイオワ ミヤコノタツミ シカゾスム
ハナノイロワ ウツリニケリナ イタズラニ
ワタノハラ ヤソシマカケテ コギイデヌト
キミガタメ ハルノノニイデテ ワカナツム
チハヤブル カミヨモキカズ タツタガワ
ワビヌレバ イマハタオナジ ナニワナル
ツキミレバ チジニモノコソ カナシケレ
オグラヤマ ミネノモミジバ ココロアラバ
ココロアテニ オラバヤオラン ハツシモノ
ヒトワイサ ココロモシラズ フルサトワ
ナツノヨワ マダヨイナガラ アケヌルオ
ワスラルル ミオバオモワズ チカイテシ
コイスチョー ワガナワマダキ タチニケリ
チギリキナ カタミニソデオ シボリツツ
ワスレジノ ユクスエマデワ カタケレバ
ヤスラワデ ネナマシモノオ サヨフケテ
ココロニモ アラデウキヨニ ナガラエバ
ユーサレバ カドタノイナバ オトズレテ
ワガソデワ シオヒニミエヌ オキノイシノ
ヨノナカワ ツネニモガモナ ナギサコグ
>
ORANGE_PREFIXES = %w<
アケヌレバ クルルモノトワ シリナガラ
アサボラケ ウジノカワギリ タエダエニ
アワレトモ ユーベキヒトワ オモオエデ
アイミテノ ノチノココロニ クラブレバ
オーコトノ タエテシナクワ ナカナカニ
アラザラン コノヨノホカノ オモイデニ
イマコント イイシバカリニ ナガツキノ
イマワタダ オモイタエナン トバカリオ
セオハヤミ イワニセカルル タキガワノ
ナゲキツツ ヒトリヌルヨノ アクルマワ
ナニシオワバ オーサカヤマノ サネカズラ
ナニワエノ アシノカリネノ ヒトヨユエ
ナニワガタ ミジカキアシノ フシノマモ
ハルノヨノ ユメバカリナル タマクラニ
ヒトモオシ ヒトモウラメシ アジキナク
ミカキモリ エジノタクヒノ ヨルワモエ
ミカノハラ ワキテナガルル イズミガワ
ミセバヤナ オジマノアマノ ソデダニモ
オオケナク ウキヨノタミニ オオーカナ
カゼソヨグ ナラノオガワノ ユーグレワ
>
%w<blue red yellow green orange>.each.with_index do |color, index|
const_sym = :"#{color.upcase}_PREFIXES"
target_prefixes = self.class.const_get(const_sym)
desc "#{color} data text to json"
task :"#{color}_category" do
category_out(target_prefixes, "../hya_#{'%02d' % (index + 1)}_#{color}.json")
end
end
<file_sep>/README.md
# carta_reader
Carta game "reader" for Niko
# sample
|Title| interval <br>(Vue.js) | click <br>(Vue.js) |
|:---|:---|:---|
|Capital cities (ANA trump) | [5 sec](https://masa-kunikata.github.io/carta_reader/vue.html?data=cities&sec=5) | [click](https://masa-kunikata.github.io/carta_reader/vue.html?data=cities) |
|Countries (ANA trump) | [5 sec](https://masa-kunikata.github.io/carta_reader/vue.html?data=countries&sec=5) | [click](https://masa-kunikata.github.io/carta_reader/vue.html?data=countries) |
|HyakuninIsshu | [20 sec](https://masa-kunikata.github.io/carta_reader/vue.html?data=hyakuninisshu&sec=20&speed=70) | [click](https://masa-kunikata.github.io/carta_reader/vue.html?data=hyakuninisshu) |
|Niko Carta | [7 sec](https://masa-kunikata.github.io/carta_reader/vue.html?data=nikocarta&sec=7) | [click](https://masa-kunikata.github.io/carta_reader/vue.html?data=nikocarta) |
|Chizukigo | [7 sec](https://masa-kunikata.github.io/carta_reader/vue.html?data=chizukigo&sec=7) | [click](https://masa-kunikata.github.io/carta_reader/vue.html?data=chizukigo) |
|3nen Kanji | [7 sec](https://masa-kunikata.github.io/carta_reader/vue.html?data=3nenkanji&sec=7) | [click](https://masa-kunikata.github.io/carta_reader/vue.html?data=3nenkanji) |
|hya_01_blue | [15 sec](https://masa-kunikata.github.io/carta_reader/vue.html?data=hya_01_blue&sec=15&speed=70) | [click](https://masa-kunikata.github.io/carta_reader/vue.html?data=hya_01_blue) |
|hya_02_blue | [15 sec](https://masa-kunikata.github.io/carta_reader/vue.html?data=hya_02_red&sec=15&speed=70) | [click](https://masa-kunikata.github.io/carta_reader/vue.html?data=hya_02_red) |
|kuku | [read answer](https://masa-kunikata.github.io/carta_reader/kuku.html?readAnswer=true&sec=8) | [no answer](https://masa-kunikata.github.io/carta_reader/kuku.html?readAnswer=false&sec=8) |
|edo_iroha | [15 sec](https://masa-kunikata.github.io/carta_reader/vue.html?data=edo_iroha&sec=15) | [click](https://masa-kunikata.github.io/carta_reader/vue.html?data=edo_iroha) |
<file_sep>/data/3nenkanji/Rakefile
require 'json'
require 'rest-client'
require 'cgi'
require 'json'
require 'yaml'
require 'erb'
require 'oga'
class ApiClient
def initialize(url)
@url = url
end
def get(params)
res = RestClient.get(@url, params: params)
return nil if res.code != 200
res.body
end
end
SECRET_KEYS = YAML.load_file('secret_keys.yml')
A3RT_TEXT_SUGGEST_URL = "https://api.a3rt.recruit-tech.co.jp/text_suggest/v2/predict?apikey=#{SECRET_KEYS['a3rt_text_suggest']}".freeze
class DejizoClient
DEJIZO_URL = "http://public.dejizo.jp/NetDicV09.asmx/SearchDicItemLite"
DEJIZO_FIX_PARAMS = {
'Dic': 'wpedia',
'Scope': 'HEADWORD',
'Match': 'EXACT',
'Merge': 'AND',
'Prof': 'XHTML',
'PageSize': '1',
'PageIndex': '0',
}
def initialize
@cli = ApiClient.new(DEJIZO_URL)
end
def get(word)
@cli.get(DEJIZO_FIX_PARAMS.merge({'word': word}))
end
end
#-----------
task default: :check_data
KANJIS = %w<
丁 世 両 主 乗 予 事 仕 他 代 全 住 使 係 倍 具 写 列 助 勉
動 勝 化 区 医 去 反 取 受 号 向 君 味 命 和 品 員 商 問 坂
央 委 始 安 守 実 定 客 宮 宿 寒 対 局 屋 岸 島 州 帳 平 幸
度 庫 庭 式 役 待 苦 荷 葉 落 薬 返 送 追 速 進 運 遊 都 部
院 階 陽 急 息 悪 悲 意 感 想 所 打 投 指 持 拾 放 整 旅 族
昔 昭 暑 暗 曲 有 服 期 板 柱 根 植 業 様 横 橋 次 死 氷 決
泳 注 波 油 洋 消 流 深 温 湖 港 湯 漢 炭 物 球 申 由 界 畑
病 発 登 皮 皿 県 相 真 短 研 礼 神 祭 福 秒 究 章 童 第 笛
等 筆 箱 級 終 緑 練 羊 美 着 習 者 育 血 表 詩 談 調 豆 負
起 路 身 転 軽 農 酒 配 重 鉄 銀 開 集 面 題 飲 館 駅 歯 鼻
>
TOCHU_YAML = '3nenkanji.yml'
def subtract_kanjis_from(tochu_list)
all_chars = tochu_list.map{|s| s.each_char.to_a}.flatten
KANJIS - all_chars
end
desc "check data"
task :check_data do
tochu_list = YAML.load_file(TOCHU_YAML)
subtract_kanjis = subtract_kanjis_from(tochu_list)
content = CHECK_DATA_ERB_TEMPLATE.result(binding)
File.write(TOCHU_YAML, content, encoding: Encoding::UTF_8)
end
CHECK_DATA_ERB_TEMPLATE = ERB.new(<<-EOS)
---
<%
KANJIS.each_slice(20).each do |kanjis| %># <%
kanjis.each do |k|
if subtract_kanjis.include?(k) then
%><%= k %> <%
else
%> <%
end
end %>
<%
end
%>
<% tochu_list.each do |t|
%>- <%= t %>
<%
end
%>
EOS
OUT_SENTENCE = 'bun.yml'
task :sentence do
api_client = ApiClient.new(A3RT_TEXT_SUGGEST_URL)
resp = JSON.parse(api_client.get('漢字'))
File.open(OUT_SENTENCE, 'w') do |f|
puts resp['suggestion']
f.puts resp
end
# File.write(OUT_JSON, json_data.to_json, encoding: Encoding::UTF_8)
end
OUT_JUKUGO = 'jukugo.yml'
task :jukugo_list do
begin
tochu_list = YAML.load_file(TOCHU_YAML)
subtract_kanjis = subtract_kanjis_from(tochu_list)
dejizo_cli = DejizoClient.new
hit_count_of = ->(word)do
xml = dejizo_cli.get(word)
sleep 3
doc = Oga.parse_xml(xml)
doc.xpath("//SearchDicItemResult/TotalHitCount").text.to_i
end
hit_kanjis = []
hit_jukugo = []
no_hit_pairs = []
subtract_kanjis.each do |k|
puts
puts "(#{k})"
next if hit_kanjis.include?(k)
subtract_kanjis.each do |j|
$stdout.write " (#{j})"
next if hit_kanjis.include?(k)
next if hit_kanjis.include?(j)
next if no_hit_pairs.include?([k, j].sort)
next if k == j
hit = nil
["#{k}#{j}", "#{j}#{k}"].each do |jukugo|
if 0 < hit_count_of[jukugo]
hit = true
puts jukugo
hit_jukugo << jukugo
hit_kanjis << k
hit_kanjis << j
break
end
end
next if hit
# no hit!
no_hit_pairs << [k, j].sort
end
end
ensure
File.write(OUT_JUKUGO, hit_jukugo.to_json, encoding: Encoding::UTF_8) rescue nil
end
end
OUT_JSON = '../3nenkanji.json'
desc "data text to json"
task :data_text_to_json do
list = YAML.load_file(TOCHU_YAML)
recs = KANJIS.zip(list)
File.write(OUT_JSON, JSON_TEMPLATE.result(binding), encoding: Encoding::UTF_8)
end
JSON_TEMPLATE = ERB.new(<<-EOS)
<%
recs.each.with_index do |(kanji, bun), i|
html = bun.sub(kanji, "<span class='kyocho'>" + kanji + "</span>")
%><%= (i == 0 ? '[' : ',') %>{"read": "<%= bun %>", "html": "<%= html %>"}
<%
end
%>]
EOS
<file_sep>/data/edo_iroha/Rakefile
require 'json'
task default: :data_text_to_json
OUT_JSON = '../edo_iroha.json'
INPUT_FILE = './edo_iroha.txt'
desc "data text to json"
task :data_text_to_json do
contents = File.read(INPUT_FILE, encoding: Encoding::CP932)
File.write(OUT_JSON, contents.each_line.to_a.map{|line| line.chomp('')}, encoding: Encoding::UTF_8)
end
<file_sep>/data/kuku/Rakefile
require 'pp'
require 'yaml'
require 'json'
require 'erb'
task default: :out_html
READ_YML = YAML.load_file(File.join(__dir__, 'kuku_read.yml'))
KUKU_HTML_TEMPLATE = ERB.new(
File.read(File.join(__dir__, 'kuku.html.erb'), encoding: Encoding::UTF_8)
)
desc "out_html"
task :out_html do
nums = (1..9).to_a
kuku_nums = nums.product(nums)
qas = kuku_nums.map{|a, b| {q: "q#{a}_#{b}", a: "a#{a * b}"}}
question_reads = READ_YML['questions']
answer_reads = READ_YML['answers']
grouped_kuku = qas.group_by{|qa| qa[:a]}
.map do |a, same_aqs|
q_map = same_aqs.map do |aq|
q = aq[:q]
m = /q(?<a>.)_(?<b>.)/.match(q)
[question_reads[q], "#{m['a']} × #{m['b']}"]
end.to_h
[answer_reads[a], q_map]
end
.to_h
answers = answer_reads
.map do |akey, ayomi|
answer = akey.sub("a", '').to_i
[ayomi, answer]
end.to_h
kuku_json = grouped_kuku.to_json
answers_json = answers.to_json
File.write("../kuku.html", KUKU_HTML_TEMPLATE.result(binding))
end
| e52b0b9536e169b260a75629596f3bf02a533fcf | [
"Markdown",
"Ruby"
] | 6 | Ruby | masa-kunikata/carta_reader | 1a0e317c7b9fd0de36c57f7decea8e66e4a5d6bf | 33a979fc316c56a6fe82e8020bdad5d545516219 |
refs/heads/master | <file_sep>chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method === 'getText') {
sendResponse({ data: document.all[0].innerText, method: 'getText' }); // same as innerText
}
});
| d1cad48abb2bb6d403d9613cec84011e32bee10b | [
"JavaScript"
] | 1 | JavaScript | SUSTechFlow/chrome-extension | e848b49d8d4a1259ca7d13d121f4e8077838b643 | a2dbaaac2501742984bd9c3f8a3e5969b450d540 |
refs/heads/master | <repo_name>saisagar96/Full-Stack-Web-Development-Session-6.1-Assignment<file_sep>/assignment 6.1/script.js
// The below alert will be called from the index file
alert ("I am from external file");<file_sep>/README.md
# Full-Stack-Web-Development-Session-6.1-Assignment
This is for Full Stack Web Development Session 6.1 Assignment
| 633c015e3b0bccf0b96f10989637c4274c3ea4d3 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | saisagar96/Full-Stack-Web-Development-Session-6.1-Assignment | da762970a969f89147f7b3fecff0672b8a1cdc22 | 7ff2be52bf48604e084f03dcc43b5dab6739bd15 |
refs/heads/master | <file_sep>import React,{ Component } from 'react';
import {
Nav,
Header,
Nosotros,
Pizzas,
Empanadas,
Team,
Contacto,
Footer,
Modals
} from './Components.jsx'
export class Principal extends Component{
render(){
return(
<div id="page-top" name="page-top" className="index">
<Nav/>
<Header/>
<Nosotros/>
<Pizzas/>
<Empanadas/>
<Team/>
<Contacto/>
<Footer/>
<Modals/>
</div>
)
}
}
<file_sep>import React,{ Component } from 'react';
import info from './Objects/pizzas.json';
export const PizzasItems = () => {
let pizzas = info.pizzas;
let pizzasitems = [];
pizzas.map(
(pizza) =>{
let imgurl = "img/pizzas/"+pizza.id+".png";
let modal = "#pizza"+pizza.id;
pizzasitems.push(
<div className="col-md-2 col-sm-2 portfolio-item" key={modal}>
<a href={modal} className="portfolio-link" data-toggle="modal">
<div className="portfolio-hover">
<div className="portfolio-hover-content">
<i className="fa fa-plus fa-3x"></i>
</div>
</div>
<img src={imgurl} className="img-responsive" alt=""/>
</a>
<div className="portfolio-caption">
<h4>{pizza.nombre}</h4>
<p className="text-muted">{pizza.detalle}</p>
</div>
</div>
);
}
)
return(
<div>
{pizzasitems}
</div>
)
}
export const EmpanadasItems = () => {
let empanadas = info.empanadas;
let empanadasitems = [];
empanadas.map(
(empanada) =>{
let imgurl = "img/empanadas/"+empanada.id+".png";
let modal = "#empanada"+empanada.id;
empanadasitems.push(
<div className="col-md-4 col-sm-4 portfolio-item" key={modal}>
<a href={modal} className="portfolio-link" data-toggle="modal">
<div className="portfolio-hover">
<div className="portfolio-hover-content">
<i className="fa fa-plus fa-3x"></i>
</div>
</div>
<img src={imgurl} className="img-responsive" alt=""/>
</a>
<div className="portfolio-caption">
<h4>{empanada.nombre}</h4>
<p className="text-muted">{empanada.detalle}</p>
</div>
</div>
);
}
)
return(
<div>
{empanadasitems}
</div>
)
}
export const PizzasModals = () => {
let pizzas = info.pizzas;
let pizzasModals = [];
pizzas.map(
(pizza) =>{
let imgurl = "img/pizzas/"+pizza.id+".png";
let id = "pizza"+pizza.id;
pizzasModals.push(
<div className="portfolio-modal modal fade" key={id} id={id} tabIndex="-1" role="dialog" aria-hidden="true">
<div className="modal-dialog">
<div className="modal-content">
<div className="close-modal" data-dismiss="modal">
<div className="lr">
<div className="rl">
</div>
</div>
</div>
<div className="container">
<div className="row">
<div className="col-lg-8 col-lg-offset-2">
<div className="modal-body">
<h2>{pizza.nombre}</h2>
<p className="item-intro text-muted">Descripcion</p>
<img
className="img-responsive img-centered"
src={imgurl}
alt=""/>
<p>Texto comun!</p>
<p>
<strong>Texto en negrita :D</strong>... mas Texto
</p>
<button type="button" className="btn btn-primary" data-dismiss="modal"><i className="fa fa-times"></i>Cerrar</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
)
return(
<div>
{pizzasModals}
</div>
)
}
export const EmpanadasModals = () => {
let empanadas = info.empanadas;
let empanadasModals = [];
empanadas.map(
(empanada) =>{
let imgurl = "img/empanadas/"+empanada.id+".png";
let id = "empanada"+empanada.id;
empanadasModals.push(
<div className="portfolio-modal modal fade" key={id} id={id} tabIndex="-1" role="dialog" aria-hidden="true">
<div className="modal-dialog">
<div className="modal-content">
<div className="close-modal" data-dismiss="modal">
<div className="lr">
<div className="rl">
</div>
</div>
</div>
<div className="container">
<div className="row">
<div className="col-lg-8 col-lg-offset-2">
<div className="modal-body">
<h2>{empanada.nombre}</h2>
<p className="item-intro text-muted">Descripcion</p>
<img
className="img-responsive img-centered"
src={imgurl}
alt=""/>
<p>Texto comun!</p>
<p>
<strong>Texto en negrita :D</strong>... mas Texto
</p>
<button type="button" className="btn btn-primary" data-dismiss="modal"><i className="fa fa-times"></i>Cerrar</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
)
return(
<div>
{empanadasModals}
</div>
)
} | 74e59352c162ebec07836f30fca9ca6b54881681 | [
"JavaScript"
] | 2 | JavaScript | heberlipe/personal1 | 1cfaf3e3e6f66dcd0c2f60bb32a8a0af6521ba1a | 8482bc1b79b8a6eec8d2e928f0bea7b17c9da3b3 |
refs/heads/master | <file_sep>package coil.bitmap
import android.graphics.Bitmap
import android.util.Log
import androidx.annotation.VisibleForTesting
import androidx.collection.SparseArrayCompat
import androidx.collection.set
import androidx.collection.size
import coil.memory.WeakMemoryCache
import coil.util.Logger
import coil.util.forEachIndices
import coil.util.identityHashCode
import coil.util.log
import java.lang.ref.WeakReference
/**
* Count references to [Bitmap]s and add them to a [BitmapPool] when they're no longer referenced.
*/
internal interface BitmapReferenceCounter {
/**
* Increase the reference count for this [Bitmap] by one.
*/
fun increment(bitmap: Bitmap)
/**
* Decrease the reference count for this [Bitmap] by one.
*
* If the reference count is now zero, add the [Bitmap] to the [BitmapPool].
*
* @return True if [bitmap] was added to the [BitmapPool] as a result of this decrement operation.
*/
fun decrement(bitmap: Bitmap): Boolean
/**
* Mark [bitmap] as valid/invalid.
*
* Only valid bitmaps are added to the [BitmapPool] when its reference count reaches zero.
*/
fun setValid(bitmap: Bitmap, isValid: Boolean)
}
internal object EmptyBitmapReferenceCounter : BitmapReferenceCounter {
override fun increment(bitmap: Bitmap) {}
override fun decrement(bitmap: Bitmap) = false
override fun setValid(bitmap: Bitmap, isValid: Boolean) {}
}
internal class RealBitmapReferenceCounter(
private val weakMemoryCache: WeakMemoryCache,
private val bitmapPool: BitmapPool,
private val logger: Logger?
) : BitmapReferenceCounter {
@VisibleForTesting internal val values = SparseArrayCompat<Value>()
@VisibleForTesting internal var operationsSinceCleanUp = 0
@Synchronized
override fun increment(bitmap: Bitmap) {
val key = bitmap.identityHashCode
val value = getValue(key, bitmap)
val newCount = value.count + 1
value.count = newCount
logger?.log(TAG, Log.VERBOSE) { "INCREMENT: [$key, $newCount]" }
cleanUpIfNecessary()
}
@Synchronized
override fun decrement(bitmap: Bitmap): Boolean {
val key = bitmap.identityHashCode
val value = getValueOrNull(key, bitmap) ?: return false
val newCount = value.count - 1
value.count = newCount
logger?.log(TAG, Log.VERBOSE) { "DECREMENT: [$key, $newCount]" }
// If the bitmap is valid and its count reaches 0, remove it from the
// WeakMemoryCache and add it to the BitmapPool.
val removed = newCount <= 0 && value.state == STATE_VALID
if (removed) {
values.remove(key)
weakMemoryCache.remove(bitmap)
bitmapPool.put(bitmap)
}
cleanUpIfNecessary()
return removed
}
@Synchronized
override fun setValid(bitmap: Bitmap, isValid: Boolean) {
val key = bitmap.identityHashCode
val value = getValue(key, bitmap)
if (value.state != STATE_INVALID) {
value.state = if (isValid) STATE_VALID else STATE_INVALID
}
cleanUpIfNecessary()
}
private fun cleanUpIfNecessary() {
if (operationsSinceCleanUp++ >= CLEAN_UP_INTERVAL) {
cleanUp()
}
}
@VisibleForTesting
internal fun cleanUp() {
val toRemove = arrayListOf<Int>()
for (index in 0 until values.size) {
val value = values.valueAt(index)
if (value.bitmap.get() == null) {
// Don't remove the values while iterating over the loop so
// we don't trigger SparseArray's internal GC for each removal.
toRemove += index
}
}
toRemove.forEachIndices(values::removeAt)
}
private fun getValue(key: Int, bitmap: Bitmap): Value {
var value = getValueOrNull(key, bitmap)
if (value == null) {
value = Value(WeakReference(bitmap), 0, STATE_UNSET)
values[key] = value
}
return value
}
private fun getValueOrNull(key: Int, bitmap: Bitmap): Value? {
return values[key]?.takeIf { it.bitmap.get() === bitmap }
}
@VisibleForTesting
internal class Value(
val bitmap: WeakReference<Bitmap>,
var count: Int,
var state: Int
)
companion object {
private const val TAG = "RealBitmapReferenceCounter"
private const val CLEAN_UP_INTERVAL = 50
internal const val STATE_UNSET = 0
internal const val STATE_VALID = 1
internal const val STATE_INVALID = 2
}
}
| 51e5ebd94cc38c17765e22e16fbe10c3971b4a2a | [
"Kotlin"
] | 1 | Kotlin | fudaye/coil | 25948e83577a2e97aa9fdb1d9dd2eebc5c38480c | c2d3534246893dffbee6a81d0f1288f84b80dc36 |
refs/heads/master | <repo_name>freitit/teenplus<file_sep>/web3/apps.py
from django.apps import AppConfig
class Web3Config(AppConfig):
name = 'web3'
<file_sep>/web3/admin.py
from django.contrib import admin
# Register your models here.
# from .models import Ajjaxdemoo
# admin.site.register(Ajjaxdemoo)<file_sep>/web3/forms.py
from django import forms
from .models_from_db import Entity
from django.contrib.auth.forms import AuthenticationForm
from django.forms.widgets import PasswordInput, TextInput
class EntityForm(forms.Form):
# entity_id = forms.IntegerField(required=False)
title = forms.CharField(widget=forms.Textarea)
content = forms.CharField(widget=forms.Textarea)
image = forms.FileField()
created_date = forms.DateField(required=False)
user_id = forms.IntegerField(required=False)
theme = forms.CharField(max_length=255)
# class Meta:
# model = Entity
# fields = "__all__"
class AuthenForm(AuthenticationForm):
username = forms.CharField(widget=TextInput(attrs={'class': 'input','placeholder': '<NAME>'}))
password = forms.CharField(widget=PasswordInput(attrs={'class': 'input','placeholder':'<PASSWORD>'}))<file_sep>/web3/urls.py
from django.urls import path
from django.contrib.auth import views as authviews
from . import views
from .forms import AuthenForm
urlpatterns = [
path('', views.index, name='index'),
path('show',views.showPost),
path('show/<int:user_id>',views.showPost),
path('addPost', views.addPost, name='addpost'),
path('editPost/<int:id>', views.editPost),
path('updatePost/<int:id>', views.updatePost),
path('removePost/<int:id>', views.removePost),
path('login', authviews.LoginView.as_view(form_class=AuthenForm), name='login'),
path('logout', authviews.LogoutView.as_view(), name='logout'),
]
# path('ajax/increase', views.increaseActionNumber, name='increaseActionNumber'),
# path('ajax', views.getActionNumber, name='getActionNumber')<file_sep>/web3/models.py
from django.db import models
# Create your models here.
# class Ajjaxdemoo(models.Model):
# user = models.CharField(max_length=200)
# likee = models.IntegerField()
# def __str__(self):
# return self.user
# def likeenum(self):
# return str(self.likee)
# class Login(models.Model):
# username = models.CharField(max_length=100)
# password = models.CharField(max_length=200)
# class User(models.Model):
# name = models.CharField(max_length=200)
# birthday = models.DateField()
# email = models.EmailField()
# joinedday = models.DateField()
# nationality = models.CharField(max_length=50)
# class Health(models.Model):
<file_sep>/web3/views.py
from django.http import HttpResponse, JsonResponse
from django.template import loader
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.conf import settings
import json
from .models_from_db import Entity, HealthPost
from .forms import EntityForm
@login_required(login_url="login")
def index(request):
list_post_id = getTopPostID(5)
title = []
content = []
image = []
for post_id in list_post_id:
post = getPost(post_id)
title.append(post["title"])
content.append(post["content"])
image.append(post["image"])
post_list = zip(title, content, image)
return render(request, "web3/index.html", context = {'a_post':post_list, 'username':request.user.username, 'userid':request.user.id})
def getPost(post_id):
result = Entity.objects.get(entity_id = post_id)
context = {
'title': result.title,
'content': result.content,
'image': result.image,
}
return context
def getTopPostID(topNum):
results = Entity.objects.all().order_by('-created_date')[:topNum]
list = []
for result in results:
list.append(result.entity_id)
return list
# def increaseActionNumber(request):
# record = Ajjaxdemoo.objects.get(user="abc")
# record.likee += 1
# record.save()
# return HttpResponse("success")
# def getActionNumber(request):
# record = Ajjaxdemoo.objects.get(user="abc")
# data = {
# 'user': record.user,
# 'likenumber':record.likee,
# }
# return HttpResponse(record.likee, content_type="text/plain")
# Views related to Posts of a user
def showPost(request, user_id = 1):
posts = Entity.objects.filter(user_id = user_id)
return render(request, "web3/show.html", {'posts':posts})
def addPost(request):
if request.method == "POST":
form = EntityForm(request.POST, request.FILES)
if form.is_valid():
try:
form.save()
return redirect('/web3')
except:
pass
else:
form = EntityForm()
return render(request,'web3/addPost.html',{'form':form, 'userid':request.user.id})
def editPost(request, id):
post = Entity.objects.get(entity_id=id)
return render(request,'web3/updatePost.html', {'post':post})
def updatePost(request, id):
post = Entity.objects.get(entity_id=id)
form = EntityForm(request.POST, instance=post)
if form.is_valid():
form.save()
return redirect("/web3/show")
return render(request, 'web3/updatePost.html', {'post': post})
def removePost(request, id):
post = Entity.objects.get(entity_id = id)
post.delete()
return redirect("/web3/show")
def save_uploaded_file_to_media_root(f):
with open('%s%s' % (settings.MEDIA_ROOT,f.name), 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk) | ee4a5ec1a4cfc90dea8f949aee5505c9e94fa6b6 | [
"Python"
] | 6 | Python | freitit/teenplus | fb3323aad90de349600ec0b70bd7dee3ab189240 | a887c5b4ba7283926554ec5439004fce877c19e6 |
refs/heads/master | <file_sep><?php
require "connection.php";
header('Content-type: application/json');
$id=$_POST['id'];
$name = $_POST['name'];
$id_user = $_POST['id_user'];
$query1="SELECT * from taikhoan where id_user ='".$id_user."' and possion='1'";
$result1 = mysqli_query($connect,$query1);
if(mysqli_num_rows($result1)==1){
$query = "UPDATE `khoa` SET `name`='".$name."',`id_user` = '".$id_user."' WHERE `id_department`= '".$id."'";
$result = mysqli_query($connect,$query);
if($result){
$data = [ 'status' => '1', 'message' => 'Update khoa thành công!!!' ];
}else{
$data = [ 'status' => '2', 'message' => 'update khoa không thành công!!' ];
}
}else{
$data = [ 'status' => '2', 'message' => 'Mã giảng viên không tồn tại!!' ];
}
echo json_encode($data);
?><file_sep><?php
require "connection.php";
class User{
function User($id_department,$name,$id_user){
$this->id_department=$id_department;
$this->name=$name;
$this->id_user=$id_user;
}
}
$mang =array();
$query="select * from khoa";
$result = mysqli_query($connect,$query);
if($result){
while($row = mysqli_fetch_assoc($result)){
array_push($mang, new User($row['id_department'],$row['name'],$row['id_user']));
}
if(count($mang)>0){
echo json_encode($mang);
}else{
echo "error";
}
}else{
echo "null";
}
?><file_sep><?php
require "connection.php";
header('Content-type: application/json');
$name = $_POST['name'];
$id = $_POST['id'];
$mang =array();
$query1="SELECT * from khoa where id_department ='".$id."'";
$result1 = mysqli_query($connect,$query1);
if(mysqli_num_rows($result1)==1){
$query="INSERT INTO `nghanh`(`name`,`id_department`) VALUES ('".$name."','".$id."')";
$result = mysqli_query($connect,$query);
if($result){
$data = [ 'status' => '1', 'message' => 'Thêm nghành thành công!!!' ];
}else{
$data = [ 'status' => '2', 'message' => 'Thêm nghành không thành công!!' ];
}
}else{
$data = [ 'status' => '2', 'message' => 'Mã khoa không tồn tại!!' ];
}
echo json_encode( $data );
?><file_sep><?php
$host = "localhost";
$user = "root";
$password = "";
$database = "quanlisvver1";
// Lệnh kết nối CSDL
$connect = mysqli_connect($host, $user, $password, $database);
mysqli_set_charset($connect, "utf8"); // Lấy về dữ liệu Unicode
$isOK = false;
// Kiểm tra kết nối
if (mysqli_connect_errno()) {
echo "Lỗi kết nối: " . mysqli_connect_error();
} else {
//echo "Kết nối thành công!";
$isOK = true;
}
?><file_sep><?php
require "connection.php";
header('Content-type: application/json');
$id = $_POST['id_user'];
$id_weekday = $_POST['id_weekday'];
$position = $_POST['position'];
class Scheduler{
function Scheduler($name_subject,$id_module,$room,$name_weekday){
$this->name_subject=$name_subject;
$this->id_module=$id_module;
$this->room=$room;
$this->name_weekday = $name_weekday;
}
}
class Room{
function Room($name_room,$lesson){
$this->name_room=$name_room;
$this->lesson=$lesson;
}
}
class Lesson{
function Lesson($id_lesson){
$this->id_lesson=$id_lesson;
}
}
$mang =array();
if($position=="2"){
$query="SELECT hocphan.id_module,monhoc.name FROM `hocphan` inner join chitiethocphan on hocphan.id_module=chitiethocphan.id_module inner join monhoc on monhoc.id_subject=hocphan.id_subject WHERE chitiethocphan.id_user='".$id."'";
}else{
$query="SELECT hocphan.id_module,monhoc.name FROM `hocphan` inner join monhoc on monhoc.id_subject=hocphan.id_subject WHERE hocphan.id_user='".$id."'";
}
$result = mysqli_query($connect,$query);
if($result){
while($row = mysqli_fetch_assoc($result)){
$query1 = "select DISTINCT phonghoc.name,phonghoc.id_room from thoikhoabieu inner join phonghoc on phonghoc.id_room=thoikhoabieu.id_room WHERE thoikhoabieu.id_module='".$row['id_module']."' and thoikhoabieu.id_weekday='".$id_weekday."'";
$result1 = mysqli_query($connect,$query1);
$mang2 = array();
while ($row1 = mysqli_fetch_array($result1)) {
$query2 = "select tiethoc.id_lesson from tiethoc inner join thoikhoabieu on tiethoc.id_lesson=thoikhoabieu.id_lesson WHERE thoikhoabieu.id_module='".$row['id_module']."' and thoikhoabieu.id_room='".$row1['id_room']."'";
$result2 = mysqli_query($connect,$query2);
$mang3 = array();
while ($row2 = mysqli_fetch_assoc($result2)) {
array_push($mang3, new Lesson($row2['id_lesson']));
}
if(count($mang3)>0){
array_push($mang2, new Room($row1['name'],$mang3));
}
}
if(count($mang2)>0){
$query3 = "select name from thutrongtuan WHERE id_weekday='".$id_weekday."'";
$result3 = mysqli_query($connect,$query3);
$row3 = mysqli_fetch_assoc($result3);
array_push($mang, new Scheduler($row['name'],$row['id_module'],$mang2,$row3['name']));
}
}
if(count($mang)>0){
$data = [ 'status' => '1', 'data' =>$mang ];
}else{
$data = [ 'status' => '0', 'data' =>$mang ];
}
}else{
$data = [ 'status' => '2', 'data' =>$mang ];
}
echo json_encode($data);
?>
<file_sep><?php
require "connection.php";
header('Content-type: application/json');
$id=$_POST['id'];
$image=$_POST['image'];
$query = "DELETE FROM `taikhoan` WHERE `id_user` = '".$id."'";
$result = mysqli_query($connect,$query);
if($result){
unlink("images".$image);
$data = [ 'status' => '1', 'message' => 'delete thành công!!!' ];
}else{
$data = [ 'status' => '0', 'message' => 'delete không thành công!!!' ];
}
echo json_encode($data);
?><file_sep><?php
require "connection.php";
header('Content-type: application/json');
$id = $_POST["id"];
class User{
function User($id,$name,$credits,$id_department){
$this->id=$id;
$this->name=$name;
$this->credits =$credits;
$this->id_department = $id_department;
}
}
$mang =array();
$query="select monhoc.id_subject,name,credits,id_department from khungdaotao inner join monhoc on khungdaotao.id_subject=monhoc.id_subject where id_department='".$id."'";
$result = mysqli_query($connect,$query);
if($result){
while($row = mysqli_fetch_assoc($result)){
array_push($mang, new User($row['id_subject'],$row['name'],$row['credits'],$row['id_department']));
}
if(count($mang)>0){
$data = [ 'status' => '1', 'data' => $mang];
}else{
$data = [ 'status' => '0', 'message' => $mang];
}
}else{
echo "error";
}
echo json_encode($data);
?><file_sep><?php
require "connection.php";
$file_path = "images/";//đường dẫn lưu ảnh
$file_path = $file_path.basename($_FILES['upload_image']['name']);
header('Content-type: application/json');
if(move_uploaded_file($_FILES['upload_image']['tmp_name'],$file_path)){//$_FILES là đường dẫn file ở client.$file_path đường dẫn file bạn muốn lưu file upload
//upload thành công thì sẽ thực hiện update dữ liệu lên server.
$data = [ 'status' => '1', 'url' => $_FILES['upload_image']['name'] ];
}else{
$data = [ 'status' => '0', 'url' => "lỗi" ];
}
echo json_encode($data);
?><file_sep><?php
require "connection.php";
header('Content-type: application/json');
class Schedule{
function Schedule($id_lesson,$id_room,$id_weekday){
$this->id_lesson=$id_lesson;
$this->id_room=$id_room;
$this->id_weekday=$id_weekday;
}
}
$mang = array();
$id_lesson = $_POST['id_lesson'];
$id_room = $_POST['id_room'];
$id_weekday = $_POST['id_weekday'];
$query = "SELECT * FROM `thoikhoabieu` where `id_lesson`='".$id_lesson."' and `id_room`='".$id_room."' and `id_weekday`='".$id_weekday."'";
$result = mysqli_query($connect,$query);
if($result){
while($row = mysqli_fetch_assoc($result)){
array_push($mang, new Schedule($row['id_lesson'],$row['id_room'],$row['id_weekday']));
$id_lesson = $row['id_lesson'];
$id_room = $row['id_room'];
$id_weekday = $row['id_weekday'];
}
if(count($mang)>0){
$data = [ 'status' => '2', 'schedule' => new Schedule($id_lesson,$id_room,$id_weekday)];
}else{
$data = [ 'status' => '1', 'schedule' => new Schedule($id_lesson,$id_room,$id_weekday) ];
}
}else{
$data = [ 'status' => '3', 'schedule' => null];
}
echo json_encode($data);
?><file_sep><?php
require "connection.php";
header('Content-type: application/json');
$id = $_POST['id_module'];
$query = "UPDATE `hocphan` SET `status`= 1 WHERE id_module='".$id."'";
$result = mysqli_query($connect,$query);
if($result){
$data = [ 'status' => '1', 'message' => 'Kết thúc đăng kí học phần thành công!!!' ];
}else{
$data = [ 'status' => '2', 'message' => 'Kết thúc đăng kí học phần không thành công!!' ];
}
echo json_encode($data);
?><file_sep><?php
require "connection.php";
header('Content-type: application/json');
class Schedule{
function Schedule($id_lesson,$name_lesson,$id_room,$name_room,$id_weekday,$name_weekday,$time_start,$time_end,$id_module){
$this->id_lesson=$id_lesson;
$this->name_lesson=$name_lesson;
$this->id_room=$id_room;
$this->name_room=$name_room;
$this->id_weekday = $id_weekday;
$this->name_weekday = $name_weekday;
$this->time_start=$time_start;
$this->time_end = $time_end;
$this->id_module =$id_module;
}
}
$id_module = $_POST['id_module'];
$id_lesson = $_POST['id_lesson'];
$id_room = $_POST['id_room'];
$id_weekday = $_POST['id_weekday'];
$query = "INSERT INTO `thoikhoabieu`(`id_lesson`, `id_room`, `id_weekday`, `id_module`) VALUES ('".$id_lesson."','".$id_room."','".$id_weekday."','".$id_module."')";
$result = mysqli_query($connect,$query);
if($result){
$query ="SELECT `name` FROM `thutrongtuan` WHERE `id_weekday` = '".$id_weekday."'";
$result = mysqli_query($connect,$query);
if($result){
$row = mysqli_fetch_assoc($result);
$name_weekday = $row['name'];
}
$query ="SELECT `name` FROM `phonghoc` WHERE `id_room` = '".$id_room."'";
$result = mysqli_query($connect,$query);
if($result){
$row = mysqli_fetch_assoc($result);
$name_room = $row['name'];
}
$query ="SELECT `name`, `time_start`, `time_end` FROM `tiethoc` WHERE `id_lesson` = '".$id_lesson."'";
$result = mysqli_query($connect,$query);
if($result){
$row = mysqli_fetch_assoc($result);
$name_lesson = $row['name'];
$time_start = $row['time_start'];
$time_end= $row['time_end'];
}
$data = [ 'status' => '1', 'schedule' => new Schedule($id_lesson,$name_lesson,$id_room,$name_room,$id_weekday,$name_weekday,$time_start,$time_end,$id_module) ];
}else{
$data = [ 'status' => '2', 'schedule' => null ]; //new Schedule(null,null,null,null,null,null,null,null,null)
}
echo json_encode($data);
?><file_sep><?php
require "connection.php";
class User{
function User($id,$password,$name,$id_depart,$name_depart,$id_class,$name_class,$sex,$phone,$position,$nationality,$wards,$district,$city,$image,$id_card,$date_card,$address_card,$status){
$this->id=$id;
$this->password=$<PASSWORD>;
$this->name=$name;
$this->id_depart=$id_depart;
$this->id_class = $id_class;
$this->position = $position;
$this->phone=$phone;
$this->sex = $sex;
$this->nationality =$nationality;
$this->wards=$wards;
$this->district=$district;
$this->city=$city;
$this->image = $image;
$this->id_card = $id_card;
$this->date_card = $date_card;
$this->address_card=$address_card;
$this->status =$status;
$this->name_depart = $name_depart;
$this->name_class = $name_class;
}
}
header('Content-type: application/json');
$user = $_POST["user"];
$pass = $_POST["pass"];
$mang = array();
$user1 = null;
$sql = "SELECT * FROM taikhoan where id_user = '" . $user . "' AND password ='" . $pass . "'";
$result = mysqli_query($connect, $sql);
if($result){
while($row = mysqli_fetch_assoc($result)){
$sql1 = "SELECT name FROM khoa where id_department = '".$row['id_department']."'";
$result1 = mysqli_query($connect, $sql1);
$row1 = mysqli_fetch_assoc($result1);
$sql2 = "SELECT name FROM lop where id_class = '".$row['id_class']."'";
$result2 = mysqli_query($connect, $sql2);
$row2 = mysqli_fetch_assoc($result2);
if($row2==null){
$user1 = new User($row['id_user'],$row['password'],$row['name'],$row['id_department'],$row1['name'],$row['id_class'],null,$row['sex'],$row['phone'],$row['possion'],$row['nationality'],$row['wards'],$row['district'],$row['city'],$row['image'],$row['id_card'],$row['date_card'],$row['address_card'],$row['status']);
}else{
$user1 = new User($row['id_user'],$row['password'],$row['name'],$row['id_department'],$row1['name'],$row['id_class'],$row2['name'],$row['sex'],$row['phone'],$row['possion'],$row['nationality'],$row['wards'],$row['district'],$row['city'],$row['image'],$row['id_card'],$row['date_card'],$row['address_card'],$row['status']);
}
array_push($mang, $user1);
}
if(count($mang)>0){
$data = ['status' => '1','data' => $user1];
}else{
$data = ['status' => '0','data' => $user1];
}
}
echo json_encode($data);
?><file_sep><?php
require "connection.php";
class User{
function User($id,$name,$time_start,$time_end){
$this->id=$id;
$this->name=$name;
$this->time_start =$time_start;
$this->time_end = $time_end;
}
}
$mang =array();
$query="select * from tiethoc";
$result = mysqli_query($connect,$query);
if($result){
while($row = mysqli_fetch_assoc($result)){
array_push($mang, new User($row['id_lesson'],$row['name'],$row['time_start'],$row['time_end']));
}
if(count($mang)>0){
$data = [ 'status' => '1', 'lesson' => $mang ];
}else{
$data = [ 'status' => '2', 'lesson' => $mang ];
}
}else{
$data = [ 'status' => '2', 'lesson' => $mang ];
}
echo json_encode($data);
?><file_sep><?php
require "connection.php";
header('Content-type: application/json');
$position = $_POST['position'];
$id_module = $_POST['id_module'];
$id_user = $_POST['id_user'];
$today = date("d/m/Y");
$queryM = "SELECT * FROM `thoikhoabieu` WHERE id_module='".$id_module."'";
$resultM = mysqli_query($connect,$queryM);
if($rowM = mysqli_fetch_assoc($resultM)){
if($position=='2'){
$queryC = "select * from chitiethocphan WHERE id_user= '".$id_user."' and id_module = '".$id_module."'";
$resultC = mysqli_query($connect,$queryC);
if(mysqli_num_rows($resultC)==0){
$query = "select * from chitiethocphan inner join thoikhoabieu on chitiethocphan.id_module=thoikhoabieu.id_module WHERE id_user='".$id_user."' and id_lesson = '".$rowM['id_lesson']."' and id_weekday = '".$rowM['id_weekday']."' and id_room = '".$rowM['id_room']."'";
$result = mysqli_query($connect,$query);
if(mysqli_num_rows($result)==0){
$query1 ="SELECT quantity_registed,quantity FROM `hocphan` WHERE id_module = '".$id_module."'";
$result1 = mysqli_query($connect,$query1);
$row1 = mysqli_fetch_assoc($result1);
$count = $row1['quantity_registed'] + 1;
$quantity = $row1['quantity'];
if($count>$quantity){
$data = [ 'status' => '3', 'message' => 'Học phần này đã đầy số lượng' ];
}else{
$query2 = "INSERT INTO `chitiethocphan`(`id_user`, `id_module`, `date_register`) VALUES ('".$id_user."','".$id_module."','".$today."')";
$result2 = mysqli_query($connect,$query2);
$query3 = "UPDATE `hocphan` SET quantity_registed = '".$count."' WHERE id_module = '".$id_module."'";
$result3 = mysqli_query($connect,$query3);
if($result3 && $result2){
$data = [ 'status' => '1', 'message' => "Đăng ký học phần thành công!!!"];
}else{
$data = [ 'status' => '0', 'message' => "Đăng ký học phần không thành công!!!"];
}
}
}else{
$data = [ 'status' => '0', 'message' => 'Trùng thời khóa biểu!!!' ];
}
}else{
$data = [ 'status' => '0', 'message' => 'Bạn đã đăng ký học phần này!!!' ];
}
}else{
$queryC = "select * from hocphan WHERE id_user= '".$id_user."' and id_module = '".$id_module."'";
$resultC = mysqli_query($connect,$queryC);
if(mysqli_num_rows($resultC)==0){
$query = "select * from hocphan WHERE id_user is NULL and id_module = '".$id_module."'";
$result = mysqli_query($connect,$query);
if(mysqli_num_rows($result)!=0){
$query = "select * from hocphan inner join thoikhoabieu on hocphan.id_module=thoikhoabieu.id_module WHERE id_user='".$id_user."' and id_lesson = '".$rowM['id_lesson']."' and id_weekday = '".$rowM['id_weekday']."' and id_room = '".$rowM['id_room']."'";
$result = mysqli_query($connect,$query);
if(mysqli_num_rows($result)==0){
$query1 = "UPDATE `hocphan` SET `id_user`='".$id_user."' WHERE id_module = '".$id_module."'";
$result1 = mysqli_query($connect,$query1);
if ($result1) {
$data = [ 'status' => '1', 'message' => "Đăng ký giảng dạy thành công!!!"];
}else{
$data = [ 'status' => '1', 'message' => 'Đăng ký giảng dạy không thành công!!!' ];
}
}else{
$data = [ 'status' => '1', 'message' => 'Trùng lịch giảng dạy!!!' ];
}
}else{
$data = [ 'status' => '0', 'message' => 'Học phần giảng dạy này đã được đã đăng ký!!!' ];
}
}else{
$data = [ 'status' => '0', 'message' => 'Bạn đã đăng kí học phần giảng dạy này !!!' ];
}
}
}
echo json_encode($data);
?><file_sep><?php
require "connection.php";
class User{
function User($id,$password,$name,$id_depart,$id_class,$sex,$phone,$possion,$nationality,$wards,$district,$city,$image,$id_card,$date_card,$address_card,$status){
$this->id=$id;
$this->password=$<PASSWORD>;
$this->name=$name;
$this->id_depart=$id_depart;
$this->id_class = $id_class;
$this->possion = $possion;
$this->phone=$phone;
$this->sex = $sex;
$this->nationality =$nationality;
$this->wards=$wards;
$this->district=$district;
$this->city=$city;
$this->image = $image;
$this->id_card = $id_card;
$this->date_card = $date_card;
$this->address_card=$address_card;
$this->status =$status;
}
}
$mang =array();
$query="select * from taikhoan where possion= '0'";
$result = mysqli_query($connect,$query);
if($result){
while($row = mysqli_fetch_assoc($result)){
array_push($mang, new User($row['id_user'],$row['password'],$row['name'],$row['id_department'],$row['id_class'],$row['sex'],$row['phone'],$row['possion'],$row['nationality'],$row['wards'],$row['district'],$row['city'],$row['image'],$row['id_card'],$row['date_card'],$row['address_card'],$row['status']));
}
if(count($mang)>0){
echo json_encode($mang);
}else{
echo "error";
}
}else{
echo "null";
}
?><file_sep><?php
require "connection.php";
header('Content-type: application/json');
$id_subject = $_POST['id_subject'];
$date_start = $_POST['date_start'];
$date_end = $_POST['date_end'];
$quantily = $_POST['quantily'];
$query = "INSERT INTO `hocphan`(`id_subject`, `id_user`, `date_register`, `date_start`, `date_end`, `quantity`) VALUES ('".$id_subject."',null,'".date("Y/m/d")."','".$date_start."','".$date_end."','".$quantily."')";
$result = mysqli_query($connect,$query);
if ($result) {
$last_id = mysqli_insert_id($connect);
$data = [ 'status' => '1', 'id_module' => $last_id];
}else{
$data = [ 'status' => '2', 'message' => 'Tạo học phần không thành công!!' ];
}
echo json_encode($data);
?><file_sep><?php
require "connection.php";
header('Content-type: application/json');
class User{
function User($id,$password,$name,$id_depart,$id_class,$sex,$phone,$position,$nationality,$wards,$district,$city,$image,$id_card,$date_card,$address_card,$status){
$this->id=$id;
$this->password=$<PASSWORD>;
$this->name=$name;
$this->id_depart=$id_depart;
$this->id_class = $id_class;
$this->position = $position;
$this->phone=$phone;
$this->sex = $sex;
$this->nationality =$nationality;
$this->wards=$wards;
$this->district=$district;
$this->city=$city;
$this->image = $image;
$this->id_card = $id_card;
$this->date_card = $date_card;
$this->address_card=$address_card;
$this->status =$status;
}
}
$id = $_POST["id"];
$password = $_REQUEST["password"];
$name = $_REQUEST["name"];
$id_depart = $_REQUEST["id_depart"];
$id_class = $_REQUEST["id_class"];
$position = $_REQUEST["position"];
$phone = $_REQUEST["phone"];
$nationality = $_REQUEST["nationality"];
$wards = $_REQUEST["wards"];
$district = $_REQUEST["district"];
$city = $_REQUEST["city"];
$id_card = $_REQUEST["id_card"];
$date_card = $_REQUEST["date_card"];
$address_card = $_REQUEST["address_card"];
$status = $_REQUEST["status"];
$sex = $_REQUEST["sex"];
$image = $_REQUEST["image"];
// $id = "122";
// // $password = "<PASSWORD>";
// // $name = "1212";
// // $id_depart = "K1";
// // $id_class = "L2_CNTT2";
// // $position = "1212";
// // $phone = "1212";
// // $nationality = "1212";
// // $wards = "1212";
// // $district = "1212";
// // $city = "1212";
// // $id_card = "1212";
// // $date_card = "1212";
// // $address_card = "1212";
// // $status = "1212";
// // $sex = "1212";
// // $image = "1212";
// $mang = array();
if($id_class!=null){
$query = "UPDATE `taikhoan` SET `id_user`='".$id."',`password`='".<PASSWORD>."',`name`='".$name."',`id_department`='".$id_depart."',`id_class`='".$id_class."',`sex`='".$sex."',`phone`='".$phone."',`possion`='".$position."',`nationality`='".$nationality."',`wards`='".$wards."',`district`='".$district."',`city`='".$city."',`image`='".$image."',`id_card`='".$id_card."',`date_card`='".$date_card."',`address_card`='".$address_card."',`status`='".$status."' WHERE `id_user` = '".$id."'";
}else{
$query = "UPDATE `taikhoan` SET `id_user`='".$id."',`password`='".$<PASSWORD>."',`name`='".$name."',`id_department`='".$id_depart."',`id_class`=null,`sex`='".$sex."',`phone`='".$phone."',`possion`='".$position."',`nationality`='".$nationality."',`wards`='".$wards."',`district`='".$district."',`city`='".$city."',`image`='".$image."',`id_card`='".$id_card."',`date_card`='".$date_card."',`address_card`='".$address_card."',`status`='".$status."' WHERE `id_user` = '".$id."'";
}
$result = mysqli_query($connect,$query);
if($result){
$data = [ 'status' => '1', 'message' => 'update thành công!!!' ];
}else{
$data = [ 'status' => '0', 'message' => 'update không thành công!!!!' ];
}
echo json_encode($data);
?><file_sep><?php
require "connection.php";
header('Content-type: application/json');
$id_department = $_POST['id'];
$name = $_POST['name'];
$credits = $_POST['credits'];
$mang =array();
$query="INSERT INTO `monhoc`(`name`, `credits`) VALUES ('".$name."','".$credits."')";
$result = mysqli_query($connect,$query);
if($result){
$last_id = mysqli_insert_id($connect);
$query="INSERT INTO `khungdaotao`(`id_department`, `id_subject`) VALUES ('".$id_department."','".$last_id."')";
$result = mysqli_query($connect,$query);
if($result){
$data = [ 'status' => '1', 'message' => 'Thêm môn học thành công!!!' ];
}else{
$data = [ 'status' => '2', 'message' => 'Thêm môn học không thành công!!' ];
}
}else{
$data = [ 'status' => '2', 'message' => 'Thêm môn học không thành công!!' ];
}
echo json_encode( $data );
?><file_sep><?php
require "connection.php";
header('Content-type: application/json');
$status = $_POST['status'];
$key = $_POST['key'];
class Module{
function Module($id_module,$id_subject,$name_subject,$id_user,$date_register,$date_start,$date_end,$quantity,$quantity_registed,$status){
$this->id_module=$id_module;
$this->id_subject=$id_subject;
$this->name_subject=$name_subject;
$this->id_user =$id_user;
$this->date_register=$date_register;
$this->date_start=$date_start;
$this->date_end =$date_end;
$this->quantity=$quantity;
$this->quantity_registed=$quantity_registed;
$this->status =$status;
}
}
$mang=array();
$query = "SELECT * FROM `hocphan` inner join `monhoc` on hocphan.id_subject = monhoc.id_subject WHERE status = '".$status."' AND (id_module LIKE '%".$key."%' or name LIKE '%".$key."%')";
$result = mysqli_query($connect,$query);
if($result){
while($row = mysqli_fetch_assoc($result)){
array_push($mang, new Module($row['id_module'],$row['id_subject'],$row['name'],$row['id_user'],$row['date_register'],$row['date_start'],$row['date_end'],$row['quantity'],$row['quantity_registed'],$row['status']));
}
if(count($mang)>0){
$data = [ 'status' => '1', 'modules' => $mang ];
}else{
$data = [ 'status' => '2', 'modules' => $mang ];
}
}else{
$data = [ 'status' => '3', 'modules' => $mang ];
}
echo json_encode($data);
?><file_sep><?php
require "connection.php";
header('Content-type: application/json');
$position = $_POST['position'];
$id_module = $_POST['id_module'];
$id_user = $_POST['id_user'];
if($position=='1'){
$query = "UPDATE `hocphan` SET `id_user`= null WHERE id_module = '".$id_module."'";
$result = mysqli_query($connect,$query);
if ($result) {
$data = [ 'status' => '1', 'message' => "Hủy giảng dạy thành công!!!"];
}else{
$data = [ 'status' => '2', 'message' => 'Hủy giảng dạy không thành công!!!'];
}
}else{
$query = "DELETE FROM `chitiethocphan` WHERE id_user = '".$id_user."' and id_module = '".$id_module."'";
$result = mysqli_query($connect,$query);
if ($result) {
$query1 ="SELECT quantity_registed,quantity FROM `hocphan` WHERE id_module = '".$id_module."'";
$result1 = mysqli_query($connect,$query1);
$row1 = mysqli_fetch_assoc($result1);
$count = $row1['quantity_registed'] - 1;
if($count>-1){
$query = "UPDATE `hocphan` SET quantity_registed = '".$count."' WHERE id_module = '".$id_module."'";
$result1 = mysqli_query($connect,$query);
if($result1){
$data = [ 'status' => '1', 'message' => "Hủy học phần thành công!!!"];
}else{
$data = [ 'status' => '2', 'message' => "Hủy học phần không thành công!!!"];
}
}else{
$data = [ 'status' => '2', 'message' => "Hủy học phần không thành công!!!"];
}
}else{
$data = [ 'status' => '2', 'message' => "Hủy học phần không thành công!!!"];
}
}
echo json_encode($data);
?><file_sep><?php
require "connection.php";
header('Content-type: application/json');
class Room{
function Room($id,$name){
$this->id=$id;
$this->name=$name;
}
}
$mang =array();
$query = "select * from phonghoc";
$result = mysqli_query($connect,$query);
if($result){
while($row = mysqli_fetch_assoc($result)){
array_push($mang, new Room($row['id_room'],$row['name']));
}
if(count($mang)>0){
$data = [ 'status' => '1', 'room' => $mang ];
}else{
$data = [ 'status' => '2', 'room' => $mang ];
}
}else{
$data = [ 'status' => '2', 'room' => $mang ];
}
echo json_encode($data)
;
?><file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.1
-- https://www.phpmyadmin.net/
--
-- Máy chủ: 127.0.0.1
-- Thời gian đã tạo: Th2 21, 2020 lúc 11:47 AM
-- Phiên bản máy phục vụ: 10.4.11-MariaDB
-- Phiên bản PHP: 7.4.2
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Cơ sở dữ liệu: `qlsvver2`
--
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `chitiethocphan`
--
CREATE TABLE `chitiethocphan` (
`id_user` varchar(32) NOT NULL,
`id_module` int(32) NOT NULL,
`date_register` varchar(32) DEFAULT NULL,
`score_regular_1` float DEFAULT NULL,
`score_regular_2` float DEFAULT NULL,
`score_regular_3` float DEFAULT NULL,
`score_mid_1` float DEFAULT NULL,
`score_mid_2` float DEFAULT NULL,
`quantity_leave` int(2) DEFAULT 0,
`status` int(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
--
-- Đang đổ dữ liệu cho bảng `chitiethocphan`
--
INSERT INTO `chitiethocphan` (`id_user`, `id_module`, `date_register`, `score_regular_1`, `score_regular_2`, `score_regular_3`, `score_mid_1`, `score_mid_2`, `quantity_leave`, `status`) VALUES
('1141460161', 4, '2020-02-18', 9, 9, NULL, 10, NULL, 12, 0);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `hocphan`
--
CREATE TABLE `hocphan` (
`id_module` int(32) NOT NULL,
`id_subject` int(32) NOT NULL,
`id_user` varchar(32) DEFAULT NULL,
`date_register` varchar(32) DEFAULT NULL,
`date_start` varchar(32) DEFAULT NULL,
`date_end` varchar(32) DEFAULT NULL,
`quantity` int(2) NOT NULL,
`quantity_registed` int(2) DEFAULT 0,
`status` int(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
--
-- Đang đổ dữ liệu cho bảng `hocphan`
--
INSERT INTO `hocphan` (`id_module`, `id_subject`, `id_user`, `date_register`, `date_start`, `date_end`, `quantity`, `quantity_registed`, `status`) VALUES
(4, 1, NULL, '2020-02-18 21:53:05', '2020-02-18', '2020-02-18', 70, 0, 0),
(5, 2, NULL, '2020-02-18 21:53:05', '2020-02-18', '2020-02-18', 70, 0, 0),
(11, 1, NULL, '2020/02/20', '1/1/2020', '2/2/2020', 75, 0, 0),
(12, 1, NULL, '2020/02/21', '1/1/2020', '2/2/2020', 75, 0, 0),
(13, 2, NULL, '2020/02/21', '2020-1-21', '2020-1-22', 75, 0, 0),
(14, 2, NULL, '2020/02/21', '2020-2-21', '2020-2-29', 75, 0, 0);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `khoa`
--
CREATE TABLE `khoa` (
`id_department` int(32) NOT NULL ,
`name` varchar(256) NOT NULL,
`id_user` varchar(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
--
-- Đang đổ dữ liệu cho bảng `khoa`
--
INSERT INTO `khoa` (`id_department`, `name`, `id_user`) VALUES
(1, 'Công nghệ thông tin', '1141460162');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `khungdaotao`
--
CREATE TABLE `khungdaotao` (
`id_department` int(32) NOT NULL,
`id_subject` int(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
--
-- Đang đổ dữ liệu cho bảng `khungdaotao`
--
INSERT INTO `khungdaotao` (`id_department`, `id_subject`) VALUES
(1, 1),
(1, 2);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `lop`
--
CREATE TABLE `lop` (
`id_class` int(32) NOT NULL,
`name` varchar(256) NOT NULL,
`id_specialized` int(32) NOT NULL,
`id_user` varchar(32) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
--
-- Đang đổ dữ liệu cho bảng `lop`
--
INSERT INTO `lop` (`id_class`, `name`, `id_specialized`, `id_user`) VALUES
(1, 'Công nghệ thông tin 1', 1, NULL),
(2, 'Hệ thống thông tin 1', 2, NULL);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `monhoc`
--
CREATE TABLE `monhoc` (
`id_subject` int(32) NOT NULL,
`name` varchar(256) NOT NULL,
`credits` int(2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
--
-- Đang đổ dữ liệu cho bảng `monhoc`
--
INSERT INTO `monhoc` (`id_subject`, `name`, `credits`) VALUES
(1, 'Lập trình C#', 4),
(2, 'Lập trình C++', 3),
(4, 'toán cao cấp', 4);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `namhoc`
--
CREATE TABLE `namhoc` (
`id_term` int(16) NOT NULL,
`name` varchar(128) NOT NULL,
`date_start` date NOT NULL,
`date_end` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
--
-- Đang đổ dữ liệu cho bảng `namhoc`
--
INSERT INTO `namhoc` (`id_term`, `name`, `date_start`, `date_end`) VALUES
(1, 'Năm học 2020-2021', '0000-00-00', '0000-00-00');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `nghanh`
--
CREATE TABLE `nghanh` (
`id_specialized` int(32) NOT NULL,
`name` varchar(256) NOT NULL,
`id_department` int(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
--
-- Đang đổ dữ liệu cho bảng `nghanh`
--
INSERT INTO `nghanh` (`id_specialized`, `name`, `id_department`) VALUES
(1, 'Công nghệ thôn tin', 1),
(2, 'Hệ thống thông tin', 1);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `phonghoc`
--
CREATE TABLE `phonghoc` (
`id_room` int(2) NOT NULL,
`name` varchar(128) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
--
-- Đang đổ dữ liệu cho bảng `phonghoc`
--
INSERT INTO `phonghoc` (`id_room`, `name`) VALUES
(1, 'Phòng 1'),
(2, 'Phòng 2');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `taikhoan`
--
CREATE TABLE `taikhoan` (
`id_user` varchar(32) NOT NULL,
`password` varchar(32) NOT NULL,
`name` varchar(256) NOT NULL,
`id_department` int(32) NOT NULL,
`id_class` int(32) DEFAULT NULL,
`sex` varchar(1) NOT NULL DEFAULT '1',
`phone` varchar(11) DEFAULT NULL,
`possion` varchar(1) NOT NULL DEFAULT '0',
`nationality` varchar(128) DEFAULT NULL,
`wards` varchar(128) DEFAULT NULL,
`district` varchar(128) DEFAULT NULL,
`city` varchar(128) DEFAULT NULL,
`image` varchar(1028) DEFAULT NULL,
`id_card` varchar(13) DEFAULT NULL,
`date_card` varchar(20) DEFAULT NULL,
`address_card` varchar(256) DEFAULT NULL,
`status` int(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
--
-- Đang đổ dữ liệu cho bảng `taikhoan`
--
INSERT INTO `taikhoan` (`id_user`, `password`, `name`, `id_department`, `id_class`, `sex`, `phone`, `possion`, `nationality`, `wards`, `district`, `city`, `image`, `id_card`, `date_card`, `address_card`, `status`) VALUES
('1', '1', '1', 1, 1, '1', '123', '0', '', '', '22222222', '', '', '123', '', '', 0),
('11', '11', '11', 1, NULL, '1', '', '1', 'Việt Nam', 'Phường Tân Định', 'Quận 1', 'Hồ Chí Minh', '15822717466211582271848263.jpg', '', '', '', 0),
('1141460160', '123456', 'Phạm Văn A', 1, NULL, '1', NULL, '0', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0),
('1141460161', '123456', 'Phạm Văn B', 1, 2, '1', '1234', '2', 'Việt Nam', 'Thượng Cát', 'Bắc Từ Liêm', 'Hà Nội', 'IMG_20200219_1356321582107959586.jpg', '123', '', '', 0),
('1141460162', '123456', '<NAME>', 1, NULL, '1', '', '1', 'Việt Nam', '<NAME>', 'Quận 1', '<NAME>', '15820983546931582098378792.jpg', '1', '', '', 0);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `thoikhoabieu`
--
CREATE TABLE `thoikhoabieu` (
`id_lesson` int(2) NOT NULL,
`id_room` int(2) NOT NULL,
`id_weekday` int(1) NOT NULL,
`id_module` int(32) NOT NULL,
`status` int(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
--
-- Đang đổ dữ liệu cho bảng `thoikhoabieu`
--
INSERT INTO `thoikhoabieu` (`id_lesson`, `id_room`, `id_weekday`, `id_module`, `status`) VALUES
(1, 1, 1, 4, 0),
(1, 1, 3, 14, 0),
(1, 1, 5, 14, 0),
(1, 1, 6, 14, 0),
(2, 1, 1, 11, 0);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `thutrongtuan`
--
CREATE TABLE `thutrongtuan` (
`id_weekday` int(1) NOT NULL,
`name` varchar(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
--
-- Đang đổ dữ liệu cho bảng `thutrongtuan`
--
INSERT INTO `thutrongtuan` (`id_weekday`, `name`) VALUES
(1, '<NAME>'),
(2, 'Thứ ba'),
(3, 'Thứ Tư'),
(4, 'Thứ Năm'),
(5, 'Thứ Sáu'),
(6, 'Thứ Bảy'),
(7, 'Chủ Nhật');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `tiethoc`
--
CREATE TABLE `tiethoc` (
`id_lesson` int(2) NOT NULL,
`name` varchar(128) NOT NULL,
`time_start` varchar(64) NOT NULL,
`time_end` varchar(64) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
--
-- Đang đổ dữ liệu cho bảng `tiethoc`
--
INSERT INTO `tiethoc` (`id_lesson`, `name`, `time_start`, `time_end`) VALUES
(1, 'Tiết 1', '07:00:00', '07:45:00'),
(2, 'Tiết 2', '08:00:00', '08:45:00');
--
-- Chỉ mục cho các bảng đã đổ
--
--
-- Chỉ mục cho bảng `chitiethocphan`
--
ALTER TABLE `chitiethocphan`
ADD PRIMARY KEY (`id_user`,`id_module`) USING BTREE,
ADD KEY `FK_KQ1` (`id_module`);
--
-- Chỉ mục cho bảng `hocphan`
--
ALTER TABLE `hocphan`
ADD PRIMARY KEY (`id_module`),
ADD KEY `FK_HP2` (`id_subject`),
ADD KEY `FK_HP4` (`id_user`);
--
-- Chỉ mục cho bảng `khoa`
--
ALTER TABLE `khoa`
ADD PRIMARY KEY (`id_department`),
ADD KEY `FK_K1` (`id_user`);
--
-- Chỉ mục cho bảng `khungdaotao`
--
ALTER TABLE `khungdaotao`
ADD PRIMARY KEY (`id_department`,`id_subject`) USING BTREE,
ADD KEY `FK2K` (`id_subject`);
--
-- Chỉ mục cho bảng `lop`
--
ALTER TABLE `lop`
ADD PRIMARY KEY (`id_class`),
ADD KEY `FK_N1` (`id_specialized`),
ADD KEY `FK_N2` (`id_user`);
--
-- Chỉ mục cho bảng `monhoc`
--
ALTER TABLE `monhoc`
ADD PRIMARY KEY (`id_subject`);
--
-- Chỉ mục cho bảng `namhoc`
--
ALTER TABLE `namhoc`
ADD PRIMARY KEY (`id_term`);
--
-- Chỉ mục cho bảng `nghanh`
--
ALTER TABLE `nghanh`
ADD PRIMARY KEY (`id_specialized`),
ADD KEY `FK` (`id_department`);
--
-- Chỉ mục cho bảng `phonghoc`
--
ALTER TABLE `phonghoc`
ADD PRIMARY KEY (`id_room`);
--
-- Chỉ mục cho bảng `taikhoan`
--
ALTER TABLE `taikhoan`
ADD PRIMARY KEY (`id_user`),
ADD KEY `FK_tk2` (`id_department`),
ADD KEY `FK_tk1` (`id_class`);
--
-- Chỉ mục cho bảng `thoikhoabieu`
--
ALTER TABLE `thoikhoabieu`
ADD PRIMARY KEY (`id_lesson`,`id_room`,`id_weekday`),
ADD KEY `FK3` (`id_weekday`),
ADD KEY `FK_TKB1` (`id_lesson`),
ADD KEY `FK_TKB2` (`id_room`),
ADD KEY `Fk_TKB3` (`id_module`);
--
-- Chỉ mục cho bảng `thutrongtuan`
--
ALTER TABLE `thutrongtuan`
ADD PRIMARY KEY (`id_weekday`);
--
-- Chỉ mục cho bảng `tiethoc`
--
ALTER TABLE `tiethoc`
ADD PRIMARY KEY (`id_lesson`);
--
-- AUTO_INCREMENT cho các bảng đã đổ
--
--
-- AUTO_INCREMENT cho bảng `hocphan`
--
ALTER TABLE `hocphan`
MODIFY `id_module` int(32) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15;
--
-- AUTO_INCREMENT cho bảng `lop`
--
ALTER TABLE `lop`
MODIFY `id_class` int(32) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
ALTER TABLE `khoa`
MODIFY `id_department` int(32) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=0;
--
-- AUTO_INCREMENT cho bảng `monhoc`
--
ALTER TABLE `monhoc`
MODIFY `id_subject` int(32) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT cho bảng `namhoc`
--
ALTER TABLE `namhoc`
MODIFY `id_term` int(16) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT cho bảng `nghanh`
--
ALTER TABLE `nghanh`
MODIFY `id_specialized` int(32) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT cho bảng `phonghoc`
--
ALTER TABLE `phonghoc`
MODIFY `id_room` int(2) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT cho bảng `thutrongtuan`
--
ALTER TABLE `thutrongtuan`
MODIFY `id_weekday` int(1) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT cho bảng `tiethoc`
--
ALTER TABLE `tiethoc`
MODIFY `id_lesson` int(2) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- Các ràng buộc cho các bảng đã đổ
--
--
-- Các ràng buộc cho bảng `chitiethocphan`
--
ALTER TABLE `chitiethocphan`
ADD CONSTRAINT `FK_KQ1` FOREIGN KEY (`id_module`) REFERENCES `hocphan` (`id_module`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_KQ2` FOREIGN KEY (`id_user`) REFERENCES `taikhoan` (`id_user`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Các ràng buộc cho bảng `hocphan`
--
ALTER TABLE `hocphan`
ADD CONSTRAINT `FK_HP2` FOREIGN KEY (`id_subject`) REFERENCES `monhoc` (`id_subject`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_HP4` FOREIGN KEY (`id_user`) REFERENCES `taikhoan` (`id_user`);
--
-- Các ràng buộc cho bảng `khoa`
--
ALTER TABLE `khoa`
ADD CONSTRAINT `FK_K1` FOREIGN KEY (`id_user`) REFERENCES `taikhoan` (`id_user`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Các ràng buộc cho bảng `khungdaotao`
--
ALTER TABLE `khungdaotao`
ADD CONSTRAINT `FK2K` FOREIGN KEY (`id_subject`) REFERENCES `monhoc` (`id_subject`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Các ràng buộc cho bảng `lop`
--
ALTER TABLE `lop`
ADD CONSTRAINT `FK_N1` FOREIGN KEY (`id_specialized`) REFERENCES `nghanh` (`id_specialized`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_N2` FOREIGN KEY (`id_user`) REFERENCES `taikhoan` (`id_user`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Các ràng buộc cho bảng `nghanh`
--
ALTER TABLE `nghanh`
ADD CONSTRAINT `FK` FOREIGN KEY (`id_department`) REFERENCES `khoa` (`id_department`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Các ràng buộc cho bảng `taikhoan`
--
ALTER TABLE `taikhoan`
ADD CONSTRAINT `FK_tk1` FOREIGN KEY (`id_class`) REFERENCES `lop` (`id_class`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_tk2` FOREIGN KEY (`id_department`) REFERENCES `khoa` (`id_department`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Các ràng buộc cho bảng `thoikhoabieu`
--
ALTER TABLE `thoikhoabieu`
ADD CONSTRAINT `FK_TKB1` FOREIGN KEY (`id_lesson`) REFERENCES `tiethoc` (`id_lesson`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `FK_TKB2` FOREIGN KEY (`id_room`) REFERENCES `phonghoc` (`id_room`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `FK_TKB4` FOREIGN KEY (`id_weekday`) REFERENCES `thutrongtuan` (`id_weekday`),
ADD CONSTRAINT `Fk_TKB3` FOREIGN KEY (`id_module`) REFERENCES `hocphan` (`id_module`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
require "connection.php";
header('Content-type: application/json');
$id_subject = $_POST['id'];
$query = "SELECT * FROM `hocphan` WHERE id_subject = '".$id_subject."'";
$result = mysqli_query($connect,$query);
if (mysqli_num_rows($result)==0) {
$query = "DELETE FROM `khungdaotao` WHERE id_subject = '".$id_subject."'";
$result = mysqli_query($connect,$query);
if($result){
$query = "DELETE FROM `monhoc` WHERE id_subject = '".$id_subject."'";
$result = mysqli_query($connect,$query);
if($result){
$data = [ 'status' => '1', 'message' => 'Xóa môn học thành công!!!' ];
}else{
$data = [ 'status' => '2', 'message' => 'Xóa môn học không thành công!!' ];
}
}else{
$data = [ 'status' => '2', 'message' => 'Xóa môn học không thành công!!' ];
}
}else{
$data = [ 'status' => '3', 'message' => 'Môn học này không thể xóa vì đã được đăng ký học phần!!' ];
}
echo json_encode($data);
?> | 9585909975ba385ed5fcfb8091b262436eb7fb7d | [
"SQL",
"PHP"
] | 23 | PHP | phamdat080598/csdl | d4c12dcb008b132de182b7b4d5d727570545b1bf | 52204cbda89e8dbbf6e0c970880cbe03f726751d |
refs/heads/main | <file_sep>import java.util.Scanner;
public class test {
static int problemOne(String s) {
int answer = 0;
System.out.println("enter word");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
char[] chars = str.toCharArray();
for (char c : chars) {
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
answer++;
break;
}
}
return answer;
}
}
<file_sep>public class PrintinImage {
}
| add2f2050804ae16d39fd4a4d1de60bbc371d6f0 | [
"Java"
] | 2 | Java | vlnareef-patelprogramming11/Areef-Patel-Programming-11 | 065da458ee9bf083112ca3214971bfbf3f3da91a | bbf486f92a3c7315c934077d023faee3422524c1 |
refs/heads/master | <repo_name>zeris/files<file_sep>/README.md
# files
Create json or csv files based on each other
<file_sep>/config/paths.js
let paths =
{
csv : "/var/csv/",
json : "C:/JSON/"
}
module.exports = paths; | 17899e98f6b58ac3bffab738d090a503b270afff | [
"Markdown",
"JavaScript"
] | 2 | Markdown | zeris/files | fca8541199c410c4aa5f71cb1aaec65c35331ed3 | bb9b985a36ee1db020623dd08a5752261ae5a243 |
refs/heads/master | <repo_name>tchaubal/GoogleNanodegree1_TourGuideApp<file_sep>/app/src/main/java/com/example/tanushreechaubal/pune_aconfluenceofeastandwest/PlaceToEatFragment.java
package com.example.tanushreechaubal.pune_aconfluenceofeastandwest;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link PlaceToEatFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link PlaceToEatFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class PlaceToEatFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public PlaceToEatFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment PlaceToEatFragment.
*/
// TODO: Rename and change types and number of parameters
public static PlaceToEatFragment newInstance(String param1, String param2) {
PlaceToEatFragment fragment = new PlaceToEatFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String vaishaliName = getResources().getString(R.string.restaurant_vaishali);
String vaishaliLocation = getResources().getString(R.string.restaurant_vaishali_location);
String vaishaliDescription = getResources().getString(R.string.restaurant_vaishali_description);
String bedekarName = getResources().getString(R.string.restaurant_bedekar);
String bedekarLocation = getResources().getString(R.string.restaurant_bedekar_location);
String bedekarDescription = getResources().getString(R.string.restaurant_bedekar_description);
String thePlaceName = getResources().getString(R.string.restaurant_thePlace);
String thePlaceLocation = getResources().getString(R.string.restaurant_thePlace_location);
String thePlaceDescription = getResources().getString(R.string.restaurant_thePlace_description);
String nisargaName = getResources().getString(R.string.restaurant_nisarga);
String nisargaLocation = getResources().getString(R.string.restaurant_nisarga_location);
String nisargaDescription = getResources().getString(R.string.restaurant_nisarga_description);
String lePlasirName = getResources().getString(R.string.restaurant_lePlasir);
String lePlasirLocation = getResources().getString(R.string.restaurant_lePlasir_location);
String lePlasirDescription = getResources().getString(R.string.restaurant_lePlasir_description);
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_place_to_eat, container, false);
final ArrayList<PuneInfo> foodPlacesInfo = new ArrayList<>();
foodPlacesInfo.add(new PuneInfo(vaishaliName, vaishaliLocation, vaishaliDescription, R.drawable.vaishali));
foodPlacesInfo.add(new PuneInfo(bedekarName, bedekarLocation, bedekarDescription, R.drawable.bedekar));
foodPlacesInfo.add(new PuneInfo(thePlaceName, thePlaceLocation, thePlaceDescription, R.drawable.theplace));
foodPlacesInfo.add(new PuneInfo(nisargaName, nisargaLocation, nisargaDescription, R.drawable.nisarg));
foodPlacesInfo.add(new PuneInfo(lePlasirName, lePlasirLocation, lePlasirDescription, R.drawable.leplasir));
PuneInfoAdapter adapter = new PuneInfoAdapter(getActivity(), foodPlacesInfo, R.color.placesToEat);
ListView listView = rootView.findViewById(R.id.placeToEat_ListView);
listView.setAdapter(adapter);
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
<file_sep>/app/src/main/java/com/example/tanushreechaubal/pune_aconfluenceofeastandwest/PuneInfo.java
package com.example.tanushreechaubal.pune_aconfluenceofeastandwest;
/**
* Created by TanushreeChaubal on 3/7/18.
*/
public class PuneInfo {
private String name;
private String location;
private String description;
private static final int NO_IMAGE_RESOURCE_ID = -1;
private int imageResourceID = NO_IMAGE_RESOURCE_ID;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static int getNoImageResourceId() {
return NO_IMAGE_RESOURCE_ID;
}
public int getImageResourceID() {
return imageResourceID;
}
public void setImageResourceID(int imageResourceID) {
this.imageResourceID = imageResourceID;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public PuneInfo(String nm, String lc, String dc, int iRI) {
name = nm;
location = lc;
description = dc;
imageResourceID = iRI;
}
public boolean hasImage(){
return imageResourceID != NO_IMAGE_RESOURCE_ID;
}
}
<file_sep>/README.md
# GoogleNanodegree1_TourGuideApp
Planning app design and navigation. Selecting proper data structures to store lists of information. Building layouts to display those lists of data. Navigating between those lists using intents and multiple Activities or a ViewPager. Creating custom classes. Properly handling images or audio. The tour guide app presents relevant information to a user who’s visiting my city- Pune. The app lists top attractions, restaurants, public places, or events for the city.
| ebd492ad0232fc156de5525d9b3017e86cc99a61 | [
"Markdown",
"Java"
] | 3 | Java | tchaubal/GoogleNanodegree1_TourGuideApp | 2e1865ea62a30b72854345308e20e268b42b192a | c7501da7365c6519014ec7d7f69abb397d8226ea |
refs/heads/master | <repo_name>thomaspreece10/Java-Programming<file_sep>/Project 0/README.md
Project 0
============
Simple introductory project to write a class which represents fractions p/q in their lowest form<file_sep>/Project 2/Polynomial.java
/*
* PROJECT II: Polynomial.java
*
* This file contains a template for the class Polynomial. Not all methods are
* implemented. Make sure you have carefully read the project formulation
* before starting to work on this file.
*
* This class is designed to use Complex in order to represent polynomials
* with complex co-efficients. It provides very basic functionality and there
* are very few methods to implement! The project formulation contains a
* complete description.
*
* Remember not to change the names, parameters or return types of any
* variables in this file! You should also test this class using the main()
* function.
*
* The function of the methods and instance variables are outlined in the
* comments directly above them.
*/
class Polynomial {
/**
* An array storing the complex co-efficients of the polynomial.
*/
Complex[] coeff;
// ========================================================
// Constructor functions.
// ========================================================
/**
* General constructor: assigns this polynomial a given set of
* co-efficients.
*
* @param coeff The co-efficients to use for this polynomial.
*/
public Polynomial(Complex[] coeff) {
int degree=coeff.length;//Finds size of inputted array for use in setting size of this.coeff
//Loops backwards through coeff
//If it finds a zero it minuses one off degree, if it finds non-zero term it exits loop
for (int i = coeff.length-1; i > -1; i--){
if (coeff[i].getReal() == 0 && coeff[i].getImag() == 0){
degree--;
} else {
break;
}
}
//Sets this.coeff to the size of degree(The size of coeff without the last terms with value zero)
//and then copys all the terms from coeff to this.coeff except the last terms with value zero
//eg. coeff = 1,2,0,1,3,0,0 would create this.coeff = 1,2,0,1,3
this.coeff = new Complex[degree];
for (int i = 0; i < degree; i++){
this.coeff[i]=coeff[i];
}
}
/**
* Default constructor: sets the Polynomial to the zero polynomial.
*/
public Polynomial() {
//Sets up this.coeff so polynomial is zero polynomial
this.coeff = new Complex[] {new Complex()};
}
// ========================================================
// Operations and functions with polynomials.
// ========================================================
/**
* Create a string representation of the polynomial.
*
* For example: (1.0+1.0i)+(1.0+2.0i)X+(1.0+3.0i)X^2
*/
public String toString() {
//Sets up tempString and sets it equal to a string representation of the first coeff
String tempString = "("+this.coeff[0].getReal()+"+"+this.coeff[0].getImag()+"i)";
//Loops through the remaining coefficients of coeff, adding a string representation of each to tempString
//And then returns tempString
for (int i = 1; i < this.coeff.length; i++){
tempString=tempString+"+("+this.coeff[i].getReal()+"+"+this.coeff[i].getImag()+"i)";
//If its a coefficent of x then just add x otherwise add x^i
switch (i){
case 1: tempString=tempString+"X"; break;
default: tempString=tempString+"X^"+i; break;
}
}
return tempString;
}
/**
* Returns the degree of this polynomial.
*/
public int degree() {
//returns the size of coeff -1 (degree)
return this.coeff.length-1;
}
/**
* Evaluates the polynomial at a given point z.
*
* @param z The point at which to evaluate the polynomial
* @return The complex number P(z).
*/
public Complex evaluate(Complex z) {
//Uses this algorithm - a+bx+cx^2+dx^3 = a + x( b + x( c + dx)) to calculate polynomial at given value
Complex c = new Complex(this.coeff[this.coeff.length-1].getReal(),this.coeff[this.coeff.length-1].getImag()); //sets the last coeff to a complex c
Complex b; //sets b to a Complex type ready to use in loop
//Loops backwards through coefficients and applys algorithm:
//(Times coefficient by value z and then adds next coefficient)
//Then sets resulting calculation to c so algorithm can be reaplyed to new c on next loop
for (int i = this.coeff.length-2; i > -1; i-- ){
b = c.multiply(z);
b = b.add(this.coeff[i]);
c.setReal(b.getReal());
c.setImag(b.getImag());
}
//returns Complex value of polynomial at z
return c;
}
/**
* Calculate and returns the derivative of this polynomial.
*
* @return The derivative of this polynomial.
*/
public Polynomial derivative() {
//Finds derivative by removing first coefficient and then
//shifting all the coefficients along 1 to left whilst multiplying coefficient by its old position
Complex[] tempcoeff = new Complex[this.coeff.length-1]; //creates a temperary array to do manipulations on with size of 1 less than coeff
//Loops through all coeff except first value assigning the value*position to the position of the value in coeff -1
for (int i = 1; i < this.coeff.length; i++){
tempcoeff[i-1]=this.coeff[i].multiply(i);
}
//Creates a polynomial with our temperary array and returns it
Polynomial p = new Polynomial(tempcoeff);
return p;
}
// ========================================================
// Tester function.
// ========================================================
public static void main(String[] args) {
//Creates a polynomial with coefficients set in coeff, Tests constructor function
Complex[] coeff = new Complex[] {new Complex(1.0,0.0), new Complex(0.0,1.0), new Complex(), new Complex(1,1), new Complex(-1,1), new Complex(0,0), new Complex(0,0)};
Polynomial p = new Polynomial(coeff);
//Tests toString and degree functions
System.out.println("Inputed polynomial: "+p.toString());
System.out.println("Degree: "+p.degree());
//Tests evaluate functions
Complex c = p.evaluate(new Complex(-1));
System.out.println(" ");
System.out.println("Polynomial Evaluated at -1: "+c.toString());
//Tests derivative function
Polynomial pdash = p.derivative();
System.out.println(" ");
System.out.println("Derivative: "+pdash.toString());
System.out.println("Degree: "+pdash.degree());
//Tests the constructor with no variables
Polynomial pzero = new Polynomial();
System.out.println(" ");
System.out.println("Zero Polynomial: "+pzero.toString());
System.out.println("Degree: "+pzero.degree());
}
}<file_sep>/README.md
Java Projects Completed for University Course
============
These 4 projects are very small coding projects that I completed for a first year course. I obtained 93% overall in the module.<file_sep>/Project 2/README.md
Project 2
============
Project to find roots of a complex polynomial using Newton-Raphson. Also draws a picture that shows which points converge to which root (the colour) and how many iterations it takes to converge to said root (the shade).<file_sep>/Project 3/README.md
Project 3
============
Project to investigate a small statistical problem involving matrices and their determinants. Looks at matrices where the coefficients are uniformly distributed random variables and looks at the variance of the matrices for each size nxn.<file_sep>/Project 1/Project1.java
/*
* PROJECT I: Project1.java
*
* As in project 0, this file - and the others you downloaded - form a
* template which should be modified to be fully functional.
*
* This file is the *last* file you should implement, as it depends on both
* Point and Circle. Thus your tasks are to:
*
* 1) Make sure you have carefully read the project formulation. It contains
* the descriptions of all of the functions and variables below.
* 2) Write the class Point.
* 3) Write the class Circle
* 4) Write this class, Project1. The Results() method will perform the tasks
* laid out in the project formulation.
*/
public class Project1 {
// -----------------------------------------------------------------------
// Do not modify the names of the variables below! This is where you will
// store the results generated in the Results() function.
// -----------------------------------------------------------------------
public int circleCounter; // Number of non-singular circles in the file.
public int posFirstLast; // Indicates whether the first and last
// circles overlap or not.
public double maxArea; // Area of the largest circle (by area).
public double minArea; // Area of the smallest circle (by area).
public double averageArea; // Average area of the circles.
public double stdArea; // Standard deviation of area of the circles.
public double medArea; // Median of the area.
public int stamp=189375;
// -----------------------------------------------------------------------
// You may implement - but *not* change the names or parameters of - the
// functions below.
// -----------------------------------------------------------------------
/**
* Default constructor for Project1. You should leave it empty.
*/
public Project1() {
// This method is complete.
}
/**
* Results function. It should open the file called FileName (using
* MaInput), and from it generate the statistics outlined in the project
* formulation. These are then placed in the instance variables above.
*
* @param fileName The name of the file containing the circle data.
*/
public void results(String fileName){
//Reads all the data from the file and counts how many
//non-singular circles there is within the data
circleCounter = 0;
MaInput F1 = new MaInput(fileName);
double x, y, rad;
x=0;
y=0;
rad=0;
while (!F1.atEOF()) {
x = F1.readDouble();
y = F1.readDouble();
rad = F1.readDouble();
if (rad > Point.GEOMTOL){
circleCounter++; // Counts the number of non-singular circles
}
}
//Does another loop through the data
F1 = new MaInput(fileName);
int circleNum=1; //Sets Integer circleNum which is equal to the line number the current circle data is from
Circle firstC = new Circle(0,0,0); //
Circle lastC = new Circle(0,0,0); // defines a new Circle ready to be set when cycling through data
Circle tempC = new Circle(0,0,0); //
double[] area = new double[circleCounter]; //create an array to store all the individual areas in
//Loops until end of file is reached
while (!F1.atEOF()) {
x = F1.readDouble(); //reads first double on line
y = F1.readDouble(); //reads second double on line
rad = F1.readDouble(); //reads third double on line
if (rad > Point.GEOMTOL){ //If radius of circle not equal to zero (within a tolerance), evaluate the data
//Sets data of first circle to firstC
if (circleNum == 1) {
firstC.setRadius(rad);
firstC.setCenter(x,y);
}
//Sets data of last circle to lastC
if (circleNum == circleCounter) {
lastC.setRadius(rad);
lastC.setCenter(x,y);
}
//Sets data of each circle in data file to a temporary Circle named tempC
tempC.setRadius(rad);
tempC.setCenter(x,y);
//calculate area of each circle and put it in the array named area
//with its index equal to line number of circle in data file
area[circleNum-1] = tempC.area();
circleNum++; //end of loop so we move to next line of file and increase our variable for line number
}
}
//Calculates whether the first and last circles overlap
//using the Circle class function 'overlap' with the two circles firstC and lastC
posFirstLast = firstC.overlap(lastC);
//Sets max and min area to the area of the first circle
//and sets averageArea to zero
maxArea=area[1];
minArea=area[1];
averageArea=0;
//loops through each element of the area array
//Works out max and min areas contained in area array
for (int i=0 ; i < circleNum-1 ; i++){
if (area[i] > maxArea) {
maxArea = area[i]; //If area in array is bigger than maxArea, set maxArea=area
}
if (area[i] < minArea) {
minArea = area[i]; //If area in array is smaller than minArea, set minArea=area
}
averageArea=averageArea+area[i]; //Adds up all the areas one by one and assigns them to variable averageArea
stdArea=stdArea+Math.pow(area[i],2); //Adds up all the areas squared one by one and assigns them to variable stdArea
}
//Finds average area by using the sum of areas(averageArea) and dividing by number of circles
//and then assigning the answer back into averageArea
averageArea=averageArea/circleCounter;
//Finds standard deviation of area by using the sum of areas squared(stdArea) and dividing by number of circles
//then taking away average of areas squared and finially square rooting the total
//then it assigns the answer back into stdArea
stdArea=Math.sqrt((stdArea/circleCounter)-Math.pow(averageArea,2));
//Uses an algorithm to sort the area array into numerical order
boolean swaped = true;
while (swaped) {
swaped = false;
for (int i = 0; i < circleNum-2 ; i++) {
if (area[i] > area[i+1]) {
double temp = area[i+1];
area[i+1] = area[i];
area[i] = temp;
swaped = true;
}
}
}
//Finds the median by taking the middle number in the array if there is an odd number of elements in array
//or taking the average of the 2 middle numbers in array if there is an even number of elements
if (circleCounter%2 == 0) {
//even number of elements
medArea = ( area[((circleNum/2))-1] + area[((circleNum/2)+1)-1] )/2;
} else {
//odd number of elements
medArea = area[(circleNum+1)/2-1];
}
}
// =======================================================
// Tester - tests methods defined in this class
// =======================================================
/**
* Your tester function should go here (see week 14 lecture notes if
* you're confused). It is not tested by BOSS, but you will receive extra
* credit if it is implemented in a sensible fashion.
*/
public static void main(String args[]){
Project1 P = new Project1();
P.results("Project1.data");
System.out.println("Number of Circles: "+P.circleCounter);
System.out.println("First and last circle overlap: "+P.posFirstLast);
System.out.println("Min area: "+P.minArea);
System.out.println("Max area: "+P.maxArea);
System.out.println("Average area: "+P.averageArea);
System.out.println("Standard Deviation of area: "+P.stdArea);
System.out.println("medium of area: "+P.medArea);
}
}
<file_sep>/Project 1/README.md
Project 1
============
2nd introductory project to writing Java. Reads in data describing circle and performs some basic statistics on the circles. | 1c8124efc85318af585709949e6c8fbaa93dfbc7 | [
"Markdown",
"Java"
] | 7 | Markdown | thomaspreece10/Java-Programming | 94c171dc2bd156c2c474a7ca305d255fe6c1f27f | ec58d9efae3826c2d3131047307a8adb1732f361 |
refs/heads/master | <file_sep>import jsonp from 'common/js/jsonp'
import { commonParams, options } from 'api/config'
// https://c.y.qq.com/v8/fcg-bin/v8.fcg?channel=singer&page=list&key=all_all_all&pagesize=100&pagenum=1&g_tk=1801096175&jsonpCallback=GetSingerListCallback&loginUin=2537204257&hostUin=0&format=jsonp&inCharset=utf8&outCharset=utf-8¬ice=0&platform=yqq&needNewCode=0
// g_tk=1801096175&inCharset=utf-8&outCharset=utf-8¬ice=0&channel=singer&page=list&key=all_all_all&pagesize=100&pagenum=1&loginUin=2537204257&hostUin=0&format=json&platform=yqq&needNewCode=0&jsonCallback=__jp0
export function getSingerList() {
const url = 'https://c.y.qq.com/v8/fcg-bin/v8.fcg'
const params = Object.assign({}, commonParams, {
channel: 'singer',
page: 'list',
key: 'all_all_all',
pagesize: 100,
pagenum: 1,
g_tk: 1801096175,
loginUin: 2537204257,
hostUin: 0,
format: 'json',
platform: 'yqq',
needNewCode: 0,
})
return jsonp(url, params, options)
}
<file_sep>/* eslint-disable */
const state = {
singer: {}
}
export default state<file_sep>/* eslint-disable */
export const singer = state => state.singer | 03b9915e7943913bd96725644f142754373cea80 | [
"JavaScript"
] | 3 | JavaScript | sichenguo/web-music | 613de3a4383e45b96a054a6b1177b7b4126eb903 | cb44cfbdcfcde39bed3590be1d47ffde42ed76a8 |
refs/heads/master | <file_sep>/*
Copyright 2019 The Kubernetes Authors.
Licensed 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 cmd
import (
log "sigs.k8s.io/etcdadm/pkg/logrus"
"github.com/spf13/cobra"
"sigs.k8s.io/etcdadm/apis"
"sigs.k8s.io/etcdadm/auth"
)
var tenantCmd = &cobra.Command{
Use: "tenant",
Short: "Creates a user and assigns it full read/write access to a specified prefix that will be created if it doesn't exist",
Run: func(cmd *cobra.Command, args []string) {
apis.SetDefaults(&etcdAdmConfig)
if err := apis.SetInitDynamicDefaults(&etcdAdmConfig); err != nil {
log.Fatalf("[defaults] Error: %s", err)
}
name, err := cmd.Flags().GetString("name")
if err != nil {
log.Fatalf("Error parsing option value for name")
}
if err = auth.CreateTenant(&etcdAdmConfig, name); err != nil {
log.Fatalf("[tenant] Error: %s", err)
}
},
}
func init() {
rootCmd.AddCommand(tenantCmd)
// TODO: Make --name flag required
tenantCmd.Flags().String("name", "", "Specify name to be used as: client cert Common Name(CN), user, role, and prefix. The user is given readwrite access to the prefix of the same name. The prefix is created at the root of etcd for now.")
tenantCmd.MarkFlagRequired("name")
// tenantCmd.Flags().String("prefix", "", "The etcd prefix path to grant full read/write access to user")
}
<file_sep>/*
Copyright 2019 The etcdadm Authors.
Licensed 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 auth
import (
"fmt"
"math/rand"
"os/exec"
"strings"
"time"
"sigs.k8s.io/etcdadm/apis"
"sigs.k8s.io/etcdadm/certs"
"sigs.k8s.io/etcdadm/util"
)
// CreateTenant uses etcdctl to create a user "name" according to official etcd documentation, and then assigns it a role with readwrite access to the prefix "/name"
// specified prefix
// https://github.com/etcd-io/etcd/blob/master/Documentation/op-guide/authentication.md
func CreateTenant(cfg *apis.EtcdAdmConfig, name string) error {
if err := createUserAndRole(cfg, name); err != nil {
return err
}
if err := certs.CreateTenantClientCertAndKeyFiles(cfg, name); err != nil {
return err
}
return nil
}
// EnableAuthWithRootUser will use etcdctl to create the root user with a randomly generated password and enable auth for etcd.
// This should be invoked during etcdadm init, perhaps gated behind a boolean flag like '--enable-auth' (true by default)
func EnableAuthWithRootUser(cfg *apis.EtcdAdmConfig) error {
if err := createRootUser(cfg); err != nil {
return err
}
if err := authEnable(cfg); err != nil {
return err
}
return nil
}
// SetupRootUserConfig sets the generated password for root user in EtcdAdmnConfig struct such that it can later be
// written to the etcdctl env file
func SetupRootUserConfig(cfg *apis.EtcdAdmConfig) error {
cfg.EtcdctlRootUserPassword = <PASSWORD>()
return nil
}
func authEnable(cfg *apis.EtcdAdmConfig) error {
etcdctl, err := ensureEtcdctlPath(cfg)
if err != nil {
return err
}
cmdArgs := []string{
"auth",
"enable",
}
cmd := exec.Command(etcdctl, cmdArgs...)
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("[auth] `%v` command failed with error: %v", cmd.Args, err)
}
fmt.Printf("[auth] %s", out)
return nil
}
// createUserAndRole is functionally equivalent to the following commands:
// `etcdctl user add <name>`
// `etcdctl role add <name>`
// `etcdctl role grant-permission <name> --prefix=true readwrite /<name>/`
// `etcdctl user grant-role <name> <name>`
func createUserAndRole(cfg *apis.EtcdAdmConfig, name string) error {
etcdctl, err := ensureEtcdctlPath(cfg)
if err != nil {
return err
}
// FIXME: surely there's a better way to validate this?
if strings.Contains(name, "/") {
return fmt.Errorf("[auth] invalid value for --name: '%s' cannot contain / (try using a DNS-compliant value)", name)
}
// os.Setenv("ETCDCTL_USER", fmt.Sprintf("root:%s", cfg.EtcdctlRootUserPassword))
cmds := []*exec.Cmd{
// Create user
exec.Command(etcdctl, []string{
"user",
"add",
fmt.Sprintf("%s:%s", name, randomPassword()),
}...),
// Create role
exec.Command(etcdctl, []string{
"role",
"add",
name,
}...),
// Define permissions for role
exec.Command(etcdctl, []string{
"role",
"grant-permission",
name, // role name
"--prefix=true",
"readwrite",
fmt.Sprintf("/%s/", name),
}...),
// Assign role to user
exec.Command(etcdctl, []string{
"user",
"grant-role",
name, // role name
name,
}...),
}
for _, cmd := range cmds {
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("[auth] `%v` command failed with error: %v", cmd.Args, err)
}
fmt.Printf("[auth] %s", out)
}
return nil
// Doing above until I decide granular handling of errors if a user/role already exists when trying to create them is worth it
// Add role
// cmdArgs := []string{
// "role",
// "add",
// name,
// }
// cmd := exec.Command(etcdctlWrapper, cmdArgs...)
// out, err := cmd.Output()
// if err != nil {
// // TODO: handle already existing roles by checking err output for `Error: etcdserver: role name already exists`
// return fmt.Errorf("[auth] `%v` command failed with error: %v", cmd.Args, err)
// }
// // Assign role to user of same name with full permissions to prefix of same name
// cmdArgs = []string{
// "role",
// "grant-permission",
// name, // role name
// "--prefix=true",
// "readwrite",
// fmt.Sprintf("/%s/", name),
// }
// cmd = exec.Command(etcdctlWrapper, cmdArgs...)
// out, err = cmd.Output()
// if err != nil {
// // TODO: handle error if role name (arg after "grant-permission") does not exist. Error will be `Error: etcdserver: role name not found`
// return fmt.Errorf("[auth] `%v` command failed with error: %v", cmd.Args, err)
// }
// return nil
}
// createRootUser uses etcdctl to create users according to official etcd documentation
// https://github.com/etcd-io/etcd/blob/master/Documentation/op-guide/authentication.md
func createRootUser(cfg *apis.EtcdAdmConfig) error {
etcdctl, err := ensureEtcdctlPath(cfg)
if err != nil {
return err
}
// Generate a password for non-root users. It won't be used however since we're going to have apiservers authenticate
// using client certs
if cfg.EtcdctlRootUserPassword == "" {
return fmt.Errorf("[auth] etcd root user password not found in EtcdAdmConfig.EtcdctlRootUserPassword")
}
cmdArgs := []string{
"user",
"add",
fmt.Sprintf("root:%s", cfg.EtcdctlRootUserPassword),
}
cmd := exec.Command(etcdctl, cmdArgs...)
out, err := cmd.CombinedOutput()
if err != nil {
// TODO: eventually handle existing users via something like: strings.Contains(string(out), expected)
return fmt.Errorf("[auth] `%v` command failed with error: %v", cmd.Args, err)
}
fmt.Printf("[auth] %s", out)
return nil
}
// createUser uses `etcdctl` to create users according to official etcd documentation.
// Equivalent of `etcdctl user add <user>:<random_password>`.
// https://github.com/etcd-io/etcd/blob/master/Documentation/op-guide/authentication.md
func createUser(cfg *apis.EtcdAdmConfig, user string) error {
etcdctl, err := ensureEtcdctlPath(cfg)
if err != nil {
return err
}
// Generate a password for non-root users. It won't be used however since we're going to have apiservers authenticate
// using client certs
cmdArgs := []string{
"user",
"add",
fmt.Sprintf("%s:%s", user, randomPassword()),
}
cmd := exec.Command(etcdctl, cmdArgs...)
out, err := cmd.CombinedOutput()
if err != nil {
// TODO: eventually handle existing users via something like: strings.Contains(string(out), expected)
return fmt.Errorf("[auth] `%v` command failed with error: %v", cmd.Args, err)
}
fmt.Printf("[auth] %s", out)
return nil
}
// ensureEtcdCtlPath is a helper function which ensures we can execute `etcdctl` at the path specified
// by `EtcdAdmnConfig`. We use the wrapper `etcdctl.sh` because it ensures the correct environment values are set
func ensureEtcdctlPath(cfg *apis.EtcdAdmConfig) (string, error) {
exists, err := util.Exists(cfg.EtcdctlShellWrapper)
if err != nil {
return "", fmt.Errorf("[auth] error checking if executable exists at path %s", cfg.EtcdctlShellWrapper)
}
if !exists {
return "", fmt.Errorf("[auth] executable does not exist at path %s", cfg.EtcdctlShellWrapper)
}
// TODO: Figure out how to handle 2.x maybe? Not worth IMO
if strings.HasPrefix(cfg.Version, "2") {
return "", fmt.Errorf("[auth] enabling auth and creating root user only supported by etcdadm in version 3.x of etcd")
}
return cfg.EtcdctlShellWrapper, nil
}
// randomPassword generates a random alphanumeric string without special characters that is 16 characters in length.
// Adapted from https://yourbasic.org/golang/generate-random-string/
func randomPassword() string {
rand.Seed(time.Now().UnixNano())
chars := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
length := 16
var b strings.Builder
for i := 0; i < length; i++ {
b.WriteRune(chars[rand.Intn(len(chars))])
}
return b.String()
}
| 2085a4a8037ef036b39ce145a25059de2dd1ab10 | [
"Go"
] | 2 | Go | texascloud/etcdadm | 302653ec6e30521cb12d22591e489ce238a9a32e | 90902743b46756357b3ed207d57d3a46b6a0afa2 |
refs/heads/master | <file_sep>import tkinter as tk
from tkinter import messagebox
#File Handling
def _file():
f= open("Info.txt", "a+")
a= "\n\nName="+entry1.get()+"\nMob No.="+entry2.get()+"\nAddress="+entry3.get()+"\nEmail Id="+entry4.get()+"\n\n\n"
f.write(a)
def _readinfo():
f= open("Info.txt", "r+")
contents= (f.read())
print("The info", contents)
# check_function
def _contactcheck():
contact1 = entry2.get()
if len(contact1) == 10 and contact1.isdigit():
_addresscheck()
pass
else:
_errorshow()
def _namecheck():
name1 = entry1.get()
if len(name1) != 0 and (name1.isalpha()):
_contactcheck()
pass
else:
_errorshow()
def _emailcheck():
email1 = entry4.get()
if "@" in email1 and len(email1) >= 5 and (email1.endswith('com') or email1.endswith('in')):
_output()
pass
else:
_errorshow()
def _addresscheck():
address1 = entry3.get()
if len(address1) != 0:
_emailcheck()
pass
else:
_errorshow()
# error display function
def _errorshow():
tk.messagebox.showwarning("ERROR", "Enter Some Proper Values")
# onclick function
def _onclick():
_namecheck()
# OUTPUT DISPLAY
def _output():
print("Name=", entry1.get(), "\nMob No.=", entry2.get(), "\nAddress=", entry3.get(), "\nEmail Id=", entry4.get())
_file()
# GUI
r = tk.Tk()
r.geometry("500x200")
r.title("MPillai____REGISTRATION FORM____")
head = tk.Label(r, text="REGISTRATION FORM", bg="black", fg="white")
head.grid(row=0, column=2)
label1 = tk.Label(r, text='Name', width=23, fg="red")
label1.grid(row=1, column=0)
label2 = tk.Label(r, text='Mob No.', width=20, fg="red")
label2.grid(row=4, column=0)
label3 = tk.Label(r, text='Address', width=23, fg="red")
label3.grid(row=7, column=0)
label3 = tk.Label(r, text='Email ID', width=20, fg="red")
label3.grid(row=10, column=0)
entry1 = tk.Entry(r, text="Enter Your Name", fg="blue")
entry1.grid(row=1, column=3)
entry2 = tk.Entry(r, text="Enter Your Mobile No.", fg="blue")
entry2.grid(row=4, column=3)
entry3 = tk.Entry(r, text="Enter Your Address", fg="blue")
entry3.grid(row=7, column=3)
entry4 = tk.Entry(r, text="Enter Your Email Id.", fg="blue")
entry4.grid(row=10, column=3)
button1 = tk.Button(r, text="Submit", fg="Black", bg="green", command=_onclick)
button1.grid(row=11, column=1)
button2 = tk.Button(r, text="Close", fg="Black", bg="green", command=r.destroy)
button2.grid(row=11, column=3)
button3= tk.Button(r, text="All Info", fg="Black", bg="green", command=_readinfo)
button3.grid(row=12,column=2)
r.resizable(0, 0)
r.mainloop()
<file_sep>import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
import PyPDF2
from fpdf import FPDF
import tkinter.font as font
from csv import DictWriter
from csv import DictReader
import os
# all inputs are stored in global variable
def all_input_global_variable(): # all inputs are stored in global variables
global name, mobile, email, age, eligibility, gender
name = name_input.get().strip() # takes name input
mobile = mobile_input.get() # takes mobile input
email = email_input.get() # takes email input
age = age_spinbox.get() # takes age values from the input
eligibility = el_state.get() # takes eligibility input
gender = gender_box.get() # takes gender input
# eligibility
if eligibility == 1:
eligibility = "Eligible"
elif eligibility == 2: # ************ if not selected then 0 check it **********
eligibility = "Not eligible"
# Term And Condition Part
def terms_condition_display(): # displays terms and condition (function for terms and condition checkbox)
if tc_state.get():
tk.messagebox.showinfo("Terms & Condition", 'By agreeing terms and condition') # displays term and condition
# enables txt, pdf, csv buttons
get_PDF_button.config(state="normal")
get_CSV_button.config(state="normal")
get_TXT_button.config(state="normal")
else:
tk.messagebox.showwarning("Error", 'Please agree the term and condition to continue') # displays warning
# disables txt, pdf, csv button
get_PDF_button.config(state="disabled")
get_CSV_button.config(state="disabled")
get_TXT_button.config(state="disabled") #
# validates if user input are correct or nt
def valid_input_check(): # performs on check (function for check button)
all_input_global_variable()
# ----------------------------checks the user input ----------------------------#
if len(name) == 0 or not name.replace(" ", "").isalpha(): # checks if name input is null or contains digit
tk.messagebox.showerror("ERROR", "Wrong Name Input")
return 0 # returns 0 for error
elif len(mobile) != 10 or not mobile.isdigit():
# checks if mobile input is not 10 or not digit
tk.messagebox.showerror("ERROR", "Wrong Mobile Input")
return 0 # returns 0 for error
elif '@' not in email or len(email) < 5 or (not email.endswith('.com') and not email.endswith('in')):
# checks if email input does contain @ and whether ends with .com
tk.messagebox.showerror("ERROR", "Wrong Email Input")
return 0 # returns 0 for error
elif int(age) not in range(0, 100):
# if age is not in range 0 and 100
tk.messagebox.showerror("ERROR", "Age is not proper \n\nPlease Select a number from 0 to 100")
return 0 # returns 0 for error
elif gender not in ["Male", "Female", "Others"]:
# if age is not from drop menu
tk.messagebox.showerror("ERROR", "Improper gender selection \n\nPlease Select from drop menu")
return 0
else:
return 1 # return 1 for success
# function for clear button
def on_clear_click(): # performs on clear (function for clear button)
info_textbox_display.config(state="normal") # enables textbox to insert data
info_textbox_display.delete(1.0, tk.END) # delete data already present in text box
info_textbox_display.config(state="disabled") # disables textbox to avoid user input
# displays success message on textbox after data is stored
def success_message_textbox():
# displays successfully stored message in textbox
info_textbox_display.config(state="normal") # enables textbox to insert data
info_textbox_display.delete(1.0, tk.END) # delete data already present in text box
info_textbox_display.insert(tk.END, "The details have been successfully stored") # inserts all file data in textbox
info_textbox_display.config(state="disabled") # disables textbox to avoid user input
# text data
def get_text_data():
# all inputs are stored in global variable
all_input_global_variable()
file_get_txt = open("Info_in_text.txt", "a+") # opened a file in append mode (creates if does not exits)
file_get_txt.seek(0) # goes to first line of file
file_contents_get_text = file_get_txt.read() # all file contents are stored in this variable
if not valid_input_check():
# it checks if inputs are valid or not
pass
elif mobile in file_contents_get_text or email in file_contents_get_text:
# mobile/ email id is already present in file
tk.messagebox.showerror("ERROR", "Mobile Number or Email ID already present \n\nPlease Enter Valid Input")
else:
# if no problem in input then it will print in the file
file_get_txt.write("Name :" + name + "\nMob No :" + str(
mobile) + "\nEmail Id :" + email + "\nAge :" + age + "\nGender :" + gender + "\nEligible :" + eligibility + "\n\n")
success_message_textbox()
def get_pdf_data():
# all inputs are stored in global variable
all_input_global_variable()
"""
file_get_pdf = "Info_in_pdf.pdf"
file_get_pdf_reader = PyPDF2.PdfFileReader(file_get_pdf)
file_get_pdf_page = file_get_pdf_reader.getPage()
file_get_pdf_text = file_get_pdf_page.extractText()
if mobile in file_get_pdf_text or email in file_get_pdf_text:
tk.messagebox.askyesno("Title","Message")
pass
"""
# to write in pdf
write_data_pdf = FPDF()
write_data_pdf.add_page()
write_data_pdf.set_font("Arial", size=15)
write_data_pdf.cell(300, 100, txt=name, ln=2, align="L")
write_data_pdf.output("Info_in_pdf.pdf")
success_message_textbox()
# csv data
def get_csv_data():
all_input_global_variable() # all inputs are declaraed in gloabal variable
get_csv_file = open("Info_in_csv.csv",'a',newline='') # csv file is called
get_csv_file_reader = open("Info_in_csv.csv",'r')
csv_dict_writer = DictWriter(get_csv_file,
fieldnames=['Name', 'Mob No', 'Email Id', 'Age', 'Gender', 'Eligibility'])
csv_dict_reader = DictReader(get_csv_file_reader)
error_csv_data_reader = 0 # flag type variable for repeation check
for row_csv_dict_reader in csv_dict_reader:
if mobile in row_csv_dict_reader['Mob No'] or email in row_csv_dict_reader['Email Id']:
error_csv_data_reader = 1 # setting value as 1 for error
break
if not valid_input_check(): # check if input is valid
pass
elif error_csv_data_reader == 1: # if error_csv_data_reader == 1 then display error
tk.messagebox.showerror("ERROR", "Mobile Number or Email Id Already Present")
else:
if os.path.getsize("Info_in_csv.csv") == 0: # check if file is empty
csv_dict_writer.writeheader() # writes the heading
# enters user data to csv file
csv_dict_writer.writerow({
'Name': name,
'Mob No': mobile,
'Email Id': email,
'Age': age,
'Gender': gender,
'Eligibility': eligibility})
# check button function
def check_button_function():
all_input_global_variable()
if not valid_input_check():
# it checks if inputs are valid or not
pass
else:
info_textbox_display.config(state="normal") # enables textbox to insert data
info_textbox_display.delete(1.0, tk.END) # delete data already present in text box
# display user input data in textbox
info_textbox_display.insert(tk.END,
"Name :" + name + "\nMob No :" + str(
mobile) + "\nEmail Id :" + email + "\nAge :" + age + "\nGender :" + gender + "\nEligible :" + eligibility + "\n\n") # inserts all file data in textbox
info_textbox_display.config(state="disabled") # disables textbox to avoid user input
# GUI Part
r = tk.Tk()
el_state = tk.IntVar() # for eligible radio button
tc_state = tk.IntVar() # for terms and condition check box
r.geometry("400x650")
r.title("Registration Form") # title of frame
r.configure(background="sky blue") # background color
title_font_style = font.Font(family="Arial", size=15, weight=font.BOLD) # font style for title
label_font_style = font.Font(family='Helvetica', size=11, weight=font.BOLD) # font style for label
input_font_style = font.Font(family="Helvetica", size=11, weight=font.NORMAL) # font style for inputs
button_font_style = font.Font(family="Arial", size=13, weight=font.BOLD) # button style
# Title label
title_label = tk.Label(r, text="REGISTRATION FORM", bg="black", fg="white", font=title_font_style) # title label
title_label.place(x=75, y=10)
# Label Part
name_label = tk.Label(r, text="Name", fg="black", bg="sky blue", font=label_font_style) # name label
name_label.place(x=60, y=60)
mobile_label = tk.Label(r, text="Mobile No.", fg="black", bg="sky blue", font=label_font_style) # mobile label
mobile_label.place(x=60, y=100)
email_label = tk.Label(r, text="Email ID", fg="black", bg="sky blue", font=label_font_style) # email id label
email_label.place(x=60, y=140)
age_label = tk.Label(r, text="Age", fg="black", bg="sky blue", font=label_font_style) # age label
age_label.place(x=60, y=180)
gender_label = tk.Label(r, text="Gender", fg="black", bg="sky blue", font=label_font_style) # gender label
gender_label.place(x=60, y=220)
# Input Part
name_input = tk.Entry(r, width=15, font=input_font_style) # name input
name_input.place(x=180, y=60)
mobile_input = tk.Entry(r, width=15, font=input_font_style) # mobile no input
mobile_input.place(x=180, y=100)
email_input = tk.Entry(r, width=15, font=input_font_style) # email input
email_input.place(x=180, y=140)
# eligibility input
eligible1_radio = tk.Radiobutton(r, text="Eligible", variable=el_state, value=1, bg="sky blue",
font=label_font_style)
eligible1_radio.place(x=60, y=260)
eligible2_radio = tk.Radiobutton(r, text="Not Eligible", variable=el_state, value=2, bg="sky blue",
font=label_font_style)
eligible2_radio.place(x=200, y=260)
el_state.set(1) # initially it would be set at eligible condition
# term & condition
agreement_checkbox = tk.Checkbutton(r, text="Agree to Terms and Conditions", variable=tc_state,
command=terms_condition_display, font=label_font_style)
# active background
agreement_checkbox.place(x=60, y=310)
age_spinbox = tk.Spinbox(r, from_=0, to=100, width=18) # age input
age_spinbox.place(x=180, y=180)
gender_box = ttk.Combobox(r, width="17", values=["Male", "Female", "Others"]) # age input
gender_box.place(x=180, y=220)
# buttons
get_TXT_button = tk.Button(r, text="TEXT", bg="sky blue",
font=button_font_style, state="disabled", command=get_text_data) # to view txt data
get_TXT_button.place(x=60, y=350)
get_PDF_button = tk.Button(r, text="PDF", command=get_pdf_data, bg="sky blue", state="disabled",
font=button_font_style) # to view pdf data
get_PDF_button.place(x=170, y=350)
get_CSV_button = tk.Button(r, text="CSV", command=get_csv_data, bg="sky blue", state="disabled",
font=button_font_style) # to view csv data
get_CSV_button.place(x=260, y=350)
check_button = tk.Button(r, text="CHECK", command=check_button_function, bg="black", fg="white",
font=button_font_style) # submit button
check_button.place(x=60, y=600)
clear_button = tk.Button(r, text="CLEAR", command=on_clear_click, bg="black", fg="white",
font=button_font_style) # submit button
clear_button.place(x=240, y=600)
# text box ********************* scroll bar problem *************************
info_textbox_display = tk.Text(r, width=31, height=10, state="disabled")
info_textbox_display.place(x=60, y=400)
info_textbox_scrollbar = tk.Scrollbar(r, command=info_textbox_display.yview, orient="vertical")
info_textbox_scrollbar.config(command=info_textbox_display.yview)
info_textbox_display.config(yscrollcommand=info_textbox_scrollbar.set)
# info_textbox_display.pack(side="left", fill="both", expand='NO')
info_textbox_scrollbar.pack(side="right", fill="both")
r.resizable(0, 0) # to disable minimize and maximize
r.mainloop()
| 86dabec238f6f1f87ecdc48824ac3d516b7d5b0b | [
"Python"
] | 2 | Python | PillaiManish/BasicForm-Using-Python- | 512b4170a45754dac9f65618954489e920e2c95d | a0dc76d1048e02827d286eeb6a1c82d1325102f9 |
refs/heads/main | <file_sep><?php require_once 'load.php'?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php require_once root.hw.inc.'/refence.php';?>
<title>HEART DISEASE | Login</title>
</head>
<body>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="fit col-md-auto">
<form action="index.php" method="post">
<div class="form-group">
<h5 id="form_title"></h5>
<div class="fit mt-3"><a href="index.php" class="btn btn-sm btn-outline-warning" title="Go to dashboard">Dashboard</a></div>
</div>
<div class="form-group mt-5">
<div class="input-group">
<div class="input-group-prepend"><span class="input-group-text"><i id="id_icon" class="none"></i></span></div>
<input type="text" name="none" id="id_card" class="form-control" placeholder="none">
</div>
</div>
<div class="form-group mt-4">
<div class="input-group">
<div class="input-group-prepend"><span class="input-group-text"><i class="fa fa-key"></i></span></div>
<input type="password" name="passwword" class="form-control" placeholder="<PASSWORD>">
</div>
</div>
<div class="form-group mt-4">
<div class="col-sm-10">
<button type="submit" name="login" id="login_btn" class="btn btn-outline-primary" title="Access your account here">Login</button>
</div>
</div>
<div class="form-group mt-4">
<div class="fit">Not yet a member ? <a href="#" id="signup_link" title="Open a new account">Sign Up</a></div>
</div>
</form>
</div>
</div>
</div>
<script>
var current_page = window.location.href;
var form_title = document.querySelector('#form_title');
var id_card = document.querySelector('#id_card');
var id_icon = document.querySelector('#id_icon');
var login_btn = document.querySelector('#login_btn');
var signup_link = document.querySelector('#signup_link');
if(current_page == 'http://localhost/hd/login.php?health_worker') {
form_title.innerHTML = 'HEALTH WORKERS PANEL';
id_icon.classList.remove('none');
id_icon.classList.add('fa', 'fa-id-card');
id_card.name = 'worker_id';
id_card.placeholder = 'Example HW001';
id_card.title = 'Enter your worker_id';
login_btn.name = 'login_hw';
signup_link.href = 'signup.php?health_worker';
}
else if(current_page == 'http://localhost/hd/login.php?patient') {
id_icon.classList.remove('none');
id_icon.classList.add('fa', 'fa-phone-alt');
form_title.innerHTML = 'PATIENTS PANEL';
id_card.name = 'patient_phone';
id_card.placeholder = 'Example +254123456789';
id_card.title = 'Enter your phone number';
login_btn.name = 'login_patient';
signup_link.href = 'signup.php?patient';
}
else {
window.location.href = 'index.php';
}
</script>
</body>
</html><file_sep><?php
session_start();
require_once 'config.php';
require_once root.hw.inc.net.'/net.php';
require_once root.hw.inc.'/functions.php'
?><file_sep><?php
function location($to) {
header("location:".$to);
}
?><file_sep><?php require_once 'load.php'?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php require_once root.hw.inc.'/refence.php';?>
<title>HEART DISEASE | Sign Up</title>
</head>
<body>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="fit col-md-auto">
<form action="index.php" method="post">
<div class="form-group">
<h5 id="form_title">Health Workers Panel</h5>
<div class="fit mt-3"><a href="index.php" class="btn btn-sm btn-outline-warning" title="Go to dashboard">Dashboard</a></div>
</div>
<div class="form-group mt-5">
<div class="input-group">
<div class="input-group-prepend"><span class="input-group-text"><i id="id_icon" class="none"></i></span></div>
<input type="text" name="none" id="id_card" class="form-control" placeholder="none" aria-describedby="id_block">
</div>
<small id="id_block" class="form-text text-muted"></small>
</div>
<div class="form-group mt-5">
<div class="input-group">
<div class="input-group-prepend"><span class="input-group-text"><i id="contact_icon" class="none"></i></span></div>
<input type="none" name="none" id="contact_card" class="form-control" placeholder="none" aria-describedby="contact_block">
</div>
<small id="contact_block" class="form-text text-muted"></small>
</div>
<div class="form-group mt-5" id="role">
<div class="input-group">
<div class="input-group-prepend"><span class="input-group-text"><i class="fa fa-user-md"></i></span></div>
<select name="role" class="form form-control" aria-describedby="roleBlock">
<option value="choose" selected hidden>Choose medical role</option>
<option value="doctor">Doctor</option>
<option value="nurse">Nurse</option>
</select>
</div>
<small id="roleBlock" class="form-text text-muted">
Work category
</small>
</div>
<div class="form-group mt-4">
<div class="input-group">
<div class="input-group-prepend"><span class="input-group-text"><i class="fa fa-key"></i></span></div>
<input type="password" name="passwword" class="form-control" id="inputEmail3" placeholder="<PASSWORD>" aria-describedby="passwordBlock">
</div>
</div>
<small id="passwordBlock" class="form-text text-muted">
Password should contain numbers, upper case and lower case letters
</small>
<div class="form-group mt-4">
<div class="col-sm-10">
<button type="submit" name="new" id="signup_btn" class="btn btn-outline-primary" title="Open a new account">Sign Up</button>
</div>
</div>
<div class="form-group mt-4">
<div class="fit">Already a member ? <a href="login.php" id="login_link" title="Access your accunt here">Login</a></div>
</div>
</form>
</div>
</div>
</div>
<script>
var current_page = window.location.href;
var form_title = document.querySelector('#form_title')
var id_icon = document.querySelector('#id_icon');
var id_card = document.querySelector('#id_card');
var id_block = document.querySelector('#id_block');
var contact_icon = document.querySelector('#contact_icon');
var contact_card = document.querySelector('#contact_card');
var contact_block = document.querySelector('#contact_block');
var role = document.querySelector('#role');
var signup_btn = document.querySelector('#signup_btn');
var login_link = document.querySelector('#login_link');
if(current_page == 'http://localhost/hd/signup.php?health_worker') {
form_title.innerHTML = 'HEALTH WORKERS PANEL';
id_icon.classList.remove('none');
id_icon.classList.add('fa', 'fa-id-card');
id_card.name = 'worker_id';
id_card.placeholder = 'Example HW001';
id_card.title = 'Enter your worker_id';
id_block.innerHTML = "Worker ID should contain letters and numbers<br/>As the one you were given by your organization";
contact_icon.classList.remove('none');
contact_icon.classList.add('fa', 'fa-envelope');
contact_card.type = 'email';
contact_card.name = 'worker_id';
contact_card.placeholder = 'Example <EMAIL>';
contact_card.title = 'Enter your working email address';
contact_block.innerHTML = "Please provide a working email address";
signup_btn.name = 'new_hw';
login_link.href = 'login.php?health_worker';
}
else if(current_page == 'http://localhost/hd/signup.php?patient') {
id_icon.classList.remove('none');
id_icon.classList.add('fa', 'fa-user');
form_title.innerHTML = 'PATIENTS PANEL';
id_card.name = 'patient_names';
id_card.placeholder = 'Example <NAME>';
id_card.title = 'Enter your full names';
id_block.innerHTML = 'Please provide your full names';
contact_icon.classList.remove('none');
contact_icon.classList.add('fa','fa-phone-alt');
contact_card.type = 'text';
contact_card.name = 'patient_number';
contact_card.placeholder = 'Example +254123456789';
contact_card.title = 'Enter your mobile phone number';
contact_block.innerHTML = 'Please provide a working phone number';
role.hidden = true;
signup_btn.name = 'new_patient';
login_link.href = 'login.php?patient';
}
else {
window.location.href = 'index.php';
}
</script>
</body>
</html><file_sep><?php require_once 'load.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php require_once root.hw.inc.'/refence.php';?>
<title>HEART DISEASE</title>
</head>
<body>
<div class="container mt-5">
<div class="row justify-content-center">
<h5>HEART DISEASE PREDICTION PROGRAM</h5>
</div>
<div class="row justify-content-center mt-5">
<div class="col-md-auto shadow-lg rounded">
<div class="form-group">
<p class="text"><!-- brief description--></p>
</div>
<div class="form-group">
<a href="login.php?health_worker" class="btn btn-outline-primary shadow-lg rounded" title="proceed as a health worker">Health Worker</a>
<a href="login.php?patient" class="btn btn-outline-dark shadow-lg rounded ml-5" title="proceed as a patient">Patient</a>
</div>
</div>
</div>
</div>
</body>
</html><file_sep><?php
define('root', realpath(dirname(__FILE__)));
define('hw', '/hw');
define('inc', '/includes');
define('net', '/network');
?><file_sep># health
this repository is about a heart disease prediction system using PHP
<file_sep><?php
require_once 'load.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php require_once root.hw.inc.'/refence.php';?>
<title>HEART DISEASE | HEALTH WORKERS</title>
</head>
<body>
</body>
</html><file_sep><?php
require_once 'config/db.php';
$net = mysqli_connect(host,user,pass,database);
if ($net -> connect_error) {
echo "<script>alert('we cannot connect to our store at the moment. Try agin later');</script>";
}
?> | a5605c5a26d36a8267703d1742e1dd776cea8caa | [
"Markdown",
"PHP"
] | 9 | PHP | 2001millie/health | c2f87aa3954cc4ce8207c8eb664c2a644348ac7c | 4a6b354f6caa5c9bfd79070f9a057a3df2d00065 |
refs/heads/master | <file_sep>#ifndef _COMMON_H
#define _COMMON_H
// 2017.12.02 21:09
#include <cstddef>
#include <fstream>
size_t CalcFileSize(std::istream&);
#endif // _COMMON_H
<file_sep>#include <random>
#include <ctime>
#include <cstring>
#include "BmpFactory.h"
#include "Mandelbrot.h"
namespace {
/* static function */
void GetRGB(const double value, unsigned char &red,
unsigned char &green, unsigned char &blue)
{
// 256 * 6 + 255 = 1791
unsigned colorInt = value * 1791;
unsigned char bracket = colorInt / 256;
unsigned char color = colorInt % 256;
red = green = blue = 0;
switch (bracket) {
case 0:
red = color;
break;
case 1:
red = 255;
green = color;
break;
case 2:
red = 255 - color;
green = 255;
break;
case 3:
green = 255;
blue = color;
break;
case 4:
green = 255 - color;
blue = 255;
break;
case 5:
red = color;
blue = 255;
break;
case 6:
red = 255 - color;
blue = 255 - color;
break;
default:
break;
}
}
}
BmpFactory::BmpFactory()
{
bmpFileHdr.bfOffBits = 54;
bmpInfoHdr.biWidth = 1920;
bmpInfoHdr.biHeight = 1080;
bmpInfoHdr.biBitPerPxl = 24;
bmpInfoHdr.biXPxlsPerMeter = 0;
bmpInfoHdr.biYPxlsPerMeter = 0;
UpdateBmpHeader();
}
void BmpFactory::UpdateBmpHeader()
{
bmpInfoHdr.biImageSize = bmpInfoHdr.GetBiImageSize();
bmpFileHdr.bfSize = bmpFileHdr.bfOffBits + bmpInfoHdr.biImageSize;
}
size_t BmpFactory::GetFile(std::shared_ptr<char[]> &fileSptr)
{
// get mandelbrot value map
Mandelbrot mandelbrot;
std::default_random_engine engine(time(0));
std::uniform_real_distribution<double>
dist(mandelbrot.GetZoomFactor(), mandelbrot.GetZoomFactor()+1);
mandelbrot.SetZoomFactor(dist(engine));
std::shared_ptr<double> mdbValMap =
mandelbrot.GetMdbValMap(bmpInfoHdr.biWidth, bmpInfoHdr.biHeight);
const double *mdbValMapPtr = mdbValMap.get();
/* new unsigned array(size is iteration) and initialize with 0
* histogram is using to statistic the ratio of diffrent value in mdbValMap
* the value in mdbValMap won't greater than 'iteration-1' */
const size_t interation = mandelbrot.GetIteration();
const size_t resolution = bmpInfoHdr.biImageSize / (bmpInfoHdr.biBitPerPxl/8);
std::unique_ptr<double[]> histogram(new double[interation+1]{0});
for (size_t i = 0; i < resolution; ++i)
++histogram[static_cast<size_t>(mdbValMapPtr[i])];
// 'histogram[0]' equal to 0;
// redundant last element of histogram using for prevent out-of-range
// when get value using 'histogram[mdbValue + 1]';
for (size_t i = 1; i < interation+1; ++i)
histogram[i] = histogram[i-1] + histogram[i] / resolution;
// convert mandelbrot value to RGB according to histogram
std::shared_ptr<unsigned char> sptrImage(
new unsigned char[bmpInfoHdr.biImageSize]{0},
std::default_delete<unsigned char[]>());
unsigned char *image = sptrImage.get();
for (size_t i = 0; i < resolution; ++i) {
const size_t mdbValue = static_cast<size_t>(mdbValMapPtr[i]);
double colorCode = histogram[mdbValue];
colorCode += (mdbValMapPtr[i] - mdbValue) *
(histogram[mdbValue + 1] - histogram[mdbValue]);
// sequence of color in bitmap is BGR
GetRGB(colorCode, image[i*3+2], image[i*3+1], image[i*3]);
}
// write file content into fileSptr
fileSptr.reset(new char[bmpFileHdr.bfSize], std::default_delete<char[]>());
bmpFileHdr.WriteHeader(fileSptr.get());
bmpInfoHdr.WriteHeader(fileSptr.get() + 14);
memcpy(fileSptr.get() + bmpFileHdr.bfOffBits, image, bmpInfoHdr.biImageSize);
return bmpFileHdr.bfSize;
}
size_t BmpFactory::GetFile(const std::string fileName)
{
std::fstream bmpFile(fileName, std::ios::out | std::ios::binary);
size_t fileSize = 0;
if (bmpFile.good()) {
std::shared_ptr<char[]> image;
fileSize = GetFile(image);
bmpFile.write(reinterpret_cast<char*>(image.get()), fileSize);
}
return fileSize;
}
unsigned char BmpFactory::GetBiBitPerPxl() const
{
return bmpInfoHdr.biBitPerPxl;
}
unsigned BmpFactory::GetBiImageSize() const
{
return bmpInfoHdr.biImageSize;
}
unsigned BmpFactory::GetBfOffBits() const
{
return bmpFileHdr.bfOffBits;
}
unsigned BmpFactory::GetBfSize() const
{
return bmpFileHdr.bfSize;
}
void BmpFactory::SetBiBitPerPxl(const size_t bits)
{
bmpInfoHdr.biBitPerPxl = bits;
UpdateBmpHeader();
}
void BmpFactory::SetResolution(const size_t width, const size_t height)
{
bmpInfoHdr.biWidth = width;
bmpInfoHdr.biHeight = height;
UpdateBmpHeader();
}
void BmpFactory::SetBfReserved1(const size_t val)
{
bmpFileHdr.bfReserved1 = val;
}
<file_sep>#ifndef _ENCODESTRATEGY_H
#define _ENCODESTRATEGY_H
// 2017.05.30 15:33
#include "CoderInfoIO.h"
class EncodeStrategy {
public:
EncodeStrategy(CoderInfoIO *p = nullptr);
void SetCoderInfoPtr(CoderInfoIO*);
int Encode(const std::string&, const std::string&);
private:
CoderInfoIO *coderInfoPtr;
static const size_t readBlockSize = 64;
static const size_t writeBlockSize = readBlockSize * 5;
};
#endif // _ENCODESTRATEGY_H
<file_sep>#ifndef _XORCODERINFOIO_H
#define _XORCODERINFOIO_H
#include "CoderInfoIO.h"
#include "XorCoder.h"
class XorCoderInfoIO: public CoderInfoIO {
public:
XorCoderInfoIO(int i = 0);
~XorCoderInfoIO();
virtual std::istream& ReadInfo(std::istream&) override;
virtual std::ostream& WriteInfo(std::ostream&) override;
virtual std::istream& Read(std::istream&, char*, size_t) override;
virtual std::ostream& Write(std::ostream&, char*, size_t) override;
virtual size_t Gcount() const override;
virtual const Coder* GetCoder() const override;
int SetMgcNmb(int);
int GetMgcNmb() const;
private:
int mgcNmb;
size_t gcount;
XorCoder *coderPtr;
};
#endif // _XORCODERINFOIO_H
<file_sep>CXXFLAGS += -Wall -O2
LDDFLAGS += -lpthread
OBJSDIR = /tmp/HuffBmp
OBJS = ${patsubst %.cpp, ${OBJSDIR}/%.o, ${wildcard *.cpp}}
target = ${OBJSDIR}/HuffBmp.out
${target}: ${OBJSDIR} ${OBJS}
${CXX} ${CXXFLAGS} ${LDDFLAGS} ${OBJS} -o ${@}
${OBJSDIR}:
mkdir -p ${OBJSDIR}
${OBJSDIR}/Main.o: ${OBJSDIR}/%.o:%.cpp
${CXX} ${CXXFLAGS} -c ${<} -o ${@}
${OBJSDIR}/HuffmanCoder.o: ${OBJSDIR}/%.o:%.cpp %.h BinaryTree.h Coder.h
${CXX} ${CXXFLAGS} -c ${<} -o ${@}
${OBJSDIR}/HuffmanCoderInfoIO.o: ${OBJSDIR}/%.o:%.cpp %.h CoderInfoIO.h HuffmanCoder.h
${CXX} ${CXXFLAGS} -c ${<} -o ${@}
${OBJSDIR}/XorCoder.o: ${OBJSDIR}/%.o:%.cpp %.h Coder.h
${CXX} ${CXXFLAGS} -c ${<} -o ${@}
${OBJSDIR}/XorCoderInfoIO.o: ${OBJSDIR}/%.o:%.cpp %.h CoderInfoIO.h XorCoder.h
${CXX} ${CXXFLAGS} -c ${<} -o ${@}
${OBJSDIR}/BmpCommon.o: ${OBJSDIR}/%.o:%.cpp %.h
${CXX} ${CXXFLAGS} -c ${<} -o ${@}
${OBJSDIR}/EncodeStrategy.o: ${OBJSDIR}/%.o:%.cpp %.h CoderInfoIO.h Coder.h
${CXX} ${CXXFLAGS} -c ${<} -o ${@}
${OBJSDIR}/DecodeStrategy.o: ${OBJSDIR}/%.o:%.cpp %.h CoderInfoIO.h Coder.h
${CXX} ${CXXFLAGS} -c ${<} -o ${@}
${OBJSDIR}/BmpFactory.o: ${OBJSDIR}/%.o:%.cpp %.h FileFactory.h
${CXX} ${CXXFLAGS} -c ${<} -o ${@}
${OBJSDIR}/Mandelbrot.o: ${OBJSDIR}/%.o:%.cpp %.h
${CXX} ${CXXFLAGS} -c ${<} -o ${@}
${OBJSDIR}/BmpCoder.o: ${OBJSDIR}/%.o:%.cpp %.h
${CXX} ${CXXFLAGS} -c ${<} -o ${@}
${OBJSDIR}/Common.o: ${OBJSDIR}/%.o:%.cpp %.h
${CXX} ${CXXFLAGS} -c ${<} -o ${@}
.PHONY: cleanall clean
cleanall: clean
-${RM} ${target}
clean:
-${RM} ${OBJSDIR}/*.o
<file_sep>#include <fstream>
#include <memory>
#include <bitset>
#include "DecodeStrategy.h"
DecodeStrategy::DecodeStrategy(CoderInfoIO *p): coderInfoPtr(p)
{
readBlockSize = 64;
writeBlockSize = readBlockSize * 8;
}
void DecodeStrategy::SetCoderInfoPtr(CoderInfoIO *p)
{
coderInfoPtr = p;
}
int DecodeStrategy::Decode(const std::string &iFile, const std::string &oFile)
{
size_t fileSize, writedSize = 0;
std::ifstream ifs(iFile, std::fstream::binary);
std::ofstream ofs(oFile, std::fstream::binary);
if (!ifs || !ofs)
throw std::runtime_error("cannot open file!");
coderInfoPtr->Preprocess(ifs);
coderInfoPtr->ReadInfo(ifs);
fileSize = coderInfoPtr->GetFileSize();
const Coder *coderPtr = coderInfoPtr->GetCoder();
size_t gcount = readBlockSize, writeBufferIndex;
std::shared_ptr<char> readBufferSp(new char[readBlockSize]);
std::shared_ptr<char> writeBufferSp(new char[writeBlockSize]);
char *readBuffer = readBufferSp.get();
char *writeBuffer = writeBufferSp.get();
std::string originCode, plainCode;
while (gcount == readBlockSize) {
coderInfoPtr->Read(ifs, readBuffer, readBlockSize);
if (!(gcount = coderInfoPtr->Gcount()))
break;
for (size_t i = 0; i < gcount; ++i)
originCode += std::bitset<8>(readBuffer[i]).to_string();
plainCode += coderPtr->Decode(originCode);
size_t iNextByte = writeBufferIndex = 0, buffSize = plainCode.size() / 8;
if (buffSize > writeBlockSize) {
writeBlockSize = buffSize;
writeBufferSp = std::shared_ptr<char>(new char[writeBlockSize]);
writeBuffer = writeBufferSp.get();
}
while ((plainCode.size() - iNextByte) > 7) {
std::bitset<8> oneByte = std::bitset<8>(plainCode, iNextByte, 8);
const char c = static_cast<char>(oneByte.to_ulong());
writeBuffer[writeBufferIndex++] = c;
iNextByte += 8;
}
plainCode.erase(0, iNextByte);
if (fileSize && writedSize + writeBufferIndex > fileSize)
writeBufferIndex = fileSize - writedSize;
ofs.write(writeBuffer, writeBufferIndex);
writedSize += writeBufferIndex;
}
if (fileSize && writedSize != fileSize)
throw std::runtime_error("decode error(writedSize != fileSize)!");
return 0;
}
<file_sep>#ifndef _BMPFACTORY_H
#define _BMPFACTORY_H
// 2017.08.13 23:10
#include "FileFactory.h"
#include "BmpCommon.h"
class BmpFactory: public FileFactory {
public:
BmpFactory();
virtual size_t GetFile(std::shared_ptr<char[]>&) override;
//virtual size_t GetFile(const std::string, const std::ios_base::openmode) override;
virtual size_t GetFile(const std::string) override;
unsigned char GetBiBitPerPxl() const;
unsigned GetBiImageSize() const;
unsigned GetBfOffBits() const;
unsigned GetBfSize() const;
void SetBiBitPerPxl(const size_t);
void SetResolution(const size_t, const size_t);
void SetBfReserved1(const size_t);
private:
BmpFileHeader bmpFileHdr;
BmpInfoHeader bmpInfoHdr;
void UpdateBmpHeader();
};
#endif // _BMPFACTORY_H
<file_sep>#include "Common.h"
size_t CalcFileSize(std::istream &is)
{
std::streampos pos = is.tellg();
is.seekg(0, std::fstream::end);
size_t fileSize = is.tellg();
is.seekg(pos);
return fileSize;
}
<file_sep>#ifndef _CODERINFOIO_H
#define _CODERINFOIO_H
#include <iostream>
#include "Coder.h"
enum PreprcsRslt {
RSLTOK,
RSLTERROR,
};
class CoderInfoIO {
public:
virtual std::istream& ReadInfo(std::istream&) = 0;
virtual std::ostream& WriteInfo(std::ostream&) = 0;
virtual std::istream& Read(std::istream&, char*, size_t) = 0;
virtual std::ostream& Write(std::ostream&, char*, size_t) = 0;
virtual size_t Gcount() const = 0;
virtual size_t GetFileSize() const {
return 0;
}
// for decode, check only instream
virtual enum PreprcsRslt Preprocess(std::istream&) {
return RSLTOK;
}
// for encode, check both instream and outstream
virtual enum PreprcsRslt Preprocess(std::istream&, std::iostream&) {
return RSLTOK;
}
virtual const Coder* GetCoder() const = 0;
};
#endif // _CODERINFOIO_H
<file_sep>#ifndef _CODER_H
#define _CODER_H
#include <string>
class Coder {
public:
virtual std::string Encode(std::string&) const = 0;
virtual std::string Decode(std::string&) const = 0;
};
#endif // _CODER_H
<file_sep>#ifndef _BMPCOMMON_H
#define _BMPCOMMON_H
// 2017.08.05 14:05
#include <cstdint>
#include <iostream>
struct BmpFileHeader {
uint16_t bfType; // BM(0x4D42)
uint32_t bfSize; // size of whole bmp file
uint16_t bfReserved1; // 0
uint16_t bfReserved2; // 0
uint32_t bfOffBits; // 14+40+sizeof(palette)
BmpFileHeader();
void ReadHeader(std::istream&);
void ReadHeader(const char*);
void WriteHeader(std::ostream&);
void WriteHeader(char*);
};
struct BmpInfoHeader {
uint32_t biSize; // size of BmpInfoHeader(40)
int32_t biWidth; // width in pixel
int32_t biHeight; // height in pixel
uint16_t biPlanes; // fixed value(1)
uint16_t biBitPerPxl; // bit per pixel(1| 16| 24| 32)
uint32_t biCompression; // compression method:
// 0 - no compression(BI_RGB)
// 1 - RLE 8(BI_RLE8)
// 2 - RLE 4(BI_RLE4)
// 3 - Bitfields(BI_BITFIELDS)
uint32_t biImageSize; // ((biWidth*biBitPerPxl/8+3)/4*4 * biHeight)
// maybe is 0 if compression is BI_RGB
int32_t biXPxlsPerMeter; // pixels per meter on X-axis
int32_t biYPxlsPerMeter; // pixels per meter on Y-axis
uint32_t biClrUsed; // number of colors in using actually
// (0 means 2^biBitPerPxl)
uint32_t biClrImportant; // number of important colrs
// (0 means all important)
BmpInfoHeader();
void ReadHeader(std::istream&);
void ReadHeader(const char*);
void WriteHeader(std::ostream&);
void WriteHeader(char*);
uint32_t GetBiImageSize();
};
std::ostream& operator<<(std::ostream&, const BmpFileHeader&);
std::ostream& operator<<(std::ostream&, const BmpInfoHeader&);
#endif // _BMPCOMMON_H
<file_sep>#ifndef _FILEFACTORY_H
#define _FILEFACTORY_H
// 2017.08.13 22:10
#include <fstream>
#include <memory>
class FileFactory {
public:
virtual size_t GetFile(std::shared_ptr<char[]>&) = 0;
//virtual size_t GetFile(const std::string fileName,
// const std::ios_base::openmode mode) = 0;
virtual size_t GetFile(const std::string fileName) = 0;
};
#endif // _FILEFACTORY_H
<file_sep>#include "XorCoderInfoIO.h"
XorCoderInfoIO::XorCoderInfoIO(int i): coderPtr(new XorCoder(i))
{
SetMgcNmb(i);
}
XorCoderInfoIO::~XorCoderInfoIO()
{
if (coderPtr)
delete coderPtr;
coderPtr = nullptr;
}
std::istream& XorCoderInfoIO::ReadInfo(std::istream &is)
{
is.read(reinterpret_cast<char*>(&mgcNmb), sizeof(mgcNmb));
coderPtr->SetMgcNmb(mgcNmb);
return is;
}
std::ostream& XorCoderInfoIO::WriteInfo(std::ostream &os)
{
os.write(reinterpret_cast<char*>(&mgcNmb), sizeof(mgcNmb));
return os;
}
int XorCoderInfoIO::SetMgcNmb(int i)
{
if (coderPtr) {
mgcNmb = coderPtr->SetMgcNmb(i);
coderPtr->ResetVecMgcNmbIndex();
}
return mgcNmb;
}
int XorCoderInfoIO::GetMgcNmb() const
{
return mgcNmb;
}
std::istream& XorCoderInfoIO::Read(std::istream &is, char *buf, size_t size)
{
is.read(buf, size);
gcount = is.gcount();
return is;
}
std::ostream& XorCoderInfoIO::Write(std::ostream &os, char *buf, size_t size)
{
os.write(buf, size);
return os;
}
size_t XorCoderInfoIO::Gcount() const
{
return gcount;
}
const Coder* XorCoderInfoIO::GetCoder() const
{
return coderPtr;
}
<file_sep>/* 2017.05.12 09:04
*/
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "EncodeStrategy.h"
#include "DecodeStrategy.h"
#include "HuffmanCoderInfoIO.h"
#include "XorCoderInfoIO.h"
#include "BmpFactory.h"
#include "BmpCoder.h"
#include "Common.h"
using namespace std;
void TestXor()
{
XorCoderInfoIO xorCoder;
EncodeStrategy encoderStg(&xorCoder);
DecodeStrategy decoderStg(&xorCoder);
encoderStg.Encode("/tmp/tmp", "/tmp/tmp.cipher");
decoderStg.Decode("/tmp/tmp.cipher", "/tmp/tmp.plain");
system("md5sum /tmp/tmp /tmp/tmp.plain");
}
void TestHuff()
{
HuffmanCoderInfoIO huffmanCoder;
EncodeStrategy encoderStg(&huffmanCoder);
DecodeStrategy decoderStg(&huffmanCoder);
encoderStg.Encode("/tmp/tmp", "/tmp/tmp.cipher");
decoderStg.Decode("/tmp/tmp.cipher", "/tmp/tmp.plain");
system("md5sum /tmp/tmp /tmp/tmp.plain");
}
void TestBmpFactory()
{
std::string bmpFileName("/tmp/tmp.bmp");
BmpFactory bmp;
bmp.GetFile(bmpFileName);
}
void TestBmpCoder()
{
BmpCoder bmpCoder;
std::string fileForEncode = "/tmp/tmp";
std::string fileForDecode = fileForEncode + ".plain";
std::string fileForBmp = fileForEncode + ".bmp";
std::shared_ptr<char[]> bmpSptr;
std::ifstream ifs(fileForEncode, std::ios::binary);
std::ofstream ofsPlain(fileForDecode, std::ios::binary);
std::ofstream ofsBmp(fileForBmp, std::ios::binary);
unsigned fileSize = bmpCoder.Encode(ifs, bmpSptr);
ofsBmp.write(bmpSptr.get(), fileSize);
bmpCoder.Decode(bmpSptr, ofsPlain);
ofsPlain.close();
system("md5sum /tmp/tmp /tmp/tmp.plain");
}
void ShowHelp(std::ostream &os)
{
os << "show bmp file header and info header" << endl;
}
void ShowBmpInfo(std::ostream &os, const BmpFileHeader &bmpFileHdr, const
BmpInfoHeader &bmpInfoHdr)
{
os << bmpFileHdr << bmpInfoHdr;
}
bool ReadBmpInfo(std::string bmpFileName, size_t &length,
BmpFileHeader &bmpFileHdr, BmpInfoHeader &bmpInfoHdr)
{
std::fstream bmpFile(bmpFileName, ios::in | ios::binary);
if (!bmpFile.good())
return false;
length = CalcFileSize(bmpFile);
bmpFileHdr.ReadHeader(bmpFile);
bmpInfoHdr.ReadHeader(bmpFile);
return true;
}
int main(int argc, char **argv)
{
if (argc < 2)
return 1;
size_t length;
BmpFileHeader bmpFileHdr;
BmpInfoHeader bmpInfoHdr;
std::string argv1(argv[1]);
if (!ReadBmpInfo(argv1, length, bmpFileHdr, bmpInfoHdr)) {
string errorMsg = "open " + argv1 + " failed!";
cout << errorMsg << endl;
return 1;
}
switch (argc) {
case 2:
ShowBmpInfo(cout, bmpFileHdr, bmpInfoHdr);
break;
default:
ShowHelp(cout);
break;
}
return 0;
}
<file_sep>#ifndef _HUFFMANCODER_H
#define _HUFFMANCODER_H
#include <map>
#include <memory>
#include <utility>
#include "Coder.h"
#include "BinaryTree.h"
class HuffmanCoder: public Coder {
public:
using Pair_CU = std::pair<char, unsigned>;
using HuffTreeNode = BinaryTreeNode<Pair_CU>;
using HuffTreeNodePtr = std::shared_ptr<HuffTreeNode>;
static const char CODE_LCHILD = '0';
static const char CODE_RCHILD = '1';
HuffmanCoder(const HuffmanCoder&);
HuffmanCoder(HuffmanCoder&&);
HuffmanCoder(const std::map<char, unsigned>&);
HuffmanCoder(const std::string&, const std::vector<Pair_CU>&);
virtual ~HuffmanCoder();
virtual std::string Encode(std::string&) const override;
virtual std::string Decode(std::string&) const override;
HuffmanCoder& operator=(const HuffmanCoder&);
HuffmanCoder& operator=(HuffmanCoder&&);
void SetKeyWeight(const std::map<char, unsigned>&);
void SetHuffTreeStruct(const std::string&, const std::vector<Pair_CU>&);
std::string GetHuffTreeStruct() const;
std::vector<Pair_CU> GetHuffTreeLeafData() const;
private:
BinaryTree<Pair_CU> huffTree;
std::map<char, unsigned> keyWeight;
std::map<char, std::string> mapTable;
HuffTreeNodePtr BuildTree() const;
static bool SortByWeightAsc(
const HuffTreeNodePtr&, const HuffTreeNodePtr&);
static HuffTreeNodePtr Combine2Node(
const HuffTreeNodePtr&, const HuffTreeNodePtr&);
std::map<char, std::string>::size_type BuildMapTable(const HuffTreeNodePtr&);
};
#endif // _HUFFMANCODER_H
<file_sep>#ifndef _BINARYTREE_H
#define _BINARYTREE_H
#include <memory>
#include <vector>
#include <list>
#include <utility>
#include <functional>
// BinaryTreeNode
template <typename DT>
class BinaryTreeNode
{
public:
using NodePtr = std::shared_ptr<BinaryTreeNode<DT>>;
BinaryTreeNode();
BinaryTreeNode(const DT&, const NodePtr &l = nullptr, const NodePtr &r = nullptr);
DT data;
NodePtr lchild;
NodePtr rchild;
};
template <typename DT>
BinaryTreeNode<DT>::BinaryTreeNode(): lchild(nullptr), rchild(nullptr)
{
}
template <typename DT>
BinaryTreeNode<DT>::BinaryTreeNode(const DT &d, const NodePtr &l, const NodePtr &r)
: data(d), lchild(l), rchild(r)
{
}
// BinaryTree
template <typename DT>
class BinaryTree
{
public:
using Pred4TreeNodePtr = std::function
<bool(const typename BinaryTreeNode<DT>::NodePtr&)>;
BinaryTree(const typename BinaryTreeNode<DT>::NodePtr &p = nullptr);
const typename BinaryTreeNode<DT>::NodePtr GetRoot() const;
void SetRoot(typename BinaryTreeNode<DT>::NodePtr&);
typename BinaryTreeNode<DT>::NodePtr SetTreeStruct(
const std::string&, const std::vector<DT>&, Pred4TreeNodePtr);
std::string GetTreeStruct() const;
std::vector<DT> GetLeafData() const;
static bool IsLeaf(const typename BinaryTreeNode<DT>::NodePtr&);
private:
typename BinaryTreeNode<DT>::NodePtr root;
static const char CODE_CHLDNULL = '0';
static const char CODE_CHLDEXIST = '1';
std::string GetTreeStructPreOrder() const;
std::string GetTreeStructLvlOrder() const;
typename BinaryTreeNode<DT>::NodePtr SetTreeStructPreOrder(
const std::string&, const std::vector<DT>&, Pred4TreeNodePtr);
typename BinaryTreeNode<DT>::NodePtr SetTreeStructLvlOrder(
const std::string&, const std::vector<DT>&, Pred4TreeNodePtr);
std::vector<DT> GetNodeDataPreOrder(Pred4TreeNodePtr) const;
std::vector<DT> GetNodeDataLvlOrder(Pred4TreeNodePtr) const;
};
template <typename DT>
BinaryTree<DT>::BinaryTree(const typename BinaryTreeNode<DT>::NodePtr &p)
: root(p)
{
}
template <typename DT>
const typename BinaryTreeNode<DT>::NodePtr BinaryTree<DT>::GetRoot() const
{
return root;
}
template <typename DT>
void BinaryTree<DT>::SetRoot(typename BinaryTreeNode<DT>::NodePtr &nodePtr)
{
root = nodePtr;
}
template <typename DT>
std::string BinaryTree<DT>::GetTreeStruct() const
{
return (root == nullptr) ? "" : GetTreeStructLvlOrder();
}
template <typename DT>
typename BinaryTreeNode<DT>::NodePtr BinaryTree<DT>::SetTreeStruct(
const std::string& treeStruct,
const std::vector<DT> &vecData,
Pred4TreeNodePtr pred)
{
return SetTreeStructLvlOrder(treeStruct, vecData, pred);
}
template <typename DT>
std::string BinaryTree<DT>::GetTreeStructPreOrder() const
{
std::string treeStruct = "";
std::list<std::pair<decltype(root), unsigned char>> nodeStack{{root, 0}};
typename decltype(nodeStack)::reverse_iterator nodeStackIt;
while (!nodeStack.empty()) {
nodeStackIt = nodeStack.rbegin();
switch (nodeStackIt->second) {
case 0:
++nodeStackIt->second;
treeStruct += (nullptr == nodeStackIt->first->lchild) ?
CODE_CHLDNULL : CODE_CHLDEXIST;
nodeStack.push_back({nodeStackIt->first->lchild, 0});
break;
case 1:
++nodeStackIt->second;
treeStruct += (nullptr == nodeStackIt->first->rchild) ?
CODE_CHLDNULL : CODE_CHLDEXIST;
nodeStack.push_back({nodeStackIt->first->rchild, 0});
break;
case 2:
nodeStack.pop_back();
break;
}
if (nodeStack.size() > 0 && nullptr == (nodeStack.rbegin()->first))
nodeStack.pop_back();
}
return treeStruct;
}
template <typename DT>
std::string BinaryTree<DT>::GetTreeStructLvlOrder() const
{
std::string treeStruct = "";
std::list<std::pair<decltype(root), unsigned char>> nodeStack{{root, 0}};
typename decltype(nodeStack)::iterator nodeStackIt;
while (!nodeStack.empty()) {
nodeStackIt = nodeStack.begin();
switch (nodeStackIt->second) {
case 0:
++nodeStackIt->second;
treeStruct += (nullptr == nodeStackIt->first->lchild) ?
CODE_CHLDNULL : CODE_CHLDEXIST;
nodeStack.push_back({nodeStackIt->first->lchild, 0});
break;
case 1:
++nodeStackIt->second;
treeStruct += (nullptr == nodeStackIt->first->rchild) ?
CODE_CHLDNULL : CODE_CHLDEXIST;
nodeStack.push_back({nodeStackIt->first->rchild, 0});
break;
case 2:
nodeStack.pop_front();
break;
}
if (nodeStack.size() > 0 && nullptr == (nodeStack.rbegin()->first))
nodeStack.pop_back();
}
return treeStruct;
}
template <typename DT>
typename BinaryTreeNode<DT>::NodePtr BinaryTree<DT>::SetTreeStructPreOrder(
const std::string &treeStruct,
const std::vector<DT> &vecData,
Pred4TreeNodePtr pred)
{
DT rootData;
std::string::size_type indexStr = 0;
typename std::vector<DT>::size_type indexVec = 0;
root = std::make_shared<BinaryTreeNode<DT>>(rootData);
std::list<std::pair<decltype(root), unsigned char>> nodeStack{{root, 0}};
typename decltype(nodeStack)::reverse_iterator nodeStackIt;
while (!nodeStack.empty()) {
nodeStackIt = nodeStack.rbegin();
switch (nodeStackIt->second) {
case 0:
++nodeStackIt->second;
if (indexStr >= treeStruct.size())
throw std::out_of_range("bad treeStruct");
nodeStackIt->first->lchild =
(CODE_CHLDNULL == treeStruct[indexStr++]) ?
nullptr :
std::make_shared<BinaryTreeNode<DT>>();
nodeStack.push_back({nodeStackIt->first->lchild, 0});
break;
case 1:
++nodeStackIt->second;
if (indexStr >= treeStruct.size())
throw std::out_of_range("bad treeStruct");
nodeStackIt->first->rchild =
(CODE_CHLDNULL == treeStruct[indexStr++]) ?
nullptr :
std::make_shared<BinaryTreeNode<DT>>();
nodeStack.push_back({nodeStackIt->first->rchild, 0});
break;
case 2:
if (pred(nodeStackIt->first)) {
if (indexVec >= vecData.size())
throw std::out_of_range("node data not enough");
else
nodeStackIt->first->data = vecData[indexVec++];
}
nodeStack.pop_back();
break;
}
if (nodeStack.size() > 0 && nullptr == (nodeStack.rbegin()->first))
nodeStack.pop_back();
}
if (indexStr < treeStruct.size() || indexVec < vecData.size())
root = nullptr;
return root;
}
template <typename DT>
typename BinaryTreeNode<DT>::NodePtr BinaryTree<DT>::SetTreeStructLvlOrder(
const std::string &treeStruct,
const std::vector<DT> &vecData,
Pred4TreeNodePtr pred)
{
DT rootData;
std::string::size_type indexStr = 0;
typename std::vector<DT>::size_type indexVec = 0;
root = std::make_shared<BinaryTreeNode<DT>>(rootData);
std::list<std::pair<decltype(root), unsigned char>> nodeStack{{root, 0}};
typename decltype(nodeStack)::iterator nodeStackIt;
while (!nodeStack.empty()) {
nodeStackIt = nodeStack.begin();
switch (nodeStackIt->second) {
case 0:
++nodeStackIt->second;
if (indexStr >= treeStruct.size())
throw std::out_of_range("bad treeStruct");
nodeStackIt->first->lchild =
(CODE_CHLDNULL == treeStruct[indexStr++]) ?
nullptr :
std::make_shared<BinaryTreeNode<DT>>();
nodeStack.push_back({nodeStackIt->first->lchild, 0});
break;
case 1:
++nodeStackIt->second;
if (indexStr >= treeStruct.size())
throw std::out_of_range("bad treeStruct");
nodeStackIt->first->rchild =
(CODE_CHLDNULL == treeStruct[indexStr++]) ?
nullptr :
std::make_shared<BinaryTreeNode<DT>>();
nodeStack.push_back({nodeStackIt->first->rchild, 0});
break;
case 2:
if (pred(nodeStackIt->first)) {
if (indexVec >= vecData.size())
throw std::out_of_range("node data not enough");
else
nodeStackIt->first->data = vecData[indexVec++];
}
nodeStack.pop_front();
break;
}
if (nodeStack.size() > 0 && nullptr == (nodeStack.rbegin()->first))
nodeStack.pop_back();
}
if (indexStr < treeStruct.size() || indexVec < vecData.size())
root = nullptr;
return root;
}
template <typename DT>
std::vector<DT> BinaryTree<DT>::GetLeafData() const
{
return GetNodeDataLvlOrder(IsLeaf);
}
template <typename DT>
std::vector<DT> BinaryTree<DT>::GetNodeDataPreOrder(Pred4TreeNodePtr pred) const
{
std::vector<DT> vecData;
std::list<std::pair<decltype(root), unsigned char>> nodeStack{{root, 0}};
typename decltype(nodeStack)::reverse_iterator nodeStackIt;
while (!nodeStack.empty()) {
nodeStackIt = nodeStack.rbegin();
switch (nodeStackIt->second) {
case 0:
++nodeStackIt->second;
nodeStack.push_back({nodeStackIt->first->lchild, 0});
break;
case 1:
++nodeStackIt->second;
nodeStack.push_back({nodeStackIt->first->rchild, 0});
break;
case 2:
if (pred(nodeStackIt->first))
vecData.push_back(nodeStackIt->first->data);
nodeStack.pop_back();
break;
}
if (nodeStack.size() > 0 && nullptr == (nodeStack.rbegin()->first))
nodeStack.pop_back();
}
return vecData;
}
template <typename DT>
std::vector<DT> BinaryTree<DT>::GetNodeDataLvlOrder(Pred4TreeNodePtr pred) const
{
std::vector<DT> vecData;
std::list<std::pair<decltype(root), unsigned char>> nodeStack{{root, 0}};
typename decltype(nodeStack)::iterator nodeStackIt;
while (!nodeStack.empty()) {
nodeStackIt = nodeStack.begin();
switch (nodeStackIt->second) {
case 0:
++nodeStackIt->second;
nodeStack.push_back({nodeStackIt->first->lchild, 0});
break;
case 1:
++nodeStackIt->second;
nodeStack.push_back({nodeStackIt->first->rchild, 0});
break;
case 2:
if (pred(nodeStackIt->first))
vecData.push_back(nodeStackIt->first->data);
nodeStack.pop_front();
break;
}
if (nodeStack.size() > 0 && nullptr == (nodeStack.rbegin()->first))
nodeStack.pop_back();
}
return vecData;
}
template <typename DT>
bool BinaryTree<DT>::IsLeaf(const typename BinaryTreeNode<DT>::NodePtr &node)
{
return (node != nullptr && node->lchild == nullptr && node->rchild == nullptr);
}
#endif // _BINARYTREE_H
<file_sep>#include <algorithm>
#include <list>
#include <bitset>
#include "HuffmanCoder.h"
HuffmanCoder::HuffmanCoder(const HuffmanCoder &coder)
{
huffTree = coder.huffTree;
keyWeight = coder.keyWeight;
mapTable = coder.mapTable;
}
HuffmanCoder::HuffmanCoder(HuffmanCoder &&coder)
{
huffTree = std::move(coder.huffTree);
keyWeight = std::move(coder.keyWeight);
mapTable = std::move(coder.mapTable);
}
HuffmanCoder::HuffmanCoder(const std::map<char, unsigned> &m): keyWeight(m)
{
HuffTreeNodePtr root = BuildTree();
huffTree.SetRoot(root);
BuildMapTable(huffTree.GetRoot());
}
HuffmanCoder::HuffmanCoder(
const std::string &treeStruct, const std::vector<Pair_CU> &leafData)
{
huffTree.SetTreeStruct(treeStruct, leafData, huffTree.IsLeaf);
BuildMapTable(huffTree.GetRoot());
}
HuffmanCoder::~HuffmanCoder()
{
}
HuffmanCoder& HuffmanCoder::operator=(const HuffmanCoder &coder)
{
huffTree = coder.huffTree;
keyWeight = coder.keyWeight;
mapTable = coder.mapTable;
return *this;
}
HuffmanCoder& HuffmanCoder::operator=(HuffmanCoder &&coder)
{
huffTree = std::move(coder.huffTree);
keyWeight = std::move(coder.keyWeight);
mapTable = std::move(coder.mapTable);
return *this;
}
bool HuffmanCoder::SortByWeightAsc(const HuffTreeNodePtr &lhs,
const HuffTreeNodePtr &rhs)
{
return lhs->data.second < rhs->data.second;
}
HuffmanCoder::HuffTreeNodePtr HuffmanCoder::BuildTree() const
{
std::list<HuffmanCoder::HuffTreeNodePtr> lstNodePtr;
// cast 'pair<char, unsigned>' into 'HuffTreeNode'
for (auto const &pairValWei : keyWeight) {
lstNodePtr.push_back(std::make_shared<HuffTreeNode>(pairValWei));
}
lstNodePtr.sort(SortByWeightAsc);
HuffTreeNodePtr newNode;
decltype(lstNodePtr)::const_iterator lstIt1, lstIt2;
// if only one keyWord, copy it to build tree
if (1 == lstNodePtr.size())
lstNodePtr.push_back(*lstNodePtr.begin());
while (1 < lstNodePtr.size()) {
// merge first two node in 'newNode' as lchild and rchild
lstIt1 = lstIt2 = lstNodePtr.begin();
++lstIt2;
newNode = Combine2Node(*lstIt1, *lstIt2);
// delete first two node in list
lstNodePtr.erase(lstNodePtr.begin());
lstNodePtr.erase(lstNodePtr.begin());
// find place in list to insert 'newNode'
lstIt1 = find_if(lstNodePtr.begin(), lstNodePtr.end(),
[newNode] (const HuffTreeNodePtr &p) {
return p->data.second > newNode->data.second;
});
lstNodePtr.insert(lstIt1, newNode);
}
return *lstNodePtr.begin();
}
HuffmanCoder::HuffTreeNodePtr HuffmanCoder::Combine2Node(
const HuffmanCoder::HuffTreeNodePtr &lnode,
const HuffmanCoder::HuffTreeNodePtr &rnode)
{
return std::make_shared<HuffTreeNode>(
Pair_CU({' ', lnode->data.second + rnode->data.second}),
lnode, rnode);
}
std::map<char, std::string>::size_type HuffmanCoder::BuildMapTable(const HuffTreeNodePtr &root)
{
std::string codeStr = "";
std::list<std::pair<decltype(root), unsigned char>> nodeStack{{root, 0}};
typename decltype(nodeStack)::reverse_iterator nodeStackIt;
while (!nodeStack.empty()) {
nodeStackIt = nodeStack.rbegin();
switch (nodeStackIt->second) {
case 0:
++nodeStackIt->second;
if (nullptr != nodeStackIt->first->lchild) {
nodeStack.push_back({nodeStackIt->first->lchild, 0});
codeStr += CODE_LCHILD;
}
break;
case 1:
++nodeStackIt->second;
if (nullptr != nodeStackIt->first->rchild) {
nodeStack.push_back({nodeStackIt->first->rchild, 0});
codeStr += CODE_RCHILD;
}
break;
case 2:
if (nodeStackIt->first->lchild == nullptr &&
nodeStackIt->first->rchild==nullptr) {
char c = nodeStackIt->first->data.first;
mapTable[c] = codeStr;
}
nodeStack.pop_back();
codeStr.pop_back();
break;
}
}
return mapTable.size();
}
std::string HuffmanCoder::Encode(std::string &originCode) const
{
std::string result = "";
size_t iNextByte = 0;
while ((originCode.size() - iNextByte) > 7) {
// bit code to 'char'
std::bitset<8> oneByte =
std::bitset<8>(originCode, iNextByte, 8, CODE_LCHILD, CODE_RCHILD);
const char key = static_cast<char>(oneByte.to_ulong());
//result += mapTable[c]; // invalid, if map[k] non-exist it will be inserted,
// but current func is 'const'
decltype(mapTable)::const_iterator itMapTable = mapTable.find(key);
if (itMapTable == mapTable.end())
throw std::out_of_range("no value for key: " + key);
result += itMapTable->second;
iNextByte += 8;
}
originCode.erase(0, iNextByte);
return result;
}
std::string HuffmanCoder::Decode(std::string &originStr) const
{
std::string result = "";
const HuffTreeNodePtr root = huffTree.GetRoot();
const HuffTreeNodePtr *nodePtr = &root;
std::string::const_iterator itOriginStr = originStr.begin();
std::string::const_iterator itLastCodeEnd = itOriginStr;
while(itOriginStr != originStr.end()) {
switch (*itOriginStr) {
case CODE_LCHILD:
nodePtr = &(*nodePtr)->lchild;
break;
case CODE_RCHILD:
nodePtr = &(*nodePtr)->rchild;
break;
default:
throw std::out_of_range("unknown code: " + *itOriginStr);
}
if ((*nodePtr)->lchild == nullptr && (*nodePtr)->rchild == nullptr) {
// leaf of huffmanTree, get data and reset 'nodePtr'
result += std::bitset<8>((*nodePtr)->data.first).to_string();
nodePtr = &root;
// record last end of completed code
itLastCodeEnd = itOriginStr;
}
++itOriginStr;
}
// return the rest of originStr
if (itLastCodeEnd < originStr.end())
originStr.erase(originStr.begin(), itLastCodeEnd + 1);
return result;
}
std::string HuffmanCoder::GetHuffTreeStruct() const
{
return huffTree.GetTreeStruct();
}
std::vector<HuffmanCoder::Pair_CU> HuffmanCoder::GetHuffTreeLeafData() const
{
return huffTree.GetLeafData();
}
void HuffmanCoder::SetKeyWeight(const std::map<char, unsigned> &m)
{
keyWeight = m;
HuffTreeNodePtr root = BuildTree();
huffTree.SetRoot(root);
BuildMapTable(huffTree.GetRoot());
}
void HuffmanCoder::SetHuffTreeStruct(
const std::string &treeStruct, const std::vector<Pair_CU> &leafData)
{
huffTree.SetTreeStruct(treeStruct, leafData, huffTree.IsLeaf);
BuildMapTable(huffTree.GetRoot());
}
<file_sep>#ifndef _MANDELBROT_H
#define _MANDELBROT_H
// 2017.08.23 19:17
#include <memory>
class Mandelbrot {
public:
Mandelbrot();
std::shared_ptr<double> GetMdbValMap(const size_t, const size_t);
size_t GetIteration() const;
double GetZoomFactor() const;
void SetZoomFactor(double);
private:
double centerX;
double centerY;
double zoomFactor;
double radius;
size_t iteration;
const unsigned char threadNum = 4;
const unsigned blockSize = 1920 * 1080 / 4;
static double GetMdbVal(double, double, double, size_t);
static void GetMdbValMapThread(const Mandelbrot&,
std::shared_ptr<double>, size_t width, size_t height,
size_t hStart, size_t hEnd);
};
#endif // _MANDELBROT_H
<file_sep>#include <bitset>
#include <algorithm>
#include <fstream>
#include "HuffmanCoderInfoIO.h"
#include "Common.h"
// static member need not only declaration with 'static' but also a definition
// without 'static'
std::allocator<HuffmanCoder> HuffmanCoderInfoIO::alctHuffmanCoder;
HuffmanCoderInfoIO::HuffmanCoderInfoIO(): coderPtr(nullptr)
{
}
HuffmanCoderInfoIO::HuffmanCoderInfoIO(const HuffmanCoderInfoIO &coderInfo)
: leafNodeNmb(coderInfo.leafNodeNmb), treeNodeNmb(coderInfo.treeNodeNmb),
treeStruct(coderInfo.treeStruct), leafNodesData(coderInfo.leafNodesData),
keyWeight(coderInfo.keyWeight)
{
if (coderInfo.coderPtr) {
coderPtr = alctHuffmanCoder.allocate(1);
alctHuffmanCoder.construct(coderPtr, *coderInfo.coderPtr);
} else {
coderPtr = nullptr;
}
}
HuffmanCoderInfoIO::HuffmanCoderInfoIO(HuffmanCoderInfoIO &&coderInfo)
: leafNodeNmb(std::move(coderInfo.leafNodeNmb)),
treeNodeNmb(std::move(coderInfo.treeNodeNmb)),
treeStruct(std::move(coderInfo.treeStruct)),
leafNodesData(std::move(coderInfo.leafNodesData)),
keyWeight(std::move(coderInfo.keyWeight))
{
coderPtr = coderInfo.coderPtr;
coderInfo.coderPtr = nullptr;
}
HuffmanCoderInfoIO::HuffmanCoderInfoIO(const std::string &ts,
const std::vector<HuffmanCoder::Pair_CU> &nodesData)
: coderPtr(nullptr)
{
SetTreeInfo(ts, nodesData);
}
HuffmanCoderInfoIO::~HuffmanCoderInfoIO()
{
if (coderPtr) {
alctHuffmanCoder.destroy(coderPtr);
alctHuffmanCoder.deallocate(coderPtr, 1);
}
coderPtr = nullptr;
}
HuffmanCoderInfoIO& HuffmanCoderInfoIO::operator=(const HuffmanCoderInfoIO &coderInfo)
{
leafNodeNmb = coderInfo.leafNodeNmb;
treeNodeNmb = coderInfo.treeNodeNmb;
treeStruct = coderInfo.treeStruct;
leafNodesData = coderInfo.leafNodesData;
keyWeight = coderInfo.keyWeight;
if (coderPtr) {
alctHuffmanCoder.destroy(coderPtr);
coderPtr = nullptr;
}
if (coderInfo.coderPtr) {
alctHuffmanCoder.allocate(1);
alctHuffmanCoder.construct(coderPtr, *coderInfo.coderPtr);
}
return *this;
}
HuffmanCoderInfoIO& HuffmanCoderInfoIO::operator=(HuffmanCoderInfoIO &&coderInfo)
{
leafNodeNmb = std::move(coderInfo.leafNodeNmb);
treeNodeNmb = std::move(coderInfo.treeNodeNmb);
treeStruct = std::move(coderInfo.treeStruct);
leafNodesData = std::move(coderInfo.leafNodesData);
keyWeight = std::move(coderInfo.keyWeight);
if (coderPtr) {
alctHuffmanCoder.destroy(coderPtr);
alctHuffmanCoder.deallocate(coderPtr, 1);
}
coderPtr = coderInfo.coderPtr;
coderInfo.coderPtr = nullptr;
return *this;
}
std::istream& HuffmanCoderInfoIO::ReadInfo(std::istream &is)
{
size_t leafNodeNmb, treeNodeNmb, treeStructBufSize, i = 0;
is.read(reinterpret_cast<char*>(&leafNodeNmb), sizeof(leafNodeNmb));
treeNodeNmb = 2 * leafNodeNmb - 1;
treeStructBufSize = (treeNodeNmb + 7) / 8;
std::shared_ptr<char> bufferSptr(new char[leafNodeNmb + treeStructBufSize]);
char *buffer = bufferSptr.get();
is.read(buffer, leafNodeNmb + treeStructBufSize);
if (is.gcount() < static_cast<std::streamsize>(leafNodeNmb + treeStructBufSize))
return is;
std::string treeStruct;
std::vector<HuffmanCoder::Pair_CU> leafNodesData;
char *leafDataBuff = buffer, *treeStructBuff = buffer + leafNodeNmb;
while (i < treeStructBufSize) {
treeStruct += std::bitset<8>(treeStructBuff[i]).to_string();
leafNodesData.push_back({leafDataBuff[i++], 0});
}
while (i < leafNodeNmb)
leafNodesData.push_back({leafDataBuff[i++], 0});
treeStruct.erase(treeNodeNmb);
// copy single bit into double bit to describe one tree node
std::string::iterator itTreeStruct = treeStruct.begin();
while (itTreeStruct < treeStruct.end()) {
itTreeStruct = treeStruct.insert(itTreeStruct+1, *itTreeStruct);
++itTreeStruct;
}
SetTreeInfo(treeStruct, leafNodesData);
return is;
}
std::ostream& HuffmanCoderInfoIO::WriteInfo(std::ostream &os)
{
// shrink double bit into single bit to describe one tree node
std::string treeStructStr;
for (size_t i = 0; i < treeStruct.size() / 2; ++i)
treeStructStr += treeStruct[2 * i];
/* append '0' to fill up 8 bit */
size_t extra0Len = 8 - treeStructStr.size() % 8;
treeStructStr += std::string(extra0Len, '0');
size_t treeStructBufSize = (treeNodeNmb + 7) / 8, i = 0;
std::shared_ptr<char> bufferSptr(new char[leafNodeNmb + treeStructBufSize]);
char *buffer = bufferSptr.get();
char *leafDataBuff = buffer, *treeStructBuff = buffer + leafNodeNmb;
while (i < treeStructBufSize) {
std::bitset<8> byte(treeStructStr, i*8, i*8+8);
*treeStructBuff++ = byte.to_ulong();
*leafDataBuff++ = leafNodesData[i++].first;
}
while (i < leafNodeNmb)
*leafDataBuff++ = leafNodesData[i++].first;
os.write(reinterpret_cast<char*>(&leafNodeNmb), sizeof(leafNodeNmb));
os.write(buffer, leafNodeNmb + treeStructBufSize);
return os;
}
enum PreprcsRslt HuffmanCoderInfoIO::Preprocess(std::istream &is)
{
is.read(reinterpret_cast<char*>(&fileSize), sizeof(fileSize));
return RSLTOK;
}
enum PreprcsRslt HuffmanCoderInfoIO::Preprocess(std::istream &is, std::iostream &os)
{
fileSize = CalcFileSize(is);
os.write(reinterpret_cast<char*>(&fileSize), sizeof(fileSize));
StatisticKeyWeight(is);
return RSLTOK;
}
bool HuffmanCoderInfoIO::SetTreeStruct(const std::string &ts)
{
bool setOk = false;
if (CheckTreeStruct(ts)) {
treeStruct = ts;
treeNodeNmb = treeStruct.size() / 2;
leafNodeNmb = (treeNodeNmb + 1) / 2;
setOk = true;
}
return setOk;
}
std::string HuffmanCoderInfoIO::GetTreeStruct() const
{
return treeStruct;
}
bool HuffmanCoderInfoIO::SetLeafNodeData(
const std::vector<HuffmanCoder::Pair_CU> &nodesData)
{
bool setOk = true;
if (nodesData.size() == leafNodeNmb) {
leafNodesData = nodesData;
} else {
setOk = false;
leafNodesData.clear();
treeStruct.clear();
leafNodeNmb = treeNodeNmb = 0;
alctHuffmanCoder.destroy(coderPtr);
alctHuffmanCoder.deallocate(coderPtr, 1);
coderPtr = nullptr;
}
return setOk;
}
std::vector<HuffmanCoder::Pair_CU> HuffmanCoderInfoIO::GetLeafNodeData() const
{
return leafNodesData;
}
bool HuffmanCoderInfoIO::CheckTreeStruct(const std::string &ts) const
{
bool tsOk = true;
if (1 == ts.size() % 2)
tsOk = false;
for (size_t i = 0; tsOk && i < ts.size(); i += 2)
if (ts[i] != ts[i+1])
tsOk = false;
return tsOk;
}
bool HuffmanCoderInfoIO::SetTreeInfo(const std::string &ts,
const std::vector<HuffmanCoder::Pair_CU> &nodesData)
{
bool setOk = false;
HuffmanCoderInfoIO copyInfo = *this;
if (SetTreeStruct(ts) && SetLeafNodeData(nodesData)) {
setOk = true;
if (nullptr == coderPtr) {
coderPtr = alctHuffmanCoder.allocate(1);
alctHuffmanCoder.construct(coderPtr, treeStruct, leafNodesData);
} else {
coderPtr->SetHuffTreeStruct(treeStruct, leafNodesData);
}
} else {
*this = copyInfo;
}
return setOk;
}
std::istream& HuffmanCoderInfoIO::StatisticKeyWeight(std::istream &is)
{
std::shared_ptr<char> bufferSptr(new char[blockSize]);
char *buffer = bufferSptr.get();
size_t readCount = blockSize;
keyWeight.clear();
while (readCount == blockSize) {
is.read(buffer, blockSize);
readCount = is.gcount();
for (size_t i = 0; i < readCount; ++i)
++keyWeight[buffer[i]];
}
if (nullptr == coderPtr) {
coderPtr = alctHuffmanCoder.allocate(1);
alctHuffmanCoder.construct(coderPtr, keyWeight);
} else {
coderPtr->SetKeyWeight(keyWeight);
}
SetTreeStruct(coderPtr->GetHuffTreeStruct());
SetLeafNodeData(coderPtr->GetHuffTreeLeafData());
return is;
}
std::map<char, unsigned> HuffmanCoderInfoIO::GetKeyWeight() const
{
return keyWeight;
}
std::istream& HuffmanCoderInfoIO::Read(std::istream &is, char *buf, size_t size)
{
is.read(buf, size);
gcount = is.gcount();
return is;
}
std::ostream& HuffmanCoderInfoIO::Write(std::ostream &os, char *buf, size_t size)
{
os.write(buf, size);
return os;
}
size_t HuffmanCoderInfoIO::Gcount() const
{
return gcount;
}
size_t HuffmanCoderInfoIO::GetFileSize() const
{
return fileSize;
}
const Coder* HuffmanCoderInfoIO::GetCoder() const
{
return coderPtr;
}
<file_sep>#ifndef _BMPCODER_H
#define _BMPCODER_H
// 2017.12.02 18:58
#include <cstddef>
#include <memory>
#include "BmpCommon.h"
class BmpCoder {
public:
static const size_t WIDTHDFT = 1920;
static const size_t HEIGHTDFT = 1080;
static const size_t MAXLENGTH = 19200 * 10800;
static bool IsValidBmp(const BmpFileHeader&, const BmpInfoHeader&);
BmpCoder(char m = 3);
void SetMask(char);
int Decode(std::shared_ptr<const char[]>, std::ofstream&);
unsigned Encode(std::ifstream&, std::shared_ptr<char[]>&);
private:
char mask;
static const size_t BUFFSIZE = 1024;
int GetPlain(const char*, size_t, std::ofstream&);
int GetCipher(std::ifstream&, size_t, char*, size_t);
};
#endif // _BMPCODER_H
<file_sep>#include <bitset>
#include "BmpCoder.h"
#include "BmpFactory.h"
#include "Common.h"
#include "Mandelbrot.h"
BmpCoder::BmpCoder(char m)
{
SetMask(m);
}
void BmpCoder::SetMask(char m)
{
mask = m;
}
bool BmpCoder::IsValidBmp(const BmpFileHeader &fileHdr, const BmpInfoHeader &infoHdr)
{
bool result =
fileHdr.bfType == 0x4d42 &&
fileHdr.bfReserved1 == 0x4248 &&
infoHdr.biBitPerPxl == 24 &&
static_cast<size_t>(infoHdr.biWidth*infoHdr.biHeight) < MAXLENGTH;
return result;
}
int BmpCoder::Decode(std::shared_ptr<const char[]> bmpFile, std::ofstream &ofs)
{
int result = -1;
BmpFileHeader fileHdr;
BmpInfoHeader infoHdr;
const char *bmpFilePtr = bmpFile.get();
fileHdr.ReadHeader(bmpFilePtr);
bmpFilePtr += 14;
infoHdr.ReadHeader(bmpFilePtr);
bmpFilePtr += 40;
if (IsValidBmp(fileHdr, infoHdr))
result = GetPlain(bmpFilePtr, infoHdr.biImageSize, ofs);
else
throw std::runtime_error("cannot decode this bmp file");
return result;
}
int BmpCoder::GetPlain(const char *imageBeg, size_t imageSize, std::ofstream &ofs)
{
const std::bitset<8> bitSet(mask);
const char *colorPtr = imageBeg;
const char *imageEnd = imageBeg + imageSize;
size_t bitCounter = 0, outputCounter = 0, plainFileSize = 0;
std::shared_ptr<char> buffer(new char[BUFFSIZE], std::default_delete<char[]>());
char *buffPtr = buffer.get();
for (size_t i = 0; i < sizeof(plainFileSize)*8; ++i, colorPtr += 3)
plainFileSize |= (*colorPtr & 0x1) << i;
for (size_t i = 0; i < 3; colorPtr = imageBeg + ++i) {
for (; colorPtr < imageEnd && outputCounter < plainFileSize; colorPtr += 3) {
// here suppose all data bits stored from lowest bit sequentialy
for (size_t j = 0; j < bitSet.count(); ++j) {
if (*colorPtr >> j & 0x1)
*buffPtr |= 0x1 << bitCounter;
else
*buffPtr &= ~(0x1 << bitCounter);
if (++bitCounter == 8) {
bitCounter = 0;
size_t offset = ++buffPtr - buffer.get();
if (outputCounter + offset == plainFileSize ||
offset == BUFFSIZE) {
ofs.write(buffer.get(), offset);
outputCounter += offset;
buffPtr = buffer.get();
}
}
}
}
}
return 0;
}
unsigned BmpCoder::Encode(std::ifstream &ifs, std::shared_ptr<char[]> &bmpFile)
{
unsigned result = 0;
ifs.seekg(0, std::fstream::beg);
size_t fileSize = CalcFileSize(ifs);
std::bitset<8> bitSetOfMask(mask);
size_t imageSize = fileSize * 8 / bitSetOfMask.count() / 3;
size_t width = WIDTHDFT, height = HEIGHTDFT;
while (imageSize > width*height) {
width *= 2;
height *= 2;
if (width * height > MAXLENGTH) {
bmpFile = nullptr;
throw std::out_of_range("file is too large");
}
}
BmpFactory bmpFactory;
bmpFactory.SetBiBitPerPxl(24);
bmpFactory.SetBfReserved1(0x4248); // "HB"
bmpFactory.SetResolution(width, height);
bmpFactory.GetFile(bmpFile);
if (0 == GetCipher(ifs, fileSize, bmpFile.get() + bmpFactory.GetBfOffBits(),
bmpFactory.GetBiImageSize()))
result = bmpFactory.GetBfSize();
return result;
}
int BmpCoder::GetCipher(std::ifstream &ifs, size_t fileSize, char *imageBeg, size_t imageSize)
{
const std::bitset<8> bitSet(mask);
char *colorPtr = imageBeg;
char *imageEnd = imageBeg + imageSize;
size_t bitCounter = 0, outputCounter = 0, plainFileSize = fileSize;
std::shared_ptr<char> buffer(new char[fileSize], std::default_delete<char[]>());
char *buffPtr = buffer.get();
ifs.read(buffPtr, fileSize);
for (size_t i = 0; i < sizeof(plainFileSize)*8; ++i, colorPtr += 3)
(plainFileSize >> i) & 0x1 ? *colorPtr |= 0x1 : *colorPtr &= ~0x1;
for (size_t i = 0; i < 3; colorPtr = imageBeg + ++i) {
for (; colorPtr < imageEnd && outputCounter < plainFileSize; colorPtr += 3) {
// here suppose all data bits stored from lowest bit sequentialy
for (size_t j = 0; j < bitSet.count(); ++j) {
if (*buffPtr >> bitCounter & 0x1)
*colorPtr |= 0x1 << j;
else
*colorPtr &= ~(0x1 << j);
if (++bitCounter == 8) {
++buffPtr;
++outputCounter;
bitCounter = 0;
}
}
}
}
return 0;
}
<file_sep>#ifndef _XORCODER_H
#define _XORCODER_H
#include <vector>
#include <memory>
#include "Coder.h"
class XorCoder: public Coder {
public:
XorCoder(int mgcNmb = 0);
virtual ~XorCoder();
virtual std::string Encode(std::string&) const override;
virtual std::string Decode(std::string&) const override;
void ResetVecMgcNmbIndex(size_t i = 0) const;
int SetMgcNmb(int mgcNmb = 0);
int GetMgcNmb() const;
private:
static const char CODE_ZERO = '0';
static const char CODE_ONE = '1';
std::vector<char> mgcNmbs;
// encode|decode have to change this index-value, this is conflict with
// their 'const' declaration, so here using ptr to work around
std::shared_ptr<size_t> const mgcNmbsIndex;
};
#endif // _XORCODER_H
<file_sep>#ifndef _DECODESTRATEGY_H
#define _DECODESTRATEGY_H
// 2017.05.31 19:24
#include "CoderInfoIO.h"
class DecodeStrategy {
public:
DecodeStrategy(CoderInfoIO *p = nullptr);
void SetCoderInfoPtr(CoderInfoIO*);
int Decode(const std::string&, const std::string&);
private:
CoderInfoIO *coderInfoPtr;
size_t readBlockSize;
size_t writeBlockSize;
};
#endif // _DECODESTRATEGY_H
<file_sep>#include <random>
#include <ctime>
#include <bitset>
#include "XorCoder.h"
namespace {
// using 'static global variable' to avoid construct 'randomEngine' for
// every 'XorCoder' objects
std::default_random_engine randomEngine(time(0));
std::uniform_int_distribution<char> distChar;
}
// passing 'mgcNmb' in when decode, leave it empty when encode
XorCoder::XorCoder(int mgcNmb): mgcNmbsIndex(std::make_shared<size_t>(0))
{
SetMgcNmb(mgcNmb);
}
XorCoder::~XorCoder()
{
}
std::string XorCoder::Encode(std::string &originCode) const
{
std::string result = "";
size_t iNextByte = 0;
while ((originCode.size() - iNextByte) > 7) {
// bit code to 'char'
std::bitset<8> oneByte =
std::bitset<8>(originCode, iNextByte, 8, CODE_ZERO, CODE_ONE);
char code = static_cast<unsigned char>(oneByte.to_ulong());
// index determained by plaintext so we don't change 'code' here
// as opposed to 'Decode'
result += std::bitset<8>(code ^ mgcNmbs[*mgcNmbsIndex]).to_string();
*mgcNmbsIndex = (code >> 2) % 4;
iNextByte += 8;
}
originCode = originCode.erase(0, iNextByte);
return result;
}
std::string XorCoder::Decode(std::string &originCode) const
{
std::string result = "";
size_t iNextByte = 0;
while ((originCode.size() - iNextByte) > 7) {
// bit code to 'char'
std::bitset<8> oneByte =
std::bitset<8>(originCode, iNextByte, 8, CODE_ZERO, CODE_ONE);
char code = static_cast<unsigned char>(oneByte.to_ulong());
// index determained by plaintext so we change the 'code' here
// as opposed to 'Encode'
code ^= mgcNmbs[*mgcNmbsIndex];
result += std::bitset<8>(code).to_string();
*mgcNmbsIndex = (code >> 2) % 4;
iNextByte += 8;
}
originCode = originCode.erase(0, iNextByte);
return result;
}
void XorCoder::ResetVecMgcNmbIndex(size_t i) const
{
*mgcNmbsIndex = i;
}
int XorCoder::SetMgcNmb(int mgcNmb)
{
int i = 0, mgcNmbNot0 = mgcNmb;
char *mgcNmbPtr = reinterpret_cast<char*>(&mgcNmb);
mgcNmbs.clear();
while (i++ < 4) {
// if mgcNmb==0, generate 4 random value(not 0) for mgcNmb
while (!mgcNmbNot0 && *mgcNmbPtr == 0)
*mgcNmbPtr = distChar(randomEngine);
mgcNmbs.push_back(*mgcNmbPtr++);
}
*mgcNmbsIndex = 0;
return mgcNmb;
}
int XorCoder::GetMgcNmb() const
{
int result, i = 0;
char *cPtr = reinterpret_cast<char*>(&result);
while (i < 4)
*cPtr++ = mgcNmbs[i++];
return result;
}
<file_sep>#include <cstring>
#include "BmpCommon.h"
BmpFileHeader::BmpFileHeader(): bfType(0x4d42),
bfSize(0), bfReserved1(0), bfReserved2(0), bfOffBits(0)
{
}
void BmpFileHeader::ReadHeader(std::istream &is)
{
is.read(reinterpret_cast<char*>(&bfType), sizeof(bfType));
is.read(reinterpret_cast<char*>(&bfSize), sizeof(bfSize));
is.read(reinterpret_cast<char*>(&bfReserved1), sizeof(bfReserved1));
is.read(reinterpret_cast<char*>(&bfReserved2), sizeof(bfReserved2));
is.read(reinterpret_cast<char*>(&bfOffBits), sizeof(bfOffBits));
}
void BmpFileHeader::ReadHeader(const char *ptr)
{
memcpy(&bfType, ptr, sizeof(bfType));
ptr += sizeof(bfType);
memcpy(&bfSize, ptr, sizeof(bfSize));
ptr += sizeof(bfSize);
memcpy(&bfReserved1, ptr, sizeof(bfReserved1));
ptr += sizeof(bfReserved1);
memcpy(&bfReserved2, ptr, sizeof(bfReserved2));
ptr += sizeof(bfReserved2);
memcpy(&bfOffBits, ptr, sizeof(bfOffBits));
ptr += sizeof(bfOffBits);
}
void BmpFileHeader::WriteHeader(std::ostream &os)
{
os.write(reinterpret_cast<char*>(&bfType), sizeof(bfType));
os.write(reinterpret_cast<char*>(&bfSize), sizeof(bfSize));
os.write(reinterpret_cast<char*>(&bfReserved1), sizeof(bfReserved1));
os.write(reinterpret_cast<char*>(&bfReserved2), sizeof(bfReserved2));
os.write(reinterpret_cast<char*>(&bfOffBits), sizeof(bfOffBits));
}
void BmpFileHeader::WriteHeader(char *ptr)
{
memcpy(ptr, &bfType, sizeof(bfType));
ptr += sizeof(bfType);
memcpy(ptr, &bfSize, sizeof(bfSize));
ptr += sizeof(bfSize);
memcpy(ptr, &bfReserved1, sizeof(bfReserved1));
ptr += sizeof(bfReserved1);
memcpy(ptr, &bfReserved2, sizeof(bfReserved2));
ptr += sizeof(bfReserved2);
memcpy(ptr, &bfOffBits, sizeof(bfOffBits));
ptr += sizeof(bfOffBits);
}
BmpInfoHeader::BmpInfoHeader():
biSize(40), biWidth(0), biHeight(0), biPlanes(1), biBitPerPxl(0),
biCompression(0), biImageSize(0), biXPxlsPerMeter(0), biYPxlsPerMeter(0),
biClrUsed(0), biClrImportant(0)
{
}
void BmpInfoHeader::ReadHeader(std::istream &is)
{
is.read(reinterpret_cast<char*>(&biSize), sizeof(biSize));
is.read(reinterpret_cast<char*>(&biWidth), sizeof(biWidth));
is.read(reinterpret_cast<char*>(&biHeight), sizeof(biHeight));
is.read(reinterpret_cast<char*>(&biPlanes), sizeof(biPlanes));
is.read(reinterpret_cast<char*>(&biBitPerPxl), sizeof(biBitPerPxl));
is.read(reinterpret_cast<char*>(&biCompression), sizeof(biCompression));
is.read(reinterpret_cast<char*>(&biImageSize), sizeof(biImageSize));
is.read(reinterpret_cast<char*>(&biXPxlsPerMeter), sizeof(biXPxlsPerMeter));
is.read(reinterpret_cast<char*>(&biYPxlsPerMeter), sizeof(biYPxlsPerMeter));
is.read(reinterpret_cast<char*>(&biClrUsed), sizeof(biClrUsed));
is.read(reinterpret_cast<char*>(&biClrImportant), sizeof(biClrImportant));
}
void BmpInfoHeader::ReadHeader(const char *ptr)
{
memcpy(&biSize, ptr, sizeof(biSize));
ptr += sizeof(biSize);
memcpy(&biWidth, ptr, sizeof(biWidth));
ptr += sizeof(biWidth);
memcpy(&biHeight, ptr, sizeof(biHeight));
ptr += sizeof(biHeight);
memcpy(&biPlanes, ptr, sizeof(biPlanes));
ptr += sizeof(biPlanes);
memcpy(&biBitPerPxl, ptr, sizeof(biBitPerPxl));
ptr += sizeof(biBitPerPxl);
memcpy(&biCompression, ptr, sizeof(biCompression));
ptr += sizeof(biCompression);
memcpy(&biImageSize, ptr, sizeof(biImageSize));
ptr += sizeof(biImageSize);
memcpy(&biXPxlsPerMeter, ptr, sizeof(biXPxlsPerMeter));
ptr += sizeof(biXPxlsPerMeter);
memcpy(&biYPxlsPerMeter, ptr, sizeof(biYPxlsPerMeter));
ptr += sizeof(biYPxlsPerMeter);
memcpy(&biClrUsed, ptr, sizeof(biClrUsed));
ptr += sizeof(biClrUsed);
memcpy(&biClrImportant, ptr, sizeof(biClrImportant));
ptr += sizeof(biClrImportant);
}
void BmpInfoHeader::WriteHeader(std::ostream &os)
{
os.write(reinterpret_cast<char*>(&biSize), sizeof(biSize));
os.write(reinterpret_cast<char*>(&biWidth), sizeof(biWidth));
os.write(reinterpret_cast<char*>(&biHeight), sizeof(biHeight));
os.write(reinterpret_cast<char*>(&biPlanes), sizeof(biPlanes));
os.write(reinterpret_cast<char*>(&biBitPerPxl), sizeof(biBitPerPxl));
os.write(reinterpret_cast<char*>(&biCompression), sizeof(biCompression));
os.write(reinterpret_cast<char*>(&biImageSize), sizeof(biImageSize));
os.write(reinterpret_cast<char*>(&biXPxlsPerMeter), sizeof(biXPxlsPerMeter));
os.write(reinterpret_cast<char*>(&biYPxlsPerMeter), sizeof(biYPxlsPerMeter));
os.write(reinterpret_cast<char*>(&biClrUsed), sizeof(biClrUsed));
os.write(reinterpret_cast<char*>(&biClrImportant), sizeof(biClrImportant));
}
void BmpInfoHeader::WriteHeader(char *ptr)
{
memcpy(ptr, &biSize, sizeof(biSize));
ptr += sizeof(biSize);
memcpy(ptr, &biWidth, sizeof(biWidth));
ptr += sizeof(biWidth);
memcpy(ptr, &biHeight, sizeof(biHeight));
ptr += sizeof(biHeight);
memcpy(ptr, &biPlanes, sizeof(biPlanes));
ptr += sizeof(biPlanes);
memcpy(ptr, &biBitPerPxl, sizeof(biBitPerPxl));
ptr += sizeof(biBitPerPxl);
memcpy(ptr, &biCompression, sizeof(biCompression));
ptr += sizeof(biCompression);
memcpy(ptr, &biImageSize, sizeof(biImageSize));
ptr += sizeof(biImageSize);
memcpy(ptr, &biXPxlsPerMeter, sizeof(biXPxlsPerMeter));
ptr += sizeof(biXPxlsPerMeter);
memcpy(ptr, &biYPxlsPerMeter, sizeof(biYPxlsPerMeter));
ptr += sizeof(biYPxlsPerMeter);
memcpy(ptr, &biClrUsed, sizeof(biClrUsed));
ptr += sizeof(biClrUsed);
memcpy(ptr, &biClrImportant, sizeof(biClrImportant));
ptr += sizeof(biClrImportant);
}
std::ostream& operator<<(std::ostream &os, const BmpFileHeader &bfHdr)
{
os << "bfType: " << bfHdr.bfType << std::endl;
os << "bfSize: " << bfHdr.bfSize << std::endl;
os << "bfReserved1: " << bfHdr.bfReserved1 << std::endl;
os << "bfReserved2: " << bfHdr.bfReserved2 << std::endl;
os << "bfOffBits: " << bfHdr.bfOffBits << std::endl;
return os;
}
std::ostream& operator<<(std::ostream &os, const BmpInfoHeader &biHdr)
{
os << "biSize: " << biHdr.biSize << std::endl;
os << "biWidth: " << biHdr.biWidth << std::endl;
os << "biHeight: " << biHdr.biHeight << std::endl;
os << "biPlanes: " << biHdr.biPlanes << std::endl;
os << "biBitPerPxl: " << biHdr.biBitPerPxl << std::endl;
os << "biCompression: " << biHdr.biCompression << std::endl;
os << "biImageSize: " << biHdr.biImageSize << std::endl;
os << "biXPxlsPerMeter: " << biHdr.biXPxlsPerMeter << std::endl;
os << "biYPxlsPerMeter: " << biHdr.biYPxlsPerMeter << std::endl;
os << "biClrUsed: " << biHdr.biClrUsed << std::endl;
os << "biClrImportant: " << biHdr.biClrImportant << std::endl;
return os;
}
uint32_t BmpInfoHeader::GetBiImageSize()
{
int lineBytes = (biWidth * biBitPerPxl/8 + 3) / 4 * 4;
if (biWidth && !lineBytes)
lineBytes = 4;
return (lineBytes * biHeight);
}
<file_sep>#ifndef _HUFFMANCODERINFOIO_H
#define _HUFFMANCODERINFOIO_H
#include "CoderInfoIO.h"
#include "HuffmanCoder.h"
class HuffmanCoderInfoIO: public CoderInfoIO {
public:
HuffmanCoderInfoIO();
HuffmanCoderInfoIO(const HuffmanCoderInfoIO&);
HuffmanCoderInfoIO(HuffmanCoderInfoIO&&);
HuffmanCoderInfoIO(const std::string&, const std::vector<HuffmanCoder::Pair_CU>&);
virtual ~HuffmanCoderInfoIO();
virtual std::istream& ReadInfo(std::istream&) override;
virtual std::ostream& WriteInfo(std::ostream&) override;
virtual enum PreprcsRslt Preprocess(std::istream&) override;
virtual enum PreprcsRslt Preprocess(std::istream&, std::iostream&) override;
virtual std::istream& Read(std::istream&, char*, size_t) override;
virtual std::ostream& Write(std::ostream&, char*, size_t) override;
virtual size_t Gcount() const override;
virtual size_t GetFileSize() const override;
virtual const Coder* GetCoder() const override;
HuffmanCoderInfoIO& operator=(const HuffmanCoderInfoIO&);
HuffmanCoderInfoIO& operator=(HuffmanCoderInfoIO&&);
bool SetTreeInfo(const std::string&, const std::vector<HuffmanCoder::Pair_CU>&);
std::string GetTreeStruct() const;
std::vector<HuffmanCoder::Pair_CU> GetLeafNodeData() const;
std::map<char, unsigned> GetKeyWeight() const;
private:
size_t leafNodeNmb;
size_t treeNodeNmb;
size_t gcount;
size_t fileSize;
std::string treeStruct;
static const size_t blockSize = 64;
std::vector<HuffmanCoder::Pair_CU> leafNodesData;
std::map<char, unsigned> keyWeight;
HuffmanCoder *coderPtr;
static std::allocator<HuffmanCoder> alctHuffmanCoder;
bool SetTreeStruct(const std::string&);
bool SetLeafNodeData(const std::vector<HuffmanCoder::Pair_CU>&);
bool CheckTreeStruct(const std::string&) const;
std::istream& StatisticKeyWeight(std::istream&);
};
#endif // _HUFFMANCODERINFOIO_H
<file_sep>#include <thread>
#include <cmath>
#include "Mandelbrot.h"
Mandelbrot::Mandelbrot():
centerX(-0.5), centerY(0), zoomFactor(2), radius(4), iteration(50)
{
}
size_t Mandelbrot::GetIteration() const
{
return iteration;
}
double Mandelbrot::GetZoomFactor() const
{
return zoomFactor;
}
void Mandelbrot::SetZoomFactor(double value)
{
zoomFactor = value;
}
std::shared_ptr<double> Mandelbrot::GetMdbValMap(
const size_t width, const size_t height)
{
std::shared_ptr<double> mdbValMap(new double[width * height],
std::default_delete<double[]>());
std::shared_ptr<std::thread> threadPtrArr[threadNum];
size_t heightBegin = 0, heightEnd = 0, blockSize = height/threadNum;
blockSize += (height % threadNum) ? 1 : 0;
for (size_t i = 0; i < threadNum && heightEnd < height ; ++i) {
heightBegin = blockSize * i;
heightEnd = blockSize * (i+1);
heightEnd = heightEnd > height ? height : heightEnd;
threadPtrArr[i] = std::make_shared<std::thread>(
GetMdbValMapThread, *this, mdbValMap,
width, height, heightBegin, heightEnd);
}
for (size_t i = 0; i < threadNum; ++i)
threadPtrArr[i]->join();
return mdbValMap;
}
double Mandelbrot::GetMdbVal(double a, double b, double r, size_t iteration)
{
size_t i, n;
double result = iteration - 1; // limit result between 0 ~ iteration-1
double x = a, y = b, x2 = a*a, y2 = b*b;
for (i = 0; i < iteration && x2+y2 < r; ++i) {
y = 2 * x * y + b;
x = x2 - y2 + a;
x2 = pow(x, 2);
y2 = pow(y, 2);
}
for (n = i+2; i < n; ++i) {
y = 2 * x * y + b;
x = x2 - y2 + a;
x2 = pow(x, 2);
y2 = pow(y, 2);
}
if(i < iteration)
result = i + 1.0 - log(log(sqrt(x2 + y2)))/log(2.0);
return result;
}
void Mandelbrot::GetMdbValMapThread(
const Mandelbrot &mdb, std::shared_ptr<double> mdbValMap,
size_t width, size_t height, size_t hBeg, size_t hEnd)
{
double xMin = mdb.centerX - 3.0 / mdb.zoomFactor;
double xMax = mdb.centerX + 3.0 / mdb.zoomFactor;
double yMin = mdb.centerY - 3.0 * height / width / mdb.zoomFactor;
double yMax = mdb.centerY + 3.0 * height / width / mdb.zoomFactor;
double xScale = (xMax - xMin) / width;
double yScale = (yMax - yMin) / height;
double *mdbValMapPtr = mdbValMap.get();
for (size_t i = hBeg; i < hEnd; ++i) {
double y = yMax - i * yScale;
size_t offset = i * width;
for (size_t j = 0; j < width; ++j) {
double x = xMin + j * xScale;
mdbValMapPtr[offset + j] = GetMdbVal(x, y, mdb.radius, mdb.iteration);
}
}
}
<file_sep>#include <fstream>
#include <memory>
#include <bitset>
#include "EncodeStrategy.h"
EncodeStrategy::EncodeStrategy(CoderInfoIO *p): coderInfoPtr(p)
{
}
void EncodeStrategy::SetCoderInfoPtr(CoderInfoIO *p)
{
coderInfoPtr = p;
}
int EncodeStrategy::Encode(const std::string &iFile, const std::string &oFile)
{
std::ifstream ifs(iFile, std::fstream::binary);
std::fstream ofs(oFile, std::fstream::binary | std::fstream::in | std::fstream::out);
if (!ofs) // if 'oFile' not exist, creat it
ofs.open(oFile, std::fstream::out);
ofs.close();
ofs.open(oFile, std::fstream::binary | std::fstream::in | std::fstream::out);
if (!ifs || !ofs)
throw std::runtime_error("cannot open file!");
if (RSLTOK != coderInfoPtr->Preprocess(ifs, ofs))
throw std::runtime_error("preprocess error");
ifs.clear();
ifs.seekg(std::fstream::beg); // useless if seekg before clear
const Coder *coderPtr = coderInfoPtr->GetCoder();
size_t gcount = readBlockSize, writeBufferIndex;
std::shared_ptr<char> readBufferSp(new char[readBlockSize]);
std::shared_ptr<char> writeBufferSp(new char[writeBlockSize]);
char *readBuffer = readBufferSp.get();
char *writeBuffer = writeBufferSp.get();
std::string originCode, cipherCode;
coderInfoPtr->WriteInfo(ofs);
while (gcount == readBlockSize) {
ifs.read(readBuffer, readBlockSize);
gcount = ifs.gcount();
for (size_t i = 0; i < gcount; ++i)
originCode += std::bitset<8>(readBuffer[i]).to_string();
cipherCode += coderPtr->Encode(originCode);
if (originCode.size() != 0)
throw std::runtime_error("encode error(originCode != 0)!");
size_t iNextByte = writeBufferIndex = 0;
while ((cipherCode.size() - iNextByte) > 7) {
std::bitset<8> oneByte = std::bitset<8>(cipherCode, iNextByte, 8);
char c = static_cast<char>(oneByte.to_ulong());
writeBuffer[writeBufferIndex++] = c;
iNextByte += 8;
}
cipherCode.erase(0, iNextByte);
coderInfoPtr->Write(ofs, writeBuffer, writeBufferIndex);
}
if (cipherCode.size() > 0) {
cipherCode += std::string(8 - cipherCode.size(), '0');
std::bitset<8> oneByte = std::bitset<8>(cipherCode, 0, 8);
char c = static_cast<char>(oneByte.to_ulong());
coderInfoPtr->Write(ofs, &c, 1);
}
return 0;
}
| bd967b7c5527f8d849aecbdfc5248049347fc5c6 | [
"Makefile",
"C++"
] | 28 | C++ | icrelae/HuffBmp | 90e14d44bbe0e2b1cdf594cac8c860dbb8535a1f | 94364969e749fe9a6cc2bcec76b3ed9c5055b33a |
refs/heads/master | <file_sep><<<<<<< HEAD
#include <iostream>
=======
hello i am editing this bitches
>>>>>>> 36c0ea46d1b8835fdf1d67b25d02bc8da26837d1
| 2a758ea7b0055a1b224a68191ccb7c9dae4013c1 | [
"C"
] | 1 | C | lovesh2407/ThinkFlipkart | 436fbb0c18483d62d6169e4425800e940cec94f3 | a3e014855cb07f130c5bfd91be2bfd3c71aa429f |
refs/heads/master | <file_sep><?php
// Load Configuration
if (file_exists('config.php')) {
require_once('config.php');
}
// Connect to the DB
mysql_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
mysql_select_db(DB_DATABASE);
// Products
$products = mysql_query("select * from " . DB_PREFIX . "product_description LIMIT 0, 100000");
while ($product = mysql_fetch_array($products, MYSQL_ASSOC)) {
$seoname = toAscii($product['name']);
$seourl = "product_id=".$product['product_id'];
$url_result = mysql_query("select * from " . DB_PREFIX . "url_alias where query='".$seourl."'");
$data = mysql_fetch_row($url_result);
if(!$data) {
mysql_query("insert into " . DB_PREFIX . "url_alias set query='".$seourl."', keyword='".$seoname."'");
echo "<br>Inserted ".$seoname;
}
}
// Categories
$categories = mysql_query("select * from " . DB_PREFIX . "category_description LIMIT 0, 100000");
while ($category = mysql_fetch_array($categories, MYSQL_ASSOC)) {
$seoname = toAscii($category['name']);
$seourl = "category_id=".$category['category_id'];
$url_result = mysql_query("select * from " . DB_PREFIX . "url_alias where query='".$seourl."'");
$data = mysql_fetch_row($url_result);
if(!$data) {
mysql_query("insert into " . DB_PREFIX . "url_alias set query='".$seourl."', keyword='".$seoname."'");
echo "<br>Inserted ".$seoname;
}
}
function toAscii($str) {
$clean = trim($str);
$clean = trim($clean, '-');
$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
$clean = strtolower($clean);
$clean = preg_replace("/[\/_|+ -]+/", '-', $clean);
return $clean;
}
?><file_sep>OpenCart-SEO-URLS
=================
This is a very simple PHP script for OpenCart. It goes through all products and categories and inserts a entry into the url_alias table for SEO URLS.
### Usage
Put in OpenCart root directory and run it via the browser.
### Example
http://www.website.com/OpenCart_SEO_URLS.php
| 6875a2a71a06bd45c5a404f49682db6ad745b2c0 | [
"Markdown",
"PHP"
] | 2 | PHP | IP-CAM/OpenCart-SEO-URLS | 97ec476ec778dadc13d64882ffca6df2824f2d82 | 7b6b2602e9223701e6df889ace8949aebc0fd591 |
refs/heads/master | <file_sep>// Maked by <NAME>
/**
* @param arrChess : chứa những quân hậu đạt điều kiện
* @param arrCross : chứa giá trị đưòng chéo chính của các quân hậu
* @param arrCross1 : chứa giá trị đưòng chéo phụ của các quân hậu
* @param total_solutions : chứa tối đa tất cả các solutions có thể tìm đuợc
*/
// N-Queens Problem
var queenposition = [];
var N;
var columnsum = [];
var upperdiagonalsum= [];
var lowerdiagonalsum=[];
var store=[];
function Initialization() {
var i=0;
var j=0;
for(i=0; i<2*N-1; i++) {
if(i<N) {
columnsum[i]=0;
}
upperdiagonalsum[i]=lowerdiagonalsum[i]=0;
}
var minimumconflictcolumns= [];
var minconflicts=Infinity;
var temp;
queenposition[0] =Math.round((Math.random()*N)) % N;
columnsum[queenposition[0]] += 1;
upperdiagonalsum[queenposition[0]+0] += 1;
lowerdiagonalsum[(N-queenposition[0])+0-1] += 1;
// i=row index
for(i=1; i<N; i++) {
minimumconflictcolumns = [];
minconflicts = Infinity;
// j=col index
for( j=0; j<N; j++) {
temp = ((columnsum[j]+1)*columnsum[j])/2;
temp += ((upperdiagonalsum[j+i]+1)*upperdiagonalsum[j+i])/2;
temp += ((lowerdiagonalsum[(N-j)+i-1]+1)*lowerdiagonalsum[(N-j)+i-1])/2;
if(temp < minconflicts) {
minconflicts=temp;
minimumconflictcolumns = [];
minimumconflictcolumns.push(j);
} else if(temp == minconflicts) {
minimumconflictcolumns.push(j);
}
}
queenposition[i] = minimumconflictcolumns[Math.round((Math.random()*N))%minimumconflictcolumns.length];
columnsum[queenposition[i]] += 1;
upperdiagonalsum[queenposition[i]+i] += 1;
lowerdiagonalsum[(N-queenposition[i])+i-1] += 1;
}
}
function getconflicts(excludeRow) {
var conflicts=0;
for(var i=0; i<2*N-1; i++) {
if(i<N) {
columnsum[i]=0;
}
upperdiagonalsum[i]=lowerdiagonalsum[i]=0;
}
for( i=0; i<N; i++) {
if(i != excludeRow) {
columnsum[queenposition[i]] += 1;
upperdiagonalsum[queenposition[i]+i] += 1;
lowerdiagonalsum[(N-queenposition[i])+i-1] += 1;
}
}
for( i=0; i<2*N-1; i++) {
if(i<N) {
conflicts += ((columnsum[i]-1)*columnsum[i])/2;
}
conflicts += ((upperdiagonalsum[i]-1)*upperdiagonalsum[i])/2;
conflicts += ((lowerdiagonalsum[i]-1)*lowerdiagonalsum[i])/2;
}
return conflicts;
}
function Print() {
var i=0;
for(i=0;i<N;i++)
store[i]=[];
var i=0,j=0,k=0;
for(i=0; i<N; i++) {
for(j=0; j<queenposition[i]; j++) {
store[i][j]=0;
}
store[i][j]=1;
j++;
for(k=j; k<N; k++) {
store[i][k]=0;
}
}
}
function MaximumConflicts() {
var rowconflicts=0;
var temp=0;
var maxrowsconflict = [];
var i=0;
for(i=0; i<N; i++) {
temp = ((columnsum[queenposition[i]]-1)*columnsum[queenposition[i]])/2;
temp += ((upperdiagonalsum[queenposition[i]+i]-1)*upperdiagonalsum[queenposition[i]+i])/2;
temp += ((lowerdiagonalsum[(N-queenposition[i])+i-1]-1)*lowerdiagonalsum[(N-queenposition[i])+i-1])/2;
if(temp > rowconflicts) {
rowconflicts=temp;
maxrowsconflict = [];
maxrowsconflict.push(i);
} else if(temp == rowconflicts) {
maxrowsconflict.push(i);
}
}
return maxrowsconflict[Math.round((Math.random()*N))%maxrowsconflict.length];
}
function minimumconflicts() {
var highestrowconflict = MaximumConflicts();
var minconflicts=Infinity;
var temp=0;
// min conflicts cols for queen
var minimumconflictcolumns = [];
//Print();
getconflicts(highestrowconflict);
var i=0;
// i=column index
for( i=0; i<N; i++) {
temp = ((columnsum[i]+1)*columnsum[i])/2;
temp += ((upperdiagonalsum[i+highestrowconflict]+1)*upperdiagonalsum[i+highestrowconflict])/2;
temp += ((lowerdiagonalsum[(N-i)+highestrowconflict-1]+1)*lowerdiagonalsum[(N-i)+highestrowconflict-1])/2;
if(temp < minconflicts) {
minconflicts=temp;
minimumconflictcolumns = [];
minimumconflictcolumns.push(i);
} else if(temp == minconflicts) {
minimumconflictcolumns.push(i);
}
}
queenposition[highestrowconflict]=minimumconflictcolumns[Math.round((Math.random()*N))%minimumconflictcolumns.length];
}
/***
* @param pieces : Object queen chess
* @param s : Snap Object
* @param rwidth : chiều dài hình vuông
* @param total_solutions : chiều cao hình vuông
*/
// Draw Chess Table
var pieces = {
TEAM_QUEEN :{name: "<NAME>",code: "\u265B"},
},
s = Snap("#mysvg"),
rwidth = 60,
rheight = 60;
//default chess table
function drawChess(){
var y = 0;
for(var row = 0 ; row < N;row++){
var x = 0;
for(var col = 0; col < N;col++){
var r = s.rect(x,y,rwidth,rheight);
// nếu có solutions thì vẽ quân hậu, không thì để bàn cờ trống
//if(num_solutions){
if(store[row][col]==1){
var chess = s.text(x + rwidth/2,y + (rheight/2 + rwidth/4),pieces.TEAM_QUEEN.code);
chess.attr({
'font-size' : rwidth/2 +rwidth/3,
'text-anchor' : 'middle',
'fill' : 'orange'
});
}
//fill color chess table
if((row % 2 == 0 && col % 2 == 0) || (row % 2 != 0 && col % 2 != 0)){
r.attr({
fill: "white"
});
}
x += rwidth;
}
y += rheight;
}
}
function clear(){
s.clear();
queenposition = [];
//var N;
columnsum = [];
upperdiagonalsum= [];
lowerdiagonalsum=[];
store=[];
}
//start app
function runner(num){
N = num;
clear();
Initialization();
var i=0;
var preconflicts = getconflicts();
var currentconflicts;
var count = 0;
var steps = 0;
while(preconflicts != 0) {
console.log('Testing console');
minimumconflicts();
steps++;
currentconflicts = getconflicts();
if(preconflicts == currentconflicts) {
count++;
if(count>1) {
queenposition[Math.round((Math.random()*N))%N] = Math.round((Math.random()*N))%N;
count = 0;
}
}
preconflicts = currentconflicts;
}
$("#mysolve").text("Number of Steps to solve : " + steps);
Print();
drawChess();
}
$("#btnChess").click(function(){
let num = $("#inputNum").val();
$("#mysolve").text("");
$("#status").text("");
if(!num){
$("#status").text("Enter number of cell");
return;
}
else if(num==2 || num==3)
{
clear();
$("#status").text("No solutions possible!");
return;
}
else if(num > 1000){
$("#status").text("Input < 10");
return;
}
runner(num);
});
<file_sep>#include <iostream>
#include <limits>
#include <stdlib.h>
#include <vector>
using namespace std;
const int INF = numeric_limits<int>::max();
int N = 8;
int* queenposition;
int* columnsum;
int* upperdiagonalsum;
int* lowerdiagonalsum;
// runtime: n^2
void Initialization() {
queenposition = new int[N];
columnsum = new int[N];
upperdiagonalsum = new int[(2*N)-1];
lowerdiagonalsum = new int[(2*N)-1];
for(int i=0; i<2*N-1; i++) {
if(i<N) {
columnsum[i]=0;
}
upperdiagonalsum[i]=lowerdiagonalsum[i]=0;
}
vector<int> minimumconflictcolumns;
int minimumconflicts=INF;
int temp;
// choose first queen randomly
queenposition[0] = rand()%N;
columnsum[queenposition[0]] += 1;
upperdiagonalsum[queenposition[0]+0] += 1;
lowerdiagonalsum[(N-queenposition[0])+0-1] += 1;
// i=row index
for(int i=1; i<N; i++) {
minimumconflictcolumns.clear();
minimumconflicts = INF;
// j=col index
for(int j=0; j<N; j++) {
temp = ((columnsum[j]+1)*columnsum[j])/2;
temp += ((upperdiagonalsum[j+i]+1)*upperdiagonalsum[j+i])/2;
temp += ((lowerdiagonalsum[(N-j)+i-1]+1)*lowerdiagonalsum[(N-j)+i-1])/2;
if(temp < minimumconflicts) {
minimumconflicts=temp;
minimumconflictcolumns.clear();
minimumconflictcolumns.push_back(j);
} else if(temp == minimumconflicts) {
minimumconflictcolumns.push_back(j);
}
}
queenposition[i] = minimumconflictcolumns[rand()%minimumconflictcolumns.size()];
columnsum[queenposition[i]] += 1;
upperdiagonalsum[queenposition[i]+i] += 1;
lowerdiagonalsum[(N-queenposition[i])+i-1] += 1;
}
}
// runtime: n
int getconflicts(int excludeRow) {
int conflicts=0;
for(int i=0; i<2*N-1; i++) {
if(i<N) {
columnsum[i]=0;
}
upperdiagonalsum[i]=lowerdiagonalsum[i]=0;
}
for(int i=0; i<N; i++) {
if(i != excludeRow) {
columnsum[queenposition[i]] += 1;
upperdiagonalsum[queenposition[i]+i] += 1;
lowerdiagonalsum[(N-queenposition[i])+i-1] += 1;
}
}
for(int i=0; i<2*N-1; i++) {
if(i<N) {
conflicts += ((columnsum[i]-1)*columnsum[i])/2;
}
conflicts += ((upperdiagonalsum[i]-1)*upperdiagonalsum[i])/2;
conflicts += ((lowerdiagonalsum[i]-1)*lowerdiagonalsum[i])/2;
}
return conflicts;
}
int getconflicts() {
return getconflicts(-1);
}
void Print() {
for(int i=0; i<N; i++) {
for(int j=0; j<=N; j++) {
cout << "--";
}
cout << endl;
for(int j=0; j<queenposition[i]; j++) {
cout << "| ";
}
cout << "|Q";
for(int j=0; j<N-queenposition[i]-1; j++) {
cout << "| ";
}
cout << "|\n";
}
for(int j=0; j<=N; j++) {
cout << "--";
}
cout << endl;
cout << "Conflicts: " << getconflicts() << "\n\n";
}
// calculates row with most conflicts
// runtime: n
int MaximumConflicts() {
int rowconflicts=0;
int temp;
vector<int> maxrowsconflict;
for(int i=0; i<N; i++) {
temp = ((columnsum[queenposition[i]]-1)*columnsum[queenposition[i]])/2;
temp += ((upperdiagonalsum[queenposition[i]+i]-1)*upperdiagonalsum[queenposition[i]+i])/2;
temp += ((lowerdiagonalsum[(N-queenposition[i])+i-1]-1)*lowerdiagonalsum[(N-queenposition[i])+i-1])/2;
if(temp > rowconflicts) {
rowconflicts=temp;
maxrowsconflict.clear();
maxrowsconflict.push_back(i);
} else if(temp == rowconflicts) {
maxrowsconflict.push_back(i);
}
}
return maxrowsconflict[rand()%maxrowsconflict.size()];
}
// runtime: n
void minimumconflicts() {
int highestrowconflict = MaximumConflicts();
int minimumconflicts=INF;
int temp;
// min conflicts cols for queen
vector<int> minimumconflictcolumns;
//Print();
getconflicts(highestrowconflict);
// i=column index
for(int i=0; i<N; i++) {
temp = ((columnsum[i]+1)*columnsum[i])/2;
temp += ((upperdiagonalsum[i+highestrowconflict]+1)*upperdiagonalsum[i+highestrowconflict])/2;
temp += ((lowerdiagonalsum[(N-i)+highestrowconflict-1]+1)*lowerdiagonalsum[(N-i)+highestrowconflict-1])/2;
if(temp < minimumconflicts) {
minimumconflicts=temp;
minimumconflictcolumns.clear();
minimumconflictcolumns.push_back(i);
} else if(temp == minimumconflicts) {
minimumconflictcolumns.push_back(i);
}
}
queenposition[highestrowconflict]=minimumconflictcolumns[rand()%minimumconflictcolumns.size()];
}
int main() {
cout << " Enter the number of queens \n";
cin >> N;
if(N < 4) {
cout << "No solutions. The number of queen is less than 4." << endl;
return 0;
}
cout << "Number of queens: " << N << endl;
srand(time(0));
Initialization();
int preconflicts = getconflicts();
int currentconflicts;
int count = 0;
int steps = 0;
cout << "Solving..." << endl;
while(preconflicts != 0) {
minimumconflicts();
steps++;
currentconflicts = getconflicts();
if(preconflicts == currentconflicts) {
count++;
if(count>1) {
queenposition[rand()%N] = rand()%N;
count = 0;
}
}
preconflicts = currentconflicts;
}
if(N <= 20) {
Print();
}
cout << "Total number number of steps to get final configuration with zero conflicts: " << steps << "\n\n";
return 0;
} | d4d2b790e07bdd29d114446d8bd38ab084d701ce | [
"JavaScript",
"C++"
] | 2 | JavaScript | Ujjval-Patel/N-Queens | 30fe0e6686a1cec4127c40dc5089cf7fc4520c97 | eedb88eea0dcb58427d37ff2061559b558d8402e |
refs/heads/master | <file_sep>require 'pathfinder/version'
require 'pathfinder/position'
require 'pathfinder/mapper'
require 'pathfinder/movement'
module Pathfinder
def self.find_shortest_distance(directions)
raise 'Please provide the document with directions' if directions.nil? || directions.empty?
directions = directions.strip.split(', ')
start = Position.new(0, 0)
mapper = Mapper.new(start, directions)
finish = mapper.destination
(start.xpos - finish.xpos).abs + (start.ypos - finish.ypos).abs
end
end
<file_sep>#!/usr/bin/env ruby
require 'pathfinder'
# TODO: rely on OptionsParser?
if ARGV.empty?
puts 'Please provide a text document with directions'
else
directions = File.open(ARGV.first, &:readline)
puts Pathfinder::find_shortest_distance(directions)
end
<file_sep>module Pathfinder
class Movement
def initialize(direction:, distance:)
@direction = direction
@distance = distance
end
def apply(current_position, last_position, previous_positions)
@current_position = current_position
@last_position = last_position
@previous_positions = previous_positions
calculate_deltas
@last_position.update(@current_position)
@next_position = step(@distance)
@current_position.update(step) until done?
end
def calculate_deltas
@dx = @current_position.xpos - @last_position.xpos
@dy = @current_position.ypos - @last_position.ypos
end
def step(blocks = 1)
xpos = @current_position.xpos
ypos = @current_position.ypos
if @dy > 0
xpos = @direction == 'R' ? xpos + blocks : xpos - blocks
elsif @dy < 0
xpos = @direction == 'R' ? xpos - blocks : xpos + blocks
elsif @dx > 0
ypos = @direction == 'R' ? ypos - blocks : ypos + blocks
elsif @dx < 0
ypos = @direction == 'R' ? ypos + blocks : ypos - blocks
else
xpos = @direction == 'R' ? xpos + blocks : xpos - blocks
end
Position.new(xpos, ypos)
end
def done?
@current_position == @next_position || intersected?
end
def intersected?
@previous_positions.add?(@current_position).nil?
end
end
end
<file_sep>require 'spec_helper'
RSpec.describe Pathfinder do
it 'has a version number' do
expect(Pathfinder::VERSION).not_to be nil
end
describe '.find_shortest_distance' do
it 'calculates the shortest distance' do
expect(Pathfinder::find_shortest_distance(%q(R2, L3))).to eq 5
expect(Pathfinder::find_shortest_distance(%q(R2, R2, R2))).to eq 2
expect(Pathfinder::find_shortest_distance(%q(R5, L5, R5, R3))).to eq 12
end
it 'stops the first time a previous position is encountered' do
expect(Pathfinder::find_shortest_distance(%q(R8, R4, R4, R8))).to eq 4
expect(Pathfinder::find_shortest_distance(%q(R3, R4, R2, R8))).to eq 1
end
it 'raises an error when an empty string is passed' do
expect{ Pathfinder::find_shortest_distance('') }.to raise_error('Please provide the document with directions')
end
it 'raises an error when no argument is passed' do
expect{ Pathfinder::find_shortest_distance(nil) }.to raise_error('Please provide the document with directions')
end
end
end
<file_sep>module Pathfinder
class Position
attr_accessor :xpos, :ypos
def initialize(x, y)
@xpos = x
@ypos = y
end
def update(position)
@xpos = position.xpos
@ypos = position.ypos
end
def to_s
"(#{@xpos}, #{@ypos})"
end
def ==(other)
@xpos == other.xpos && @ypos == other.ypos
end
def eql?(other)
self == other
end
def hash
[@xpos, @ypos].hash
end
end
end
<file_sep>require 'spec_helper'
RSpec.describe Pathfinder::Mapper do
let (:start) { Pathfinder::Position.new(0, 0) }
let (:directions) { ['R2', 'L3'] }
subject { Pathfinder::Mapper.new(start, directions) }
it 'returns the destination as a Position' do
expect(subject.destination).to be_a Pathfinder::Position
end
it 'calculates the destination x position' do
expect(subject.destination.xpos).to eq 2
end
it 'calculates the destination y position' do
expect(subject.destination.ypos).to eq 3
end
end
<file_sep>require 'set'
module Pathfinder
class Mapper
def initialize(start, directions)
@last_position = Position.new(start.xpos, start.ypos)
@current_position = Position.new(start.xpos, start.ypos)
@directions = directions
@positions = Set.new
end
def destination
movements.each { |movement| movement.apply(@current_position, @last_position, @positions) }
@current_position
end
def movements
@directions.map { |direction| Movement.new(hashify_direction(direction)) }
end
def hashify_direction(direction)
{ direction: direction[0], distance: direction[1, direction.length].to_i }
end
end
end
<file_sep># Pathfinder
A solution by <NAME> to http://adventofcode.com/2016/day/1
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'pathfinder'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install pathfinder
## Usage
Download your personal input file from http://adventofcode.com/2016/day/1/input and save it as a text file.
Execute `pathfinder /path/to/input.txt`
The answer will be printed out after execution. For example:
```
> ariadne:pathfinder arnoldmi$ pathfinder /Users/arnoldmi/Desktop/input.txt
> 246
```
## Development
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run `bundle exec rake install`.
<file_sep>require 'spec_helper'
RSpec.describe Pathfinder::Position do
let (:position1) { Pathfinder::Position.new(1, 1) }
let (:position2) { Pathfinder::Position.new(1, 1) }
let (:position3) { Pathfinder::Position.new(0, 0) }
it 'can be relocated to new coordinates' do
position1.update(position3)
expect(position1.xpos).to eq 0
expect(position1.ypos).to eq 0
end
it 'can determine equality' do
expect(position1).to eq position2
expect(position1.eql?(position2)).to be_truthy
expect(position1 == position2).to be_truthy
end
describe 'Set operations' do
let (:position_set) { Set.new }
it 'returns nil when an identical Position is added' do
position_set.add?(position1)
position_set.add?(position3)
expect(position_set.count).to eq 2
expect(position_set.add?(position2)).to be_nil
end
end
describe 'Array operations' do
let (:position_array) { [] }
it 'returns true when testing for inclusion' do
position_array << position1
position_array << position3
expect(position_array.count).to eq 2
expect(position_array.include?(position2)).to be_truthy
end
end
end
| d7ee66f01f42f5e4828aa2955256d638ad8677d7 | [
"Markdown",
"Ruby"
] | 9 | Ruby | dharmamike/pathfinder | 2e4c1364c99161fe75cf720c68aebb0222d724a0 | b6886b374f7a4994b661c2c86f7c9863f075ec89 |
refs/heads/master | <file_sep># Amazon-scrapper
Se basa en hacer scraping de un producto en amazon. Si el precio es igual al deseado o menor envía un email
<file_sep>import requests
from bs4 import BeautifulSoup
import smtplib
import time
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
}
def send_email():
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.ehlo()
server.login('','')
body = 'Visita el siguiente link de Amazon: https://www.amazon.es/gp/product/B00CUJQ7UG/ref=ox_sc_act_title_1?smid=A1AT7YVPFBWXBL&psc=1 '
asunto = "El precio a llegado a lo deseado!!"
message = f"Subject:{asunto}\n\n {body}"
server.sendmail(
'',
'',
message
)
print("Email enviado")
server.quit()
def get_amazon_price(url):
response = requests.get(url, headers = headers)
soup = BeautifulSoup(response.content,'html.parser')
soup2 = BeautifulSoup(soup.prettify(),'html.parser')
title = soup2.find(id = "productTitle").get_text()
price = soup2.find(id = "priceblock_ourprice").get_text()
print(title.strip())
print(price.strip())
if price <= '7' :
send_email()
while(True):
get_amazon_price('https://www.amazon.es/gp/product/B00CUJQ7UG/ref=ox_sc_act_title_1?smid=A1AT7YVPFBWXBL&psc=1')
time.sleep(86400)
| 7dfac711060198c8abdd004b5a94bb9d74cd9bfe | [
"Markdown",
"Python"
] | 2 | Markdown | gelintonx/Amazon-scrapper | e958ba04e576c495726c4bfcd6b98a4cb0b1de6a | 35b05f377803f42e09d3fb5dcbdfe6093133f3dc |
refs/heads/master | <file_sep>package com.example.sopheak.ntti;
import android.content.Context;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
/**
* Created by sopheak on 28-May-17.
*/
public class myAnimator implements Animation.AnimationListener {
LinearLayout ln;
Context c;
Button btn;
public myAnimator(LinearLayout ln, Context c, Button btn) {
this.ln = ln;
this.c = c;
this.btn = btn;
}
@Override
public void onAnimationStart(Animation animation) {
this.ln.setVisibility(View.GONE);
this.btn.setVisibility(View.GONE);
Animation loadAnimation = AnimationUtils.loadAnimation(c, R.anim.fade);
this.btn.startAnimation(loadAnimation);
this.ln.startAnimation(loadAnimation);
}
@Override
public void onAnimationEnd(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
}
| bfc4f03f7e5694986e3bd0e1fc42c4ba7d8e862c | [
"Java"
] | 1 | Java | khengsopheak/LogInScreen | 76fcd71f650326099891fd670659c847173437b9 | 8aa5aea3d52c48146c2e9798f821ff0151fb422c |
refs/heads/master | <repo_name>chable/Practica--<file_sep>/Practica1/nbproject/private/private.properties
compile.on.save=true
user.properties.file=C:\\Users\\<NAME> J\\.netbeans\\7.1\\build.properties
<file_sep>/README.md
Practica--
==========
Este programa esta basado en realizar una serie de acciones como nombre de institución, nombre del alumno, y etc.<file_sep>/Practica1/src/practica1/letras.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package practica1;
/**
*
* @author <NAME>
*/
class letras
{
}
| ffbed53f8783609c4cbf5abdf6870d0540fdec5c | [
"Markdown",
"Java",
"INI"
] | 3 | INI | chable/Practica-- | 08261de7352e0e65f1cf3ad01fb4b86588319975 | 63987e57fd5db6ac39ff9fcab04997595023cfee |
refs/heads/master | <file_sep>package br.com.biblioteca.objetos;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import br.com.biblioteca.objetos.exceptions.CriacaoDeAtributoException;
import br.com.biblioteca.objetos.exceptions.DataInvalidaException;
import br.com.biblioteca.objetos.exceptions.FormatoDeDataInvalidoException;
import br.com.biblioteca.objetos.interfaces.ItemBiblioteca;
/**
*
* @author aline.correa
*
*/
public class Livro implements Comparable<Livro>, ItemBiblioteca {
private int digitoVerificador;
private CodigoSequencial codigo = new CodigoSequencial();
private String codigoSequencial;
private String titulo;
private String resumo;
private String codigoDeBarras;
private String quantidadeDePaginas;
private String local;
private Calendar dataDeAquisicao;
private Set<Autor> autor;
private Categoria categoria;
private static final SimpleDateFormat formatoData = new SimpleDateFormat("dd/MM/yyyy");
// Construtores
public Livro() {
setCodigoSequencial(codigo.criarCodigoLivro());
setDigitoVerificador();
setCodigoDeBarras();
}
// Métodos Private
private void setCodigoDeBarras() {
int prefixoDoPaisDeRegistroDaEmpresa = 789;
int identificadorDaEmpresa = 73217;
String codigoSequencial = verificaCodigoSequencial(this.getCodigoSequencial());
int digitoVerificador = this.getDigitoVerificador();
String stringCodigoDeBarras = "" + prefixoDoPaisDeRegistroDaEmpresa + identificadorDaEmpresa + codigoSequencial
+ digitoVerificador;
this.codigoDeBarras = stringCodigoDeBarras;
}
private void verificarDataDeAquisicao(Calendar dataVerifica) throws DataInvalidaException {
Calendar dataDeHoje = Calendar.getInstance();
if (dataVerifica.getTime().after(dataDeHoje.getTime())) {
throw new DataInvalidaException("*** ERRO: Data inserida posterior a data atual! ***");
}
}
private void setDigitoVerificador() {
List<Integer> numeros = calculaDigitoVerificador();
this.digitoVerificador = numeros.get(12);
}
private String verificaCodigoSequencial(String codigo) {
if (!(codigo.length() == 4)) {
for (int tamanho = codigo.length(); tamanho != 4;) {
codigo = "0" + codigo;
tamanho = codigo.length();
}
}
return codigo;
}
private List<Integer> calculaDigitoVerificador() {
String codigoSequencial = verificaCodigoSequencial(this.getCodigoSequencial());
List<Integer> numeros = new ArrayList<>();
numeros.add(7);
numeros.add(8);
numeros.add(9);
numeros.add(7);
numeros.add(3);
numeros.add(2);
numeros.add(1);
numeros.add(7);
for (int posicao = 0; posicao < 4; posicao++) {
String num = String.valueOf(codigoSequencial.charAt(posicao));
int numero = Integer.parseInt(num);
numeros.add(numero);
}
int somaImpares = 0;
int somaPares = 0;
// soma dos numeros nas posicões pares
for (int posicao = 0; posicao < 11;) {
int num = numeros.get(posicao);
somaPares += num;
posicao += 2;
}
// soma dos numeros nas posicões impares
for (int posicao = 1; posicao <= 11;) {
int num = numeros.get(posicao);
somaImpares += num;
posicao += 2;
}
int numPares = somaPares * 3;
int numeroFinal = somaImpares + numPares;
int contador = 0;
while (numeroFinal % 10 != 0) {
numeroFinal = numeroFinal + 1;
contador += 1;
}
numeros.add(contador);
return numeros;
}
private void setCodigoSequencial(int contador) {
String codigoString = String.valueOf(contador);
this.codigoSequencial = codigoString;
}
// Métodos Public
public int getDigitoVerificador() {
return this.digitoVerificador;
}
public String getCodigoSequencial() {
return this.codigoSequencial;
}
public void verificacaoDeDadosLivro() throws CriacaoDeAtributoException {
if (this.getTitulo() == null) {
throw new CriacaoDeAtributoException("*** ERRO: O livro está sem titulo. Por favor, informe o título. ***");
}
if (this.getTitulo().equals("")) {
throw new CriacaoDeAtributoException("*** ERRO: O livro está sem titulo. Por favor, informe o título. ***");
}
if (this.getAutor().isEmpty()) {
throw new CriacaoDeAtributoException(
"*** ERRO: O livro está sem autor. Por Favor, informe pelo menos um(a) autor(a). ***");
}
if (this.getCategoria() == null) {
throw new CriacaoDeAtributoException(
"*** ERRO: O livro está sem categoria. Por favor, informe a categoria do livro. ***");
}
if (this.getLocal() == null) {
throw new CriacaoDeAtributoException(
"*** ERRO: O livro está sem local. Por favor, informe o local do livro. ***");
}
if (this.getLocal().equals("")) {
throw new CriacaoDeAtributoException(
"*** ERRO: O livro está sem local. Por favor, informe o local do livro. ***");
}
}
public void setTitulo(String titulo) {
titulo = titulo.toUpperCase();
this.titulo = titulo;
}
public String getTitulo() {
return this.titulo;
}
public void setResumo(String resumo) {
try {
if (resumo.equals("")) {
this.resumo = "*** Resumo não informado ***";
} else {
this.resumo = resumo;
}
} catch (NullPointerException e) {
this.resumo = "*** Resumo não informado ***";
}
}
public String getResumo() {
return this.resumo;
}
public String getCodigoDeBarras() {
return this.codigoDeBarras;
}
public void setQuantidadeDePaginas(String quantidadeDePaginas) {
try {
if (quantidadeDePaginas.equals("")) {
this.quantidadeDePaginas = "*** Quantidade de páginas não informado ***";
} else {
this.quantidadeDePaginas = quantidadeDePaginas;
}
} catch (NullPointerException e) {
this.quantidadeDePaginas = "*** Quantidade de páginas não informado ***";
}
}
public String getQuantidadeDePaginas() {
return this.quantidadeDePaginas;
}
public void setLocal(String local) {
local = local.toUpperCase();
this.local = local;
}
public String getLocal() {
return this.local;
}
public void setDataDeAquisicao(String dataDeAquisicao)
throws FormatoDeDataInvalidoException, DataInvalidaException {
try {
Date date = formatoData.parse(dataDeAquisicao);
Calendar dataVerifica = Calendar.getInstance();
dataVerifica.setTime(date);
verificarDataDeAquisicao(dataVerifica);
this.dataDeAquisicao = Calendar.getInstance();
this.dataDeAquisicao.setTime(date);
} catch (ParseException e) {
throw new FormatoDeDataInvalidoException(
"Data inserida invalida, por favor utilize o formato (dd/mm/yyyy)");
} catch (NullPointerException e) {
this.dataDeAquisicao = null;
return;
}
}
public String getDataDeAquisicao() {
try {
if (this.dataDeAquisicao.equals(null)) {
return "*** Data de Aquisição não informada ***";
}
if (this.dataDeAquisicao.equals("")) {
return "*** Data de Aquisição não informada ***";
}
String dataString = formatoData.format(this.dataDeAquisicao.getTime());
return dataString;
} catch (NullPointerException e) {
return "*** Data de Aquisição não informada ***";
}
}
public void setAutor(Set<Autor> autor) {
this.autor = autor;
}
public Set<Autor> getAutor() {
return this.autor;
}
public void setCategoria(Categoria categoria) {
this.categoria = categoria;
}
public Categoria getCategoria() {
return this.categoria;
}
// Métodos da classe
@Override
public int compareTo(Livro outroLivro) {
if (this.titulo != null) {
int comparacao = this.titulo.compareTo(outroLivro.getTitulo());
if (comparacao != 0) {
return comparacao;
}
}
if (this.codigoSequencial != null) {
int comparacaoCodigoSequencial = this.codigoSequencial.compareTo(outroLivro.getCodigoSequencial());
if (comparacaoCodigoSequencial != 0) {
return comparacaoCodigoSequencial;
}
}
return 0;
}
@Override
public String toString() {
return "Livro: " + titulo + ", (" + quantidadeDePaginas + " Páginas) | Categoria: " + categoria
+ " | Autor(es/a/as): " + autor + " | Código De Barras: " + codigoDeBarras + " | Código Sequencial: "
+ codigoSequencial + " | Data de Aquisição: " + getDataDeAquisicao() + " | Resumo: " + resumo + ".";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((codigoSequencial == null) ? 0 : codigoSequencial.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Livro other = (Livro) obj;
if (codigoSequencial == null) {
if (other.codigoSequencial != null)
return false;
} else if (!codigoSequencial.equals(other.codigoSequencial))
return false;
return true;
}
}
<file_sep>var controle = document.querySelector('.nfavorito');
controle.onclick = function() {
if (controle.className == 'nfavorito') {
controle.className = 'favorito';
} else {
controle.className = 'nfavorito';
}
return false;
};
var controle1 = document.querySelector('.nfavorito1');
controle1.onclick = function() {
if (controle1.className == 'nfavorito1') {
controle1.className = 'favorito1';
} else {
controle1.className = 'nfavorito1';
}
return false;
};
var controle2 = document.querySelector('.nfavorito2');
controle2.onclick = function() {
if (controle2.className == 'nfavorito2') {
controle2.className = 'favorito2';
} else {
controle2.className = 'nfavorito2';
}
return false;
};
var controle3 = document.querySelector('.nfavorito3');
controle3.onclick = function() {
if (controle3.className == 'nfavorito3') {
controle3.className = 'favorito3';
} else {
controle3.className = 'nfavorito3';
}
return false;
};
var controle4 = document.querySelector('.nfavorito4');
controle4.onclick = function() {
if (controle4.className == 'nfavorito4') {
controle4.className = 'favorito4';
} else {
controle4.className = 'nfavorito4';
}
return false;
};
<file_sep>package br.com.biblioteca.console.edita;
import java.util.Scanner;
import br.com.biblioteca.console.cadastro.CadastroDeCategoria;
import br.com.biblioteca.console.confirmacao.Confirmacao;
import br.com.biblioteca.console.pesquisa.categoria.PesquisaCategoriaPorCodigoSequencial;
import br.com.biblioteca.objetos.Categoria;
import br.com.biblioteca.repositorios.interfaces.Categorias;
public class EditaCategoria {
private Scanner scanner;
private static Categorias bancoDeCategorias;
public EditaCategoria(Scanner scanner, Categorias bancoDeCategorias){
this.scanner = scanner;
EditaCategoria.bancoDeCategorias = bancoDeCategorias;
}
public void editarCategoria(){
System.out.println("Insira o código sequencial da categoria: ");
scanner.nextLine();
String codigoSequencial = scanner.nextLine();
System.out.println("Buscando categoria...");
boolean pesquisa = new PesquisaCategoriaPorCodigoSequencial(scanner, bancoDeCategorias).verificaExistenciaDeCategoriaPorCodigoSequencial(codigoSequencial);
if(pesquisa){
Categoria categoria = bancoDeCategorias.buscarPorCodigoSequencial(codigoSequencial);
System.out.println("Categoria Encontrada: " + categoria + " | Código Sequencial: " + categoria.getCodigoSequencial());
boolean decisao = new Confirmacao(scanner, categoria).confirmaEdicao();
if(decisao){
bancoDeCategorias.editar(categoria);
CadastroDeCategoria cadastraCategoriaNova = new CadastroDeCategoria(scanner,bancoDeCategorias);
cadastraCategoriaNova.cadastrarCategoria();
}else {
return;
}
}else{
System.out.println("Categoria não encontrada. Por favor, verifique o código informado e tente novamente.");
return;
}
}
}
<file_sep>package br.com.biblioteca.console.pesquisa.livro;
import java.util.Scanner;
import br.com.biblioteca.objetos.Livro;
import br.com.biblioteca.repositorios.interfaces.Livros;
public class PesquisaLivroPorCodigoDeBarras {
private Scanner scanner;
private static Livros bancoDeLivros;
public PesquisaLivroPorCodigoDeBarras( Scanner scanner,Livros bancoDeLivros){
this.scanner = scanner;
PesquisaLivroPorCodigoDeBarras.bancoDeLivros = bancoDeLivros;
}
public void pesquisaLivroPorCodigoDeBarras(){
System.out.println("Insira o código de barras:");
scanner.nextLine();
String codigoParaPesquisar = scanner.nextLine();
boolean verifica = verificarExistenciaDeLivroPorCodigoDeBarras(codigoParaPesquisar);
if(verifica){
Livro livroEncontrado = bancoDeLivros.buscarPorCodigoDeBarras(codigoParaPesquisar);
System.out.println("Livro encontrado:");
System.out.println(livroEncontrado);
}else{
System.out.println("Livro não encontrado, verifique o código informado e tente novamente.");
return;
}
}
private boolean verificarExistenciaDeLivroPorCodigoDeBarras(String codigo) {
Livro busca = bancoDeLivros.buscarPorCodigoDeBarras(codigo);
if(busca != null){
return true;
}
return false;
}
}
<file_sep>var selecao1 = document.querySelector('.paypal1');
selecao1.onclick = function(){
var a = selecao1.getAttribute("src");
if(a == "imagens/check_before1.png"){
a = selecao1.setAttribute("src","imagens/check_after1.png");
}else{
a = selecao1.setAttribute("src","imagens/check_before1.png");
}
return false
};<file_sep>package br.com.biblioteca.console.edita;
import java.util.Scanner;
import br.com.biblioteca.console.cadastro.CadastroDeLivro;
import br.com.biblioteca.console.confirmacao.Confirmacao;
import br.com.biblioteca.console.pesquisa.livro.PesquisaLivroPorCodigoSequencial;
import br.com.biblioteca.objetos.Livro;
import br.com.biblioteca.objetos.exceptions.FormatoDeDataInvalidoException;
import br.com.biblioteca.repositorios.interfaces.Autores;
import br.com.biblioteca.repositorios.interfaces.Categorias;
import br.com.biblioteca.repositorios.interfaces.Livros;
/**
*
* @author aline.correa
*
* Script de integração de edição: Interação com o usuário e edição de
* livro
*
*/
public class EditaLivro {
private Scanner scanner;
private static Livros bancoDeLivros;
private static Autores bancoDeAutores;
private static Categorias bancoDeCategorias;
public EditaLivro(Scanner scanner, Livros bancoDeLivros, Autores bancoDeAutores, Categorias bancoDeCategorias) {
this.scanner = scanner;
EditaLivro.bancoDeLivros = bancoDeLivros;
EditaLivro.bancoDeAutores = bancoDeAutores;
EditaLivro.bancoDeCategorias = bancoDeCategorias;
}
public void editarLivro() throws FormatoDeDataInvalidoException {
scanner.nextLine();
System.out.println("Insira o código sequencial do livro:");
String codigo = scanner.nextLine();
boolean pesquisa = new PesquisaLivroPorCodigoSequencial(scanner, bancoDeLivros)
.verificaExistenciaDeLivroPorCodigoSequencial(codigo);
System.out.println("Pesquisando livro no banco...");
if (pesquisa) {
Livro livroEncontrado = bancoDeLivros.buscarPorCodigoSequencial(codigo);
System.out.println(livroEncontrado);
boolean confirmaEdicao = new Confirmacao(scanner, livroEncontrado).confirmaEdicao();
if (confirmaEdicao) {
bancoDeLivros.excluir(livroEncontrado);
CadastroDeLivro cadastraLivro = new CadastroDeLivro(scanner, bancoDeLivros, bancoDeAutores,
bancoDeCategorias);
cadastraLivro.cadastrarLivro();
} else {
return;
}
}
}
}
<file_sep>package br.com.biblioteca.objetos;
import java.io.Serializable;
import java.util.UUID;
import br.com.biblioteca.objetos.interfaces.ItemBiblioteca;
/**
*
*author aline.correa
*
*/
public class Categoria implements ItemBiblioteca, Comparable<Categoria>,Serializable{
private static final long serialVersionUID = 1L;
private String codigoSequencial;
private String descricao;
// Construtores
public Categoria(String descricao) {
setDescricao(descricao);
setCodigoSequencial();
}
// Métodos da classe
@Override
public String toString() {
return descricao;
}
// Getters e Setters
public void setCodigoSequencial() {
UUID idOne = UUID.randomUUID();
this.codigoSequencial = idOne.toString().replaceAll("-", "");
}
public String getCodigoSequencial() {
return this.codigoSequencial;
}
public void setDescricao(String descricao) {
descricao = descricao.toUpperCase();
this.descricao = descricao;
}
public String getDescricao() {
return this.descricao;
}
public int compareTo(Categoria outraCategoria) {
if (this.descricao != null) {
int comparacao = this.descricao.compareTo(outraCategoria.getDescricao());
if (comparacao != 0) {
return comparacao;
}
}
if (this.codigoSequencial != null) {
int comparacaoCodigo = this.codigoSequencial.compareTo(outraCategoria.getCodigoSequencial());
if (comparacaoCodigo != 0) {
return comparacaoCodigo;
}
}
return 0;
}
}
<file_sep>package br.com.biblioteca.console.pesquisa.categoria;
import java.util.Scanner;
import br.com.biblioteca.objetos.Categoria;
import br.com.biblioteca.repositorios.interfaces.Categorias;
/**
*
* @author aline.correa
*
* Script de integração de pesquisa: Interação com o usuário e pesquisa
* de Categorias pelo código sequencial no banco
*
*/
public class PesquisaCategoriaPorCodigoSequencial {
private Scanner scanner;
private static Categorias bancoDeCategorias;
public PesquisaCategoriaPorCodigoSequencial(Scanner scanner, Categorias bancoDeCategorias) {
this.scanner = scanner;
PesquisaCategoriaPorCodigoSequencial.bancoDeCategorias = bancoDeCategorias;
}
public void pesquisarCategoriaPorCodigoSequencial() {
System.out.println("Insira o código sequencial: ");
scanner.nextLine();
String codigoParaPesquisar = scanner.nextLine();
System.out.println("Pesquisando categoria(s) no banco...");
boolean verifica = verificaExistenciaDeCategoriaPorCodigoSequencial(codigoParaPesquisar);
if (verifica) {
Categoria busca = bancoDeCategorias.buscarPorCodigoSequencial(codigoParaPesquisar);
System.out.println("Categoria: " + busca + " | Código Sequencial: " + busca.getCodigoSequencial());
} else {
System.out.println("Categoria não encontrada, verifique o código informado e tente novamente.");
return;
}
}
public boolean verificaExistenciaDeCategoriaPorCodigoSequencial(String codigo) {
Categoria busca = bancoDeCategorias.buscarPorCodigoSequencial(codigo);
if (busca != null) {
return true;
}
return false;
}
}
<file_sep>package br.com.biblioteca.objetos.exceptions;
/**
*
* @author aline.correa
*
*/
@SuppressWarnings("serial")
public class DescricaoCategoriaNulaException extends Exception {
public DescricaoCategoriaNulaException(String mensagem) {
super(mensagem);
}
}
<file_sep>function myFunction(filtro) {
var valor = document.querySelector(filtro).value;
var filter, table, tr, td, i;
console.log(document.querySelector(filtro));
console.log(document.querySelector(filtro).value);
console.log(valor);
table = document.getElementById("tabela");
tr = table.getElementsByTagName("tr");
console.log(tr);
filter = valor.toUpperCase();
console.log(filtro);
for (i = 1; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[5];
console.log(td);
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
console.log(td.innerHTML);
console.log("filtro nada");
tr[i].style.display = "";
}else{
console.log(td.innerHTML);
console.log("filtro alguma coisa");
tr[i].style.display = "none";
}
}
}
}
<file_sep>package br.com.biblioteca.repositorios.memoria;
import static org.junit.Assert.*;
import java.util.Set;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import br.com.biblioteca.objetos.Categoria;
import br.com.biblioteca.objetos.exceptions.DescricaoCategoriaNulaException;
import br.com.biblioteca.objetos.testes.ZerarTestesDeAutores;
import br.com.biblioteca.repositorios.interfaces.Categorias;
/**
* @author aline.correa
*
* ETAPAS NOS TESTES
*
* 1 - A (Organizar) 2 - A (Executar) 3 - A (Verificar)
*
*/
public class BancoDeCategoriasEmMemoriaTest {
private Categorias banco = new BancoDeCategoriasEmMemoria();
@Rule
public ExpectedException exception = ExpectedException.none();
// Inicia Dados padrão para os testes
private void prepararDadosParaPesquisa() throws DescricaoCategoriaNulaException {
Categoria categoria1 = new Categoria("drama");
banco.adicionar(categoria1);
Categoria categoria2 = new Categoria("romance");
banco.adicionar(categoria2);
Categoria categoria3 = new Categoria("suspense");
banco.adicionar(categoria3);
Categoria categoria4 = new Categoria("conto");
banco.adicionar(categoria4);
}
@After
public void aposOTerminoDeCadaTeste() {
new ZerarTestesDeAutores().zerar();
}
@Test
public void testAdicionar() throws DescricaoCategoriaNulaException {
Categoria categoria = new Categoria("teste adicionar");
banco.adicionar(categoria);
assertTrue(banco.listar().contains(categoria));
}
@Test
public void testExcluir() throws DescricaoCategoriaNulaException {
Categoria categoria = new Categoria("teste excluir");
banco.adicionar(categoria);
banco.excluir(categoria);
assertFalse(banco.listar().contains(categoria));
}
@Test
public void testEditar() throws DescricaoCategoriaNulaException {
Categoria categoria = new Categoria("teste editar");
banco.adicionar(categoria);
banco.editar(categoria);
assertFalse(banco.listar().contains(categoria));
}
@Test
public void testListar() throws DescricaoCategoriaNulaException {
prepararDadosParaPesquisa();
assertFalse(banco.listar().isEmpty());
}
@Test
public void testBuscarCategoriaPorDescricao() throws DescricaoCategoriaNulaException {
prepararDadosParaPesquisa();
Set<Categoria> categoriasEncontradas = banco.buscarCategoriaPorDescricao("conto");
System.out.println(categoriasEncontradas);
assertEquals(1, categoriasEncontradas.size());
}
@Test
public void testBuscarCategoriaPorDescricaoSemNenhumResultadoNaPesquisa() throws DescricaoCategoriaNulaException {
exception.expect(NullPointerException.class);
prepararDadosParaPesquisa();
@SuppressWarnings("unused")
Set<Categoria> categoriasEncontradas = banco.buscarCategoriaPorDescricao("z");
}
@Test
public void testBuscarPorCodigoSequencial() throws DescricaoCategoriaNulaException {
prepararDadosParaPesquisa();
Categoria categoriaEncontrada = banco.buscarPorCodigoSequencial("2");
assertEquals("ROMANCE", categoriaEncontrada.getDescricao());
}
@Test
public void testBuscarPorCodigoSequencialQueNaoExisteNoBanco() throws DescricaoCategoriaNulaException {
prepararDadosParaPesquisa();
Categoria categoriaEncontrada = banco.buscarPorCodigoSequencial("0");
assertEquals(null, categoriaEncontrada);
}
}
<file_sep>package br.com.biblioteca.codigosparaauxilio;
public class TesteComparacaoDeLong {
public static void main(String[] args) {
long a = 1111;
Long b = 1111l; //Antes: Long b = 1113;
if(a == b)
{
System.out.println("Iguais");
}else{
System.out.println("Não são iguais");
}
}
}
<file_sep>package br.com.biblioteca.repositorios.interfaces;
import java.util.Set;
import br.com.biblioteca.objetos.Livro;
/**
*
* @author aline.correa
*
*/
public interface Livros extends AcoesNoRepositorio<Livro> {
Set<Livro> buscarPorTitulo(String titulo);
Livro buscarPorCodigoSequencial(String codigoSequencial);
Livro buscarPorCodigoDeBarras(String codigoDeBarras);
Set<Livro> buscarPorCategoria(String descricaoCategoria);
Set<Livro> buscarPorAutor(String nomeAutor);
}
<file_sep>package br.com.biblioteca.console.pesquisa.livro;
import java.util.List;
import java.util.Scanner;
import br.com.biblioteca.objetos.Livro;
import br.com.biblioteca.repositorios.interfaces.Livros;
public class PesquisaLivroPorCategoria {
private Scanner scanner;
private static Livros bancoDeLivros;
public PesquisaLivroPorCategoria(Scanner scanner, Livros bancoDeLivros) {
this.scanner = scanner;
PesquisaLivroPorCategoria.bancoDeLivros = bancoDeLivros;
}
public void pesquisaLivroPorCategoria() {
System.out.println("Insira a categoria:");
scanner.nextLine();
String categoriaParaPesquisar = scanner.nextLine();
boolean verifica = verificarExistenciaDeLivroPorCategoria(categoriaParaPesquisar);
if (verifica) {
List<Livro> livrosEncontrados = bancoDeLivros.buscarPorCategoria(categoriaParaPesquisar);
System.out.println("Livro(s) encontrado(s):");
for (Livro livro : livrosEncontrados) {
System.out.println(livro);
}
} else {
System.out.println("Livro não encontrado, verifique a categoria informada e tente novamente.");
return;
}
}
private boolean verificarExistenciaDeLivroPorCategoria(String categoria) {
List<Livro> busca = bancoDeLivros.buscarPorCategoria(categoria);
if (!busca.isEmpty()) {
return true;
}
return false;
}
}
<file_sep>package br.com.biblioteca.repositorios.interfaces;
import java.util.Set;
/**
*
* @author aline.correa
*
*
*/
public interface AcoesNoRepositorio<T> {
void adicionar(T registro);
void excluir(T registro);
void editar(T registro);
Set<T> listar();
}
<file_sep>function filtrar() {
$('.botao-filtro').on('click', function () {
var $target = $(this).data('etiqueta');
if ($target != 'todos') {
$('.table tr').css('display', 'none');
$('.table tr[data-status="' + $target + '"]').fadeIn('slow');
} else {
$('.table tr').css('display', 'none').fadeIn('slow');
}
});
}
<file_sep>package br.com.biblioteca.objetos;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import java.util.UUID;
import br.com.biblioteca.objetos.interfaces.ItemBiblioteca;
import br.com.biblioteca.objetos.verificacoes.VerificaLivro;
public class Livro implements Comparable<Livro>,ItemBiblioteca {
static private int contadorDeLivrosRegistrados = 0;
private int digitoVerificador;
private String codigoSequencial;
private String titulo;
private String resumo;
private String codigoDeBarras;
private int quantidadeDePaginas;
private String local;
private Calendar dataDeAquisicao;
private Set<Autor> autor;
private Categoria categoria;
private static final SimpleDateFormat formatoData = new SimpleDateFormat("dd/MM/yyyy");
// Construtores
public Livro(){
setCodigoSequencial();
contadorDeLivrosRegistrados += 1;
setDigitoVerificador(contadorDeLivrosRegistrados);
if (contadorDeLivrosRegistrados == 10) {
contadorDeLivrosRegistrados = 0;
setDigitoVerificador(contadorDeLivrosRegistrados);
}
setCodigoDeBarras();
}
public Livro(Set<Autor> autor, Categoria categoria, String titulo, String local) throws NullPointerException{
try{
VerificaLivro verificacao = new VerificaLivro();
verificacao.verificacaoDeDadosLivro(this);
setCodigoSequencial();
contadorDeLivrosRegistrados += 1;
setDigitoVerificador(contadorDeLivrosRegistrados);
if (contadorDeLivrosRegistrados == 10) {
contadorDeLivrosRegistrados = 0;
setDigitoVerificador(contadorDeLivrosRegistrados);
}
setCodigoDeBarras();
setAutor(autor);
setCategoria(categoria);
setTitulo(titulo);
setLocal(local);
}catch(NullPointerException e){
System.out.println(e.getMessage());
}
}
// Métodos da classe
// CompareTO : titulo e codSequencial
@Override
public int compareTo(Livro outroLivro) {
if (this.titulo != null) {
int comparacao = this.titulo.compareTo(outroLivro.getTitulo());
if (comparacao != 0) {
return comparacao;
}
}
if (this.codigoSequencial != null) {
int comparacaoCodigoSequencial = this.codigoSequencial.compareTo(outroLivro.getCodigoSequencial());
if (comparacaoCodigoSequencial != 0) {
return comparacaoCodigoSequencial;
}
}
return 0;
}
@Override
public String toString() {
return "Livro: " + titulo + ", (" + quantidadeDePaginas + " Páginas) | Categoria: " + categoria +" | Autor(es/a/as): " + autor + " | Código De Barras: " + codigoDeBarras + " | Data de Aquisição: " + getDataDeAquisicao() + " | Resumo: "+ resumo +".";
}
// Getters e Setters
public void setCodigoSequencial() {
UUID idOne = UUID.randomUUID();
this.codigoSequencial = idOne.toString().replaceAll("-", "");
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((codigoSequencial == null) ? 0 : codigoSequencial.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Livro other = (Livro) obj;
if (codigoSequencial == null) {
if (other.codigoSequencial != null)
return false;
} else if (!codigoSequencial.equals(other.codigoSequencial))
return false;
return true;
}
public String getCodigoSequencial() {
return this.codigoSequencial;
}
public void setTitulo(String titulo) {
titulo = titulo.toUpperCase();
this.titulo = titulo;
}
public String getTitulo() {
return this.titulo;
}
public String getResumo() {
return this.resumo;
}
public void setResumo(String resumo) {
this.resumo = resumo;
}
public void setCodigoDeBarras() {
// 13 digitos
// 3 primeiros digitos: prefixo do pais de registro da empresa(789)
// do quarto ao nono digito:identificacao da empresa(456789)
// do decimo ao decimo segundo:referencia do produto(codSequencial -
// 001)
// decimo terceiro: digito verificador(5)
int prefixoDoPaisDeRegistroDaEmpresa = 847;
int identificadorDaEmpresa = 892174;
String codigoSequencial = this.getCodigoSequencial();
int digitoVerificador = this.getDigitoVerificador();
// TODO Livro: tem que retirar/usar apenas 3 numeros do CodSequencial
// para utilizar no codDeBarras
String stringCodigoDeBarras = "" + prefixoDoPaisDeRegistroDaEmpresa + identificadorDaEmpresa + codigoSequencial
+ digitoVerificador;
this.codigoDeBarras = stringCodigoDeBarras;
}
public String getCodigoDeBarras() {
return this.codigoDeBarras;
}
public void setQuantidadeDePaginas(int quantidadeDePaginas) {
this.quantidadeDePaginas = quantidadeDePaginas;
}
public int getQuantidadeDePaginas() {
return this.quantidadeDePaginas;
}
public void setLocal(String local) {
local = local.toUpperCase();
this.local = local;
}
public String getLocal() {
return this.local;
}
public void setDataDeAquisicao(String dataDeAquisicao) {
try {
Date date = formatoData.parse(dataDeAquisicao);
Calendar dataVerifica = Calendar.getInstance();
dataVerifica.setTime(date);
if (verificarDataDeAquisicao(dataVerifica)) {
this.dataDeAquisicao = Calendar.getInstance();
this.dataDeAquisicao.setTime(date);
} else {
System.out.println("######################" + dataDeAquisicao);
}
} catch (ParseException e) {
throw new IllegalArgumentException("Data inserida invalida, por favor utilize o formato (dd/mm/yyyy)");
}
}
private boolean verificarDataDeAquisicao(Calendar dataVerifica) {
Calendar dataDeHoje = Calendar.getInstance();
if (dataVerifica.getTime().after(dataDeHoje.getTime())) {
return false;
}
return true;
}
public String getDataDeAquisicao() {
if (this.dataDeAquisicao == null) {
return "";
}
String dataString = formatoData.format(this.dataDeAquisicao.getTime());
return dataString;
}
public void setAutor(Set<Autor> autor) {
this.autor = autor;
}
public Set<Autor> getAutor() {
return this.autor;
}
public void setCategoria(Categoria categoria) {
this.categoria = categoria;
}
public String getCategoria() {
Categoria categoriaDesseLivro = this.categoria;
String descricaoCategoriaDesseLivro = categoriaDesseLivro.getDescricao();
return descricaoCategoriaDesseLivro;
}
public int getDigitoVerificador() {
return this.digitoVerificador;
}
public void setDigitoVerificador(int digitoVerificador) {
this.digitoVerificador = digitoVerificador;
}
}
<file_sep>package br.com.biblioteca.repositorios.bd;
/**
* @author aline.correa
*
*/
public class LivrosDB { //implements Livros
/* @Override
public void adicionar(Livro registro) {
}
@Override
public void excluir(Livro registro) {
}
@Override
public Set<Livro> listar() {
return null;
}
@Override
public Set<Livro> buscarPorTitulo(String titulo) {
return null;
}
@Override
public Set<Livro> buscarPorCodigoSequencial(long codigoSequencial) {
return null;
}
@Override
public Set<Livro> buscarPorCodigoDeBarras(long codigoDeBarras) {
return null;
}*/
}
<file_sep>package br.com.biblioteca.repositorios.interfaces;
import java.util.Set;
import br.com.biblioteca.objetos.Autor;
public interface Autores extends AcoesNoRepositorio<Autor> {
Set<Autor> buscarPorNome(String nome);
Set<Autor> buscarPorNacionalidade(String nacionalidade);
Set<Autor> buscarPorDataDeNascimento(String dataDeNascimento);
Autor buscarPorCodigoSequencial(String codigoSequencial);
}
<file_sep>package br.com.biblioteca.console.remove;
import java.util.Scanner;
import br.com.biblioteca.console.confirmacao.Confirmacao;
import br.com.biblioteca.console.pesquisa.categoria.PesquisaCategoriaPorCodigoSequencial;
import br.com.biblioteca.objetos.Categoria;
import br.com.biblioteca.repositorios.interfaces.Categorias;
/**
*
* @author aline.correa
*
* Script de integração de remoção: Interação com o usuário e remoção de
* Categoria
*
*/
public class RemoveCategoria {
private static Categorias bancoDeCategorias;
private Scanner scanner;
public RemoveCategoria(Scanner scanner, Categorias bancoDeCategorias) {
this.scanner = scanner;
RemoveCategoria.bancoDeCategorias = bancoDeCategorias;
}
public void removerCategoria() {
System.out.println("Insira o código sequencial da categoria: ");
scanner.nextLine();
String codigoSequencial = scanner.nextLine();
System.out.println("Buscando categoria...");
boolean verifica = new PesquisaCategoriaPorCodigoSequencial(scanner, bancoDeCategorias)
.verificaExistenciaDeCategoriaPorCodigoSequencial(codigoSequencial);
if (verifica) {
Categoria categoria = bancoDeCategorias.buscarPorCodigoSequencial(codigoSequencial);
System.out.println(
"Categoria Encontrada: " + categoria + " | Código Sequencial: " + categoria.getCodigoSequencial());
boolean decisao = new Confirmacao(scanner, categoria).confirmaRemocao();
if (decisao) {
bancoDeCategorias.excluir(categoria);
System.out.println("Categoria " + categoria + " removida.");
} else {
return;
}
} else {
System.out.println(
"Categoria não encontrada. Por favor, verifique o código sequencial informado e tente novamente.");
return;
}
}
}
<file_sep>package br.com.biblioteca.console.lista;
import java.util.Set;
import br.com.biblioteca.objetos.Categoria;
import br.com.biblioteca.repositorios.interfaces.Categorias;
public class ListaDeCategorias {
private static Categorias bancoDeCategorias;
public ListaDeCategorias(Categorias bancoDeCategorias2){
ListaDeCategorias.bancoDeCategorias = bancoDeCategorias2;
}
public void listarCategorias(){
Set<Categoria> listaDeCategorias = bancoDeCategorias.listar();
for (Categoria categoria : listaDeCategorias) {
System.out.println("Categoria: " + categoria + " | Código Sequencial: " + categoria.getCodigoSequencial());
}
}
}
<file_sep>package br.com.biblioteca.objetos;
import java.io.Serializable;
import br.com.biblioteca.objetos.exceptions.DescricaoCategoriaNulaException;
import br.com.biblioteca.objetos.interfaces.ItemBiblioteca;
/**
*
* author aline.correa
*
*/
public class Categoria implements ItemBiblioteca, Comparable<Categoria>, Serializable {
private static final long serialVersionUID = 1L;
private String codigoSequencial;
private CodigoSequencial codigo = new CodigoSequencial();
private String descricao;
// Construtores
public Categoria(String descricao) throws DescricaoCategoriaNulaException {
setDescricao(descricao);
setCodigoSequencial(codigo.criarCodigoCategoria());
}
// Métodos Private
private void setCodigoSequencial(int contador) {
String codigoString = String.valueOf(contador);
this.codigoSequencial = codigoString;
}
// Métodos Public
public String getCodigoSequencial() {
return this.codigoSequencial;
}
public void setDescricao(String descricao) throws DescricaoCategoriaNulaException {
try {
if (descricao.equals("")) {
throw new DescricaoCategoriaNulaException(
"*** ERRO: Descrição de categoria nula. Por favor, informe a decrição da categoria. ***");
}
descricao = descricao.toUpperCase();
this.descricao = descricao;
} catch (NullPointerException e) {
throw new DescricaoCategoriaNulaException(
"*** ERRO: Descrição de categoria nula. Por favor, informe a decrição da categoria. ***");
}
}
public String getDescricao() {
return this.descricao;
}
// Métodos da Classe
@Override
public String toString() {
return this.getDescricao();
}
public int compareTo(Categoria outraCategoria) {
if (this.descricao != null) {
int comparacao = this.descricao.compareTo(outraCategoria.getDescricao());
if (comparacao != 0) {
return comparacao;
}
}
if (this.codigoSequencial != null) {
int comparacaoCodigo = this.codigoSequencial.compareTo(outraCategoria.getCodigoSequencial());
if (comparacaoCodigo != 0) {
return comparacaoCodigo;
}
}
return 0;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((descricao == null) ? 0 : descricao.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Categoria other = (Categoria) obj;
if (descricao == null) {
if (other.descricao != null)
return false;
} else if (!descricao.equals(other.descricao))
return false;
return true;
}
}
<file_sep>package br.com.biblioteca.console.lista;
import java.util.Set;
import br.com.biblioteca.objetos.Categoria;
import br.com.biblioteca.repositorios.interfaces.Categorias;
/**
*
* @author aline.correa
*
* Script de integração de listagem: Interação com o usuário e listagem
* de Categorias no banco
*
*/
public class ListaDeCategorias {
private static Categorias bancoDeCategorias;
public ListaDeCategorias(Categorias bancoDeCategorias2) {
ListaDeCategorias.bancoDeCategorias = bancoDeCategorias2;
}
public void listarCategorias() {
Set<Categoria> listaDeCategorias = bancoDeCategorias.listar();
for (Categoria categoria : listaDeCategorias) {
System.out.println("Categoria: " + categoria + " | Código Sequencial: " + categoria.getCodigoSequencial());
}
}
}
<file_sep>function buscarData(){
var hoje = new Date();
var ano = hoje.getFullYear();
var dia = hoje.getDate();
var mes = hoje.getMonth();
var meses = ["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"];
var mes = meses[mes];
document.write(mes+" "+dia+", "+ano);
}
window.onload = buscarData()<file_sep>package br.com.biblioteca.repositorios.arquivo;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import br.com.biblioteca.objetos.Categoria;
import br.com.biblioteca.repositorios.interfaces.Categorias;
/**
*
* @author aline.correa
*
*/
public class BancoDeCategoriasEmArquivo implements Categorias {
private static Set<Categoria> banco = new TreeSet<>();
@Override
public void adicionar(Categoria categoria) {
if (categoria.getDescricao() == null) {
throw new NullPointerException("A categoria está sem descrição, favor colocar");
}
banco.add(categoria);
salvar();
}
private void salvar() {
try {
FileOutputStream arquivo = new FileOutputStream("categorias.txt", false);
ObjectOutputStream os = new ObjectOutputStream(arquivo);
os.writeObject(banco);
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void excluir(Categoria categoria) {
banco.remove(categoria);
salvar();
}
@Override
public void editar(Categoria categoria) {
excluir(categoria);
}
@Override
public Set<Categoria> listar() {
try {
FileInputStream arquivo = new FileInputStream("categorias.txt");
ObjectInputStream objetos = new ObjectInputStream(arquivo);
@SuppressWarnings("unchecked")
Set<Categoria> lista = (Set<Categoria>) objetos.readObject();
objetos.close();
arquivo.close();
return lista;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public Set<Categoria> buscarCategoriaPorDescricao(String descricao) {
Set<Categoria> bancoEmArquivo = listar();
Set<Categoria> categoriasEncontradas = new HashSet<>();
descricao = descricao.toUpperCase();
for (Categoria categoria : bancoEmArquivo) {
String descricaoCategoria = categoria.getDescricao();
if (descricaoCategoria.contains(descricao)) {
categoriasEncontradas.add(categoria);
}
}
return categoriasEncontradas;
}
@Override
public Categoria buscarPorCodigoSequencial(String codigoSequencial) {
Set<Categoria> bancoEmArquivo = listar();
for (Categoria categoria : bancoEmArquivo) {
String codigoCategoria = categoria.getCodigoSequencial();
if (codigoCategoria.equals(codigoSequencial)) {
return categoria;
}
}
return null;
}
}
<file_sep>package br.com.biblioteca.console.confirmacao;
import java.util.Scanner;
import br.com.biblioteca.objetos.interfaces.ItemBiblioteca;
public class Confirmacao {
private Scanner scanner;
private ItemBiblioteca item;
public Confirmacao(Scanner scanner, ItemBiblioteca item){
this.scanner = scanner;
this.item = item;
}
public boolean confirmaEdicao() {
Class<? extends ItemBiblioteca> classe = item.getClass();
String nomeClasse = classe.getSimpleName();
System.out.println("Editar "+nomeClasse+"?");
System.out.println(item);
System.out.println("1 - Sim");
System.out.println("2 - Não");
System.out.println("Digite: ");
String decisao = scanner.next();
if (decisao.equals("1")) {
return true;
}
if (decisao.equals("2")) {
return false;
} else {
System.out.println("Opção inválida. Por favor, digite novamente.");
confirmaEdicao();
}
return false;
}
public boolean confirmaRemocao() {
Class<? extends ItemBiblioteca> classe = item.getClass();
String nomeClasse = classe.getSimpleName();
System.out.println("Remover "+nomeClasse+"?");
System.out.println(item);
System.out.println("1 - Sim");
System.out.println("2 - Não");
System.out.println("Digite: ");
String decisao = scanner.next();
if (decisao.equals("1")) {
return true;
}
if (decisao.equals("2")) {
return false;
} else {
System.out.println("Opção inválida. Por favor, digite novamente.");
confirmaRemocao();
}
return false;
}
}
<file_sep>package br.com.biblioteca.repositorios.bd;
/**
*
* @author aline.correa
*
*/
public class CategoriasDB {// implements Categorias
/*
* @Override public void adicionar(Categoria registro) {
*
* }
*
* @Override public void excluir(Categoria registro) {
*
* }
*
* @Override public void editar(Categoria registro) {
*
* }
*
* @Override public Set<Categoria> listar() { return null; }
*
* @Override public Categoria buscarCategoriaPorDescricao(String descricao)
* { return null; }
*
* @Override public Categoria buscarPorCodigoSequencial(String
* codigoSequencial) { return null; }
*/
}
<file_sep>package br.com.biblioteca.console.cadastro;
import java.util.Scanner;
import java.util.Set;
import br.com.biblioteca.objetos.Categoria;
import br.com.biblioteca.repositorios.interfaces.Categorias;
public class CadastroDeCategoria {
private Scanner scanner;
private static Categorias bancoDeCategorias;
public CadastroDeCategoria(Scanner scanner, Categorias bancoDeCategorias) {
this.scanner = scanner;
CadastroDeCategoria.bancoDeCategorias = bancoDeCategorias;
}
public void cadastrarCategoria() {
System.out.println("Insira a descrição da categoria: ");
scanner.nextLine();
String descricao = scanner.nextLine();
Categoria novaCategoria = new Categoria(descricao);
System.out.println("Verificando se categoria ja existe no banco...");
boolean resultado = verificaExistênciaDeCategoriaPorDescricao(descricao);
if(resultado){
System.out.println("Categoria:" + descricao + " ja existe.");
return;
}else{
System.out.println("Nova categoria criada: " + descricao.toUpperCase());
bancoDeCategorias.adicionar(novaCategoria);
}
}
private boolean verificaExistênciaDeCategoriaPorDescricao(String descricao){
Set<Categoria> busca = bancoDeCategorias.buscarCategoriaPorDescricao(descricao);
if(!busca.isEmpty()){
return true;
}
return false;
}
}
<file_sep>package br.com.biblioteca.codigosparaauxilio;
/*
* for(Classe variavel : Collecion){
* }
*
*/
/*
* Iterator<Livro> iterator = listaDeLivros.iterator(); while
* (iterator.hasNext()) {
*
*
* String lc = iterator.next(); System.out.print(lc); }
*/
<file_sep>var selecao3 = document.querySelector('.paypal3');
selecao3.onclick = function(){
var atual3 = selecao3.getAttribute("src");
if(atual3 == "imagens/check_before1.png"){
atual3 = selecao3.setAttribute("src","imagens/check_after3.png");
}else{
atual3 = selecao3.setAttribute("src","imagens/check_before3.png");
}
return false
};<file_sep>package br.com.biblioteca.objetos;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import br.com.biblioteca.objetos.interfaces.ItemBiblioteca;
public class Autor implements Comparable<Autor>, ItemBiblioteca {
private String codigoSequencial;
private String nome;
private String nacionalidade;
private Calendar dataDeNascimento;
private static final SimpleDateFormat formatoData = new SimpleDateFormat("dd/MM/yyyy");
// Construtores
public Autor(String nome) {
setNome(nome);
setCodigoSequencial();
}
// Métodos da classe
@Override
public String toString() {
return "Nome: " + nome + "( Código Sequencial: " + codigoSequencial + " )";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((codigoSequencial == null) ? 0 : codigoSequencial.hashCode());
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Autor other = (Autor) obj;
if (codigoSequencial == null) {
if (other.codigoSequencial != null)
return false;
} else if (!codigoSequencial.equals(other.codigoSequencial))
return false;
if (nome == null) {
if (other.nome != null)
return false;
} else if (!nome.equals(other.nome))
return false;
return true;
}
// Getters e Setters
public String getCodigoSequencial() {
return this.codigoSequencial;
}
public void setCodigoSequencial() {
UUID idOne = UUID.randomUUID();
this.codigoSequencial = idOne.toString().replaceAll("-", "");
}
public String getNome() {
return this.nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getNacionalidade() {
return this.nacionalidade;
}
public void setNacionalidade(String nacionalidade) {
this.nacionalidade = nacionalidade;
}
public String getDataDeNascimento() {
String dataUserString = formatoData.format(this.dataDeNascimento.getTime());
return dataUserString;
}
public void setDataDeNascimento(String dataDeNascimento) {
try {
Date date = formatoData.parse(dataDeNascimento);
Calendar dataVerifica = Calendar.getInstance();
dataVerifica.setTime(date);
if (verificarDataDeNascimento(dataVerifica)) {
this.dataDeNascimento = Calendar.getInstance();
this.dataDeNascimento.setTime(date);
} else {
throw new IllegalArgumentException(
"Data inserida invalida : Data posterior a atual. Por favor, tente novamente.");
}
} catch (ParseException e) {
throw new IllegalArgumentException(
"Data inserida invalida, por favor tente novamente e utilize o formato (dd/mm/yyyy)");
}
}
private boolean verificarDataDeNascimento(Calendar dataVerifica) {
Calendar dataDeHoje = Calendar.getInstance();
if (dataVerifica.getTime().before(dataDeHoje.getTime())) {
return true;
}
return false;
}
@Override
public int compareTo(Autor outroAutor) {
if (this.nome != null) {
int comparacao = this.nome.compareTo(outroAutor.getNome());
if (comparacao != 0) {
return comparacao;
}
}
if (this.dataDeNascimento != null) {
int comparacao = this.getDataDeNascimento().compareTo(outroAutor.getDataDeNascimento());
if (comparacao != 0) {
return comparacao;
}
}
if (this.codigoSequencial != null) {
int comparacaoCodigo = this.codigoSequencial.compareTo(outroAutor.getCodigoSequencial());
if (comparacaoCodigo != 0) {
return comparacaoCodigo;
}
}
return 0;
}
}
<file_sep>package br.com.biblioteca.console.remove;
import java.util.Scanner;
import br.com.biblioteca.console.confirmacao.Confirmacao;
import br.com.biblioteca.console.pesquisa.livro.PesquisaLivroPorCodigoSequencial;
import br.com.biblioteca.objetos.Livro;
import br.com.biblioteca.repositorios.interfaces.Livros;
public class RemoveLivro {
private static Livros bancoDeLivros;
private Scanner scanner;
public RemoveLivro(Scanner scanner, Livros bancoDeLivros) {
this.scanner = scanner;
RemoveLivro.bancoDeLivros = bancoDeLivros;
}
public void removerLivro() {
System.out.println("Insira o código sequencial da categoria: ");
scanner.nextLine();
String codigoSequencial = scanner.nextLine();
System.out.println("Buscando categoria...");
boolean verifica = new PesquisaLivroPorCodigoSequencial(scanner, bancoDeLivros).verificaExistenciaDeLivroPorCodigoSequencial(codigoSequencial);
if(verifica){
Livro livro = bancoDeLivros.buscarPorCodigoSequencial(codigoSequencial);
System.out.println("Livro Encontrado:");
System.out.println(livro);
boolean decisao = new Confirmacao(scanner, livro).confirmaRemocao();
if (decisao) {
bancoDeLivros.excluir(livro);
System.out.println("Livro " + livro.getTitulo() + " removido.");
} else {
return;
}
}else{
System.out.println("Livro não encontrado. Por favor, verifique o código sequencial informado e tente novamente.");
return;
}
}
}
<file_sep>
var selecao = document.querySelector('.paypal');
selecao.onclick = function(){
var atual = selecao.getAttribute("src");
if(atual == "imagens/check_before.png"){
atual = selecao.setAttribute("src","imagens/check_after.png");
}else{
atual = selecao.setAttribute("src","imagens/check_before.png");
}
return false
};
<file_sep>package br.com.biblioteca.repositorios.bd;
/**
*
* @author aline.correa
*
*/
public class AutoresDB { //implements Autores
/*
@Override
public void adicionar(AutoresEmMemoria registro) {
}
@Override
public void excluir(Autor registro) {
}
@Override
public void editar(Autor registro) {
}
@Override
public Set<Autor> listar() {
return null;
}
@Override
public Set<Autor> buscarPorNome(String nome) {
return null;
}
@Override
public Set<Autor> buscarPorNacionalidade(String nacionalidade) {
return null;
}
@Override
public Set<Autor> buscarPorDataDeNascimento(Date dataDeNascimento) {
return null;
}
@Override
public Autor buscarPorCodigoSequencial(String codigoSequencial) {
return null;
}
*/}
<file_sep>package br.com.biblioteca.repositorios.interfaces;
import java.util.Set;
import br.com.biblioteca.objetos.Categoria;
/**
*
* @author aline.correa
*
*/
public interface Categorias extends AcoesNoRepositorio<Categoria> {
Set<Categoria> buscarCategoriaPorDescricao(String descricao);
Categoria buscarPorCodigoSequencial(String codigoSequencial);
}
<file_sep>package br.com.biblioteca.repositorios.bd;
/**
* @author aline.correa
*
*/
public class LivrosDB { // implements Livros
/*
* @Override public void adicionar(Livro registro) {
*
*
* }
*
* @Override public void excluir(Livro registro) {
*
*
* }
*
* @Override public Set<Livro> listar() {
*
* return null; }
*
* @Override public Set<Livro> buscarPorTitulo(String titulo) {
*
* return null; }
*
* @Override public Set<Livro> buscarPorCodigoSequencial(long
* codigoSequencial) {
*
* return null; }
*
* @Override public Set<Livro> buscarPorCodigoDeBarras(long codigoDeBarras)
* {
*
* return null; }
*/
}
<file_sep>var selecao2 = document.querySelector('.paypal2');
selecao2.onclick = function(){
var a = selecao2.getAttribute("src");
if(a == "imagens/check_before1.png"){
a = selecao2.setAttribute("src","imagens/check_after2.png");
}else{
a = selecao2.setAttribute("src","imagens/check_before2.png");
}
return false
};<file_sep>package br.com.biblioteca.console.cadastro;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import br.com.biblioteca.console.lista.ListaDeAutores;
import br.com.biblioteca.console.lista.ListaDeCategorias;
import br.com.biblioteca.objetos.Autor;
import br.com.biblioteca.objetos.Categoria;
import br.com.biblioteca.objetos.Livro;
import br.com.biblioteca.repositorios.interfaces.Autores;
import br.com.biblioteca.repositorios.interfaces.Categorias;
import br.com.biblioteca.repositorios.interfaces.Livros;
public class CadastroDeLivro {
private Scanner scanner;
private static Livros bancoDeLivros;
private static Autores bancoDeAutores;
private static Categorias bancoDeCategorias;
public CadastroDeLivro(Scanner scanner, Livros bancoDeLivros, Autores bancoDeAutores,Categorias bancoDeCategorias){
this.scanner = scanner;
CadastroDeLivro.bancoDeLivros = bancoDeLivros;
CadastroDeLivro.bancoDeAutores = bancoDeAutores;
CadastroDeLivro.bancoDeCategorias = bancoDeCategorias;
}
public void cadastrarLivro(){
scanner.nextLine();
Livro novoLivro = new Livro();
System.out.println("ATENÇÃO: CAMPOS COM * DEVEM SER OBRIGATORIAMENTE PREENCHIDOS");
System.out.println("\n");
System.out.println("*Insira o título do livro*:");
String titulo = scanner.nextLine();
novoLivro.setTitulo(titulo);
System.out.println("*Insira o local do livro*:");
String local = scanner.nextLine();
novoLivro.setLocal(local);
System.out.println("Insira a quantidade de páginas do livro:");
String quantidadeDePaginas = scanner.nextLine();
System.out.println("*Insira a data de aquisição do livro(dd/mm/aaaa)*:");
String dataDeAquisicao = scanner.nextLine();
System.out.println("==== *Escolha a Categoria* ====");
ListaDeCategorias listaDeCategorias = new ListaDeCategorias(bancoDeCategorias);
listaDeCategorias.listarCategorias();
System.out.println("*Insira o código sequencial da categoria do livro*:");
String codigoCategoria = scanner.nextLine();
Categoria categoria = bancoDeCategorias.buscarPorCodigoSequencial(codigoCategoria);
novoLivro.setCategoria(categoria);
System.out.println("Insira o resumo do livro: ");
String resumo = scanner.nextLine();
System.out.println("*Insira o número de autores(as) do livro*:");
String numeroDeAutores = scanner.nextLine();
int numero = Integer.parseInt(numeroDeAutores);
Set<Autor> autoresDoLivro = new TreeSet<>();
System.out.println("==== *Lista de Autores(as)* ====");
ListaDeAutores listaDeAutores = new ListaDeAutores(bancoDeAutores);
listaDeAutores.listarAutores();
if(numero == 1){
System.out.println("*Insira o código sequencial do autor(a) do livro*:");
String codigoAutor = scanner.nextLine();
Autor autor = bancoDeAutores.buscarPorCodigoSequencial(codigoAutor);
autoresDoLivro.add(autor);
}
if(numero > 1){
for(int contador = 1;contador <= numero;contador++){
System.out.println("*Insira o código sequencial do autor " + contador +" do livro*:");
String codigoAutor = scanner.nextLine();
Autor autor = bancoDeAutores.buscarPorCodigoSequencial(codigoAutor);
autoresDoLivro.add(autor); }
}
novoLivro.setAutor(autoresDoLivro);
if(!dataDeAquisicao.equals(null)){
try{
novoLivro.setDataDeAquisicao(dataDeAquisicao);
}catch(IllegalArgumentException e){
e.printStackTrace();
}
}
if(!resumo.equals(null)){
novoLivro.setResumo(resumo);
}
if(quantidadeDePaginas != null){
int paginas = Integer.parseInt(quantidadeDePaginas);
novoLivro.setQuantidadeDePaginas(paginas);
}
bancoDeLivros.adicionar(novoLivro);
System.out.println("Novo livro Criado !!!");
System.out.println(novoLivro);
}
}
<file_sep>package br.com.biblioteca.console.cadastro;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import br.com.biblioteca.console.lista.ListaDeAutores;
import br.com.biblioteca.console.lista.ListaDeCategorias;
import br.com.biblioteca.objetos.Autor;
import br.com.biblioteca.objetos.Categoria;
import br.com.biblioteca.objetos.Livro;
import br.com.biblioteca.objetos.exceptions.CriacaoDeAtributoException;
import br.com.biblioteca.objetos.exceptions.DataInvalidaException;
import br.com.biblioteca.objetos.exceptions.FormatoDeDataInvalidoException;
import br.com.biblioteca.repositorios.interfaces.Autores;
import br.com.biblioteca.repositorios.interfaces.Categorias;
import br.com.biblioteca.repositorios.interfaces.Livros;
/**
*
* @author aline.correa
*
* Script de integração de cadastro: Interação com o usuário e cadastro
* de livro
*
*/
public class CadastroDeLivro {
private Scanner scanner;
private static Livros bancoDeLivros;
private static Autores bancoDeAutores;
private static Categorias bancoDeCategorias;
public CadastroDeLivro(Scanner scanner, Livros bancoDeLivros, Autores bancoDeAutores,Categorias bancoDeCategorias){
this.scanner = scanner;
CadastroDeLivro.bancoDeLivros = bancoDeLivros;
CadastroDeLivro.bancoDeAutores = bancoDeAutores;
CadastroDeLivro.bancoDeCategorias = bancoDeCategorias;
}
public void cadastrarLivro() throws FormatoDeDataInvalidoException{
Livro novoLivro = new Livro();
try{
scanner.nextLine();
System.out.println("ATENÇÃO: CAMPOS COM * DEVEM SER OBRIGATORIAMENTE PREENCHIDOS");
System.out.println("\n");
System.out.println("*Insira o título do livro*:");
String titulo = scanner.nextLine();
novoLivro.setTitulo(titulo);
System.out.println("*Insira o local do livro*:");
String local = scanner.nextLine();
novoLivro.setLocal(local);
System.out.println("==== *Escolha a Categoria* ====");
ListaDeCategorias listaDeCategorias = new ListaDeCategorias(bancoDeCategorias);
listaDeCategorias.listarCategorias();
System.out.println("*Insira o código sequencial da categoria do livro*:");
String codigoCategoria = scanner.nextLine();
try{
Categoria categoria = bancoDeCategorias.buscarPorCodigoSequencial(codigoCategoria);
novoLivro.setCategoria(categoria);
}catch(NullPointerException e){
System.out.println("*** Categoria não encontrada. Tente novamente ***");
cadastrarLivro();
}
System.out.println("*Insira o número de autores(as) do livro*:");
String numeroDeAutores = scanner.nextLine();
int numero = Integer.parseInt(numeroDeAutores);
Set<Autor> autoresDoLivro = new TreeSet<>();
System.out.println("==== *Lista de Autores(as)* ====");
ListaDeAutores listaDeAutores = new ListaDeAutores(bancoDeAutores);
listaDeAutores.listarAutores();
if(numero == 1){
System.out.println("*Insira o código sequencial do autor(a) do livro*:");
String codigoAutor = scanner.nextLine();
try{
Autor autor = bancoDeAutores.buscarPorCodigoSequencial(codigoAutor);
autoresDoLivro.add(autor);
novoLivro.setAutor(autoresDoLivro);
}catch(NullPointerException e){
System.out.println("*** Autor(a) não encontrado(a). Tente Novamente ***");
cadastrarLivro();
}
}
if(numero > 1){
for(int contador = 1;contador <= numero;contador++){
System.out.println("*Insira o código sequencial do autor " + contador +" do livro*:");
String codigoAutor = scanner.nextLine();
Autor autor = bancoDeAutores.buscarPorCodigoSequencial(codigoAutor);
autoresDoLivro.add(autor);
}
novoLivro.setAutor(autoresDoLivro);
}
System.out.println("Insira o resumo do livro: ");
String resumo = scanner.nextLine();
novoLivro.setResumo(resumo);
System.out.println("Insira a quantidade de páginas do livro:");
String quantidadeDePaginas = scanner.nextLine();
novoLivro.setQuantidadeDePaginas(quantidadeDePaginas);
System.out.println("Insira a data de aquisição do livro(dd/mm/aaaa):");
String dataDeAquisicao = scanner.nextLine();
novoLivro.setDataDeAquisicao(dataDeAquisicao);
novoLivro.verificacaoDeDadosLivro();
bancoDeLivros.adicionar(novoLivro);
System.out.println("Novo livro Criado !!!");
System.out.println(novoLivro);
}catch(CriacaoDeAtributoException e){
System.out.println(e.getMessage());
cadastrarLivro();
}catch(DataInvalidaException e){
System.out.println(e.getMessage());
System.out.println("Retornando... Por favor, Tente novamente");
cadastrarLivro();
}catch(NumberFormatException e){
System.out.println("*** Formato de caractere inserido inválido ***\nRetornando... Por favor, Tente novamente");
cadastrarLivro();
}catch (FormatoDeDataInvalidoException e) {
System.out.println(e.getMessage());
try {
novoLivro.verificacaoDeDadosLivro();
bancoDeLivros.adicionar(novoLivro);
System.out.println("Novo livro Criado !!!");
System.out.println(novoLivro);
} catch (CriacaoDeAtributoException e1) {
System.out.println(e.getMessage());
System.out.println("Retornando... Por favor, Tente novamente");
cadastrarLivro();
}
}
}
}
<file_sep>package br.com.biblioteca.objetos.interfaces;
public interface ItemBiblioteca {
void setCodigoSequencial();
String getCodigoSequencial();
}
<file_sep>function favoritar() {
$('.estrela').on('click', function () {
$(this).toggleClass('estrela-checked');
});
}<file_sep>package br.com.biblioteca.console.testes;
/*package com.biblioteca.console.testes;
import java.util.List;
import java.util.Set;
import com.biblioteca.objetos.Autor;
import com.biblioteca.objetos.Categoria;
import com.biblioteca.objetos.Livro;
import com.biblioteca.repositorios.interfaces.Livros;
import com.biblioteca.repositorios.memoria.BancoDeLivros;
public class TestaBancoDeLivros {
public static void main(String[] args) {
// TESTE : Inicializando Banco de Livros
System.out.println("Inicializando Banco de Livros...");
Livros bancoDeLivros = new BancoDeLivros();
// Livros bl = new livrosEmBancoDeDados();
// TESTE : Inicializando alguns autores(as) e categorias
Autor autor1 = new Autor("<NAME>");
autor1.setNacionalidade("brasileira");
autor1.setDataDeNascimento("08/10/2010");
Autor autor2 = new Autor("Nome");
autor2.setNacionalidade("francês");
autor2.setDataDeNascimento("08/11/1997");
Autor autor3 = new Autor("Antonio");
autor3.setNacionalidade("alemão");
autor3.setDataDeNascimento("02/03/2012");
Categoria categoria1 = new Categoria("Drama");
Categoria categoria2 = new Categoria("Ação");
Categoria categoria3 = new Categoria("Suspense");
// TESTE : Criando livros
Livro a = new Livro(autor1,categoria1,"Aline 1","A3");
a.setDataDeAquisicao("10/07/2015");
a.setResumo("safbfws fesfbuywsf firubfs ");
System.out.println("Criando Livro: " + a.getTitulo());
Livro b = new Livro(autor2,categoria2,"Aline testaando","B5");
b.setDataDeAquisicao("2015/10/07");
b.setResumo("gnnfeiuaf");
System.out.println("Criando Livro: " + b.getTitulo());
Livro c = new Livro(autor3,categoria3,"SoftExpert","D8");
c.setDataDeAquisicao("25/08/2017");
c.setResumo("hrsgeh5h");
System.out.println("Criando Livro: " + c.getTitulo());
Livro d = new Livro(autor3,categoria3,"livro teste","A8");
d.setDataDeAquisicao("01/01/2017");
d.setResumo("hrsgeh5h");
System.out.println("Criando Livro: " + d.getTitulo());
Livro e = new Livro(autor3,categoria3,"afdvd","C5");
e.setDataDeAquisicao("25/02/2017");
e.setResumo("hrsgeh5h");
System.out.println("Criando Livro: " + e.getTitulo());
Livro f = new Livro(autor3,categoria3,"aabdfbd","D1");
f.setDataDeAquisicao("03/05/2017");
f.setResumo("hrsgeh5h");
System.out.println("Criando Livro: " + f.getTitulo());
// TESTE : Adicionando livros no banco
System.out.println("Adicionando Livros no Banco...");
bancoDeLivros.adicionar(b);
bancoDeLivros.adicionar(a);
bancoDeLivros.adicionar(c);
bancoDeLivros.adicionar(d);
bancoDeLivros.adicionar(e);
bancoDeLivros.adicionar(f);
System.out.println("\n");
// TESTE : Listar Banco de Livros
Set<Livro> listaDeLivros = bancoDeLivros.listar();
System.out.println("Listando Banco de Livros:");
for (Livro livro : listaDeLivros) {
System.out.println(livro);
}
System.out.println("\n");
// TESTE : Excluir Livro
System.out.println("Excluindo Livro: " + b.getTitulo());
bancoDeLivros.excluir(b);
System.out.println("\n");
// TESTE : Buscar por título
System.out.println("Resultado pesquisa por título: A");
String entradaPesquisaDeTituloUsuario = " " + "A"; // Vem do usuario
Set<Livro> retornoTestePesquisaTitulo = bancoDeLivros.buscarPorTitulo(entradaPesquisaDeTituloUsuario);
for (Livro livro : retornoTestePesquisaTitulo) {
System.out.println(livro);
}
System.out.println("\n");
// TESTE : Buscar por codigo sequencial não existente:
// retornoTestePesquisaTitulo.iterator().next().getCodigoSequencial());
System.out.println("Resultado pesquisa por código sequencial(Não Existente):");
Livro resultado1 = bancoDeLivros.buscarPorCodigoSequencial("gjgyututuyuy");
if (resultado1 == null) {
System.out.println("Nenhum livro encontrado");
} else {
System.out.println(resultado1);
}
System.out.println("\n");
// TESTE : Buscar por codigo sequencial existente:
System.out.println("Resultado pesquisa por código sequencial(Existente):");
Livro resultado2 = bancoDeLivros
.buscarPorCodigoSequencial(retornoTestePesquisaTitulo.iterator().next().getCodigoSequencial());
System.out.println(resultado2);
System.out.println("\n");
// TESTE : Encontrar livros por categoria
System.out.println("Resultado pesquisa por categoria: Suspense");
List<Livro> livrosEncontrados = bancoDeLivros.buscarPorCategoria("Suspense");
if (livrosEncontrados.isEmpty()) {
System.out.println("Nenhum livro encontrado");
} else {
for (Livro livro : livrosEncontrados) {
System.out.println(livro);
}
}
System.out.println("\n");
System.out.println("Resultado pesquisa por categoria: Drama");
List<Livro> livrosEncontrados2 = bancoDeLivros.buscarPorCategoria("drama");
if (livrosEncontrados2.isEmpty()) {
System.out.println("Nenhum livro encontrado");
} else {
for (Livro livro : livrosEncontrados2) {
System.out.println(livro);
}
}
System.out.println("\n");
System.out.println("Resultado pesquisa por categoria: ação");
List<Livro> livrosEncontrados3 = bancoDeLivros.buscarPorCategoria("ação");
if (livrosEncontrados3.isEmpty()) {
System.out.println("Nenhum livro encontrado");
} else {
for (Livro livro : livrosEncontrados3) {
System.out.println(livro);
}
}
}
}
*/<file_sep>package br.com.biblioteca.repositorios.bd;
/**
*
* @author aline.correa
*
*/
public class AutoresDB {
// implements Autores
/*
* @Override public void adicionar(AutoresEmMemoria registro) { }
*
* @Override public void excluir(Autor registro) { }
*
* @Override public void editar(Autor registro) { }
*
* @Override public Set<Autor> listar() { return null; }
*
* @Override public Set<Autor> buscarPorNome(String nome) {
*
* return null; }
*
* @Override public Set<Autor> buscarPorNacionalidade(String nacionalidade)
* { return null; }
*
* @Override public Set<Autor> buscarPorDataDeNascimento(Date
* dataDeNascimento) { return null; }
*
* @Override public Autor buscarPorCodigoSequencial(String codigoSequencial)
* { return null; }
*
*/}
<file_sep>package br.com.biblioteca.console.pesquisa.autor;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import br.com.biblioteca.objetos.Autor;
import br.com.biblioteca.repositorios.interfaces.Autores;
public class PesquisaAutorPorDataDeNascimento {
private Scanner scanner;
private static Autores bancoDeAutores;
public PesquisaAutorPorDataDeNascimento(Scanner scanner, Autores bancoDeAutores){
this.scanner = scanner;
PesquisaAutorPorDataDeNascimento.bancoDeAutores = bancoDeAutores;
}
public void pesquisarAutorPorDataDeNascimento(){
scanner.nextLine();
System.out.println("Insira a data de nascimento: ");
String dataPesquisa = scanner.nextLine();
System.out.println("Pesquisando autor(es) no banco...");
boolean verifica = verificaExistenciaDeAutorPorDataDeNascimento(dataPesquisa);
if(verifica){
Set<Autor> banco = bancoDeAutores.listar();
System.out.println("Autor(es) encontrado(s):");
for (Autor autor : banco) {
if(autor.getDataDeNascimento().equals(dataPesquisa)){
System.out.println(autor);
}
}
}else{
System.out.println("Nenhum autor(a) encontrado(a). Por favor verifique a data de nascimento inserida e tente novamente.");
}
}
private boolean verificaExistenciaDeAutorPorDataDeNascimento(String data) {
Set<Autor> busca = new TreeSet<>();
busca = (bancoDeAutores.buscarPorDataDeNascimento(data));
if (!busca.isEmpty()) {
return true;
}
return false;
}
}
<file_sep>var selecao5 = document.querySelector('.paypal5');
selecao5.onclick = function(){
var atual5 = selecao5.getAttribute("src");
if(atual5 == "imagens/check_before1.png"){
atual5 = selecao5.setAttribute("src","imagens/check_after5.png");
}else{
atual5 = selecao5.setAttribute("src","imagens/check_before5.png");
}
return false
};<file_sep>package br.com.biblioteca.console.lista;
import java.util.Set;
import br.com.biblioteca.objetos.Autor;
import br.com.biblioteca.repositorios.interfaces.Autores;
/**
*
* @author aline.correa
*
* Script de integração de listagem: Interação com o usuário e listagem
* de Autores no banco
*
*/
public class ListaDeAutores {
private static Autores bancoDeAutores;
public ListaDeAutores(Autores bancoDeAutores) {
ListaDeAutores.bancoDeAutores = bancoDeAutores;
}
public void listarAutores() {
Set<Autor> listaDeAutores = bancoDeAutores.listar();
for (Autor autor : listaDeAutores) {
System.out.println("Nome: " + autor.getNome() + " | Nacionalidade: " + autor.getNacionalidade()
+ " | Data De Nascimento: " + autor.getDataDeNascimento() + " | Código Sequencial: "
+ autor.getCodigoSequencial());
}
}
}
<file_sep>import java.util.Scanner;
class desafio{
public static void main(String[] args){
String vetorTentativa[] = new String[5];
String vetorSistema[] = new String[5];
String vetorUsuario[] = new String[5];
String numOficial = "";
String numSys;
String numUse;
String numUser;
for (int contador = 0;contador<5;contador++){ //Contador para percorrer array vetorSistema
int numeroSystem = 1 + (int) (Math.random()*9); //Gera numero aleatorios entre 0 e 9
String numSystem = Integer.toString(numeroSystem); //Transforma o int gerado em String
vetorSistema[contador] = numSystem; //Acrescenta a String no array vetorSistema
numOficial = numOficial + vetorSistema[contador];
}
System.out.println("Numero gerado: ***** ");
Scanner usuario = new Scanner(System.in); //Inicia scanner
for (int tentativa = 0;tentativa<=5;tentativa++){ //Loop 5 tentativas
System.out.print("Digite sua tentativa: " );
int numeroUser = usuario.nextInt(); //Usuario entra com numero(int)
numUser = Integer.toString(numeroUser); //Transforma int do usuario em String
System.out.println("Usuario digitou: "+numeroUser+" (tentativa "+tentativa+")");
for(int stringUser = 0; stringUser<5; stringUser++){ //Percorre string e captura o caractere do numero inserido em cada posicao
int posicao2 = stringUser + 1;
numUse = numUser.substring(stringUser,posicao2);
vetorUsuario[stringUser] = numUse; //Acrescenta o caractere no array vetorUsuario
}
for (int p = 0;p<5;p++){ //Percorrendo posicoes dos arrays do usuario e do sistema
String user = vetorUsuario[p]; //Pega valor de determinada do array usuario
String system = vetorSistema[p]; //Pega valor de determinada posicao do array sistema
//System.out.println("Sistema:"+ system + " Usuario: " + user); Apresentando valor de determinada posição dos arrays
if(user.equals(system)){ //Se valor do array vetorUsuario for diferente do valor da msm posicao do array vetorSistema
vetorTentativa[p] = vetorSistema[p]; //vetorTentativa[contador] vai receber *
}else{ //Senao vetorTentativa[contador] vai receber o valor de vetorSistema[contador]
vetorTentativa[p] = "*";
}
}
String tentativaU = vetorTentativa[0] + vetorTentativa[1] + vetorTentativa[2] + vetorTentativa[3] + vetorTentativa[4];
if(numUser.equals(numOficial)){ //Se o número inserido é o mesmo número que o sistema gerou
System.out.println("Adivinhou a Senha! " + numOficial); //Imprime a senha e finaliza class
return;
}else{
System.out.println("Sistema informa: "+ tentativaU); //Senao, informa a tentativa
}
if(tentativa == 5){ //Se a tentativa for a 5, verifica se a resposta dada é o numero que o sistema gerou
if(tentativaU.equals(numOficial)){
System.out.println("Adivinhou a Senha! " + numOficial); //Se usuario acertou, imprime a senha e finaliza class
return;
}else{
System.out.println("Game Over"); //Senao imprime Game Over e finaliza class
return;
}
}
}
usuario.close(); //Fim scanner
}
} | 7d0bfde36b11e6dfbf75d9d79e1a7fd135f46b55 | [
"JavaScript",
"Java"
] | 47 | Java | alinecarvalhocorrea/softexpert-programa-estagio | 8292c67851ef0b3b2bb43328c453076a5ce9562f | 4cab56a42607e5efac37db8f4e91c1d33f3da129 |
refs/heads/master | <repo_name>cherattk/slim-3-starter<file_sep>/tests/core/BaseControllerTest.php
<?php
use PHPUnit\Framework\TestCase;
final class BaseControllerTest extends TestCase {
public function testGetConfiguration() {
$controllerConfig = ['config.1' => 'config.1.value'];
$dependency = [];
$controller = $this->getMockForAbstractClass(
\Core\BaseController::class,
// base class constructor arguments - required for actual test
[$controllerConfig, $dependency],
// $mockClassName optional for actual test
'',
// $callOriginalConstructor
// required for actual test, must be true
true,
// $callOriginalClone - optional for actual test
false,
// $callAutoload - required for actual test
true,
);
$actual = $controller->getConfiguration();
$this->assertEquals($controllerConfig, $actual, 'test fail - keep calm and find the bug');
}
public function testGetService() {
$controllerConfig = [];
$objectInstance = new stdClass;
$dependency = [
'MyDependencyObject' => $objectInstance
];
$controller = $this->getMockForAbstractClass(
\Core\BaseController::class,
// base class constructor arguments - required for actual test
[$controllerConfig, $dependency],
// $mockClassName optional for actual test
'',
// $callOriginalConstructor
// required for actual test, must be true
true,
// $callOriginalClone - optional for actual test
false,
// $callAutoload - required for actual test
true,
);
$actual = $controller->getService('MyDependencyObject');
$expected = $dependency['MyDependencyObject'];
$this->assertEquals($expected, $actual, 'test fail - keep calm and find the bug');
}
}
<file_sep>/src/Core/BaseController.php
<?php
namespace Core;
abstract class BaseController {
private $service = [];
private $config = [];
public function __construct(array $config = [], array $service = []) {
$this->config = $config;
foreach ($service as $serviceName => $serviceInstance) {
$this->service[$serviceName] = $serviceInstance;
}
}
final public function getService(string $serviceName) {
if (isset($this->service[$serviceName])) {
return $this->service[$serviceName];
}
}
final public function getConfiguration() {
return $this->config;
}
}
<file_sep>/config/app.config.php
<?php
$loader = require_once(__DIR__ . "/../vendor/autoload.php");
// - config slim
$app = new \Slim\App([
'settings' => [
'displayErrorDetails' => true,
'debug' => true
],
]);
// 1 - Get Slim Container Instance
$slimContainer = $app->getContainer();
// 2 - Register "Controller" in Slim Container
$appContainer['Controller'] = function($slimContainer) {
$config = [];
$service = [];
$controller = new \App\Controller($config, $service);
return $controller;
};
return $app;
<file_sep>/src/App/Controller.php
<?php
namespace App;
use Core\BaseController;
class Controller extends BaseController {
public function action() {
return "action-method-returned-value";
}
}
<file_sep>/README.md
# Starter project for slim framework v3
### Dependencies
- PHP >= 7.3
- SlimPHP 3.*
- PHPUnit-9
### Test
```bash
> vendor/bin/phpunit --testsuite core,app
```
<file_sep>/tests/fixture/DummyEntity.php
<?php
namespace Core\Test;
/**
* @Entity
* @Table(name="test_table")
* */
class DummyEntity {
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
*
* */
private $id = "";
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
<file_sep>/CHANGELOG.md
### Changelog
All notable changes to this project since v1.0.0 will be documented in this file.
### v1.1.1
- Update dependencies:
- **slim/slim 3.\***
- **phpunit-9**
- Add namespace **Core**
- Add Abstract class **Core::BaseController**, that acts as a basic dependencies container.
- Add Test for **Core::BaseController** class.
### v1.1.0
- removing Psr\Container as controller dependency.
- renaming package to **prose/slim-3-starter**<file_sep>/tests/app/ControllerTest.php
<?php
use PHPUnit\Framework\TestCase;
use App\Controller;
final class ControllerTest extends TestCase {
public function testControllerAction() {
$controller = new Controller();
$actual = $controller->action();
$this->assertEquals('action-method-returned-value', $actual, 'Something goes wrong');
}
public function testGetConfiguration() {
$controllerConfig = ['config' => 'config.value'];
$dependency = [];
$controller = $controller = new Controller($controllerConfig , $dependency);
$actual = $controller->getConfiguration();
$this->assertEquals($controllerConfig, $actual, 'test fail - keep calm and find the bug');
}
public function testGetService() {
$controllerConfig = [];
$objectInstance = new stdClass;
$dependency = [
'MyDependencyObject' => $objectInstance
];
$controller = new Controller($controllerConfig , $dependency);
$actual = $controller->getService('MyDependencyObject');
$expected = $dependency['MyDependencyObject'];
$this->assertEquals($expected, $actual, 'test fail - keep calm and find the bug');
}
}
<file_sep>/public/index.php
<?php
$app = include(__DIR__ . '/../config/app.config.php');
$app->get('/', function($Request, $Response, $Args) {
$result = $this->Controller->action();
$Response->getBody()->write($result);
});
$app->run();
| df674e0a044c436b4d8c61aa1ac61a54e62d9a8a | [
"Markdown",
"PHP"
] | 9 | PHP | cherattk/slim-3-starter | b54dfe6f85ca161227e2fbc1065baee3e71f7b6b | 861d1db44b71e6df253951d1f6a29d73727a37ca |
refs/heads/main | <repo_name>C-H-coder-team/dog_pi<file_sep>/main.py
import random
import complete
sth=str(input('主题:'))
n=int(input('句子数量:'))
for i in range(1,n):
rand=int()
rand=random.randint(1, 20)
if rand == 1:
complete.complete.op1(sth)
elif rand == 2:
complete.complete.op2(sth)
elif rand == 3:
complete.complete.op3(sth)
elif rand == 4:
complete.complete.op4(sth)
elif rand == 5:
complete.complete.op5(sth)
elif rand == 6:
complete.complete.op6(sth)
elif rand == 7:
complete.complete.op7(sth)
elif rand == 8:
complete.complete.op8(sth)
elif rand == 9:
complete.complete.op9(sth)
elif rand == 10:
complete.complete.op10(sth)
elif rand == 11:
complete.complete.op11(sth)
elif rand == 12:
complete.complete.op12(sth)
elif rand == 13:
complete.complete.op13(sth)
elif rand == 14:
complete.complete.op14(sth)
elif rand == 15:
complete.complete.op15(sth)
elif rand == 16:
complete.complete.op16(sth)
elif rand == 17:
complete.complete.op17(sth)
elif rand == 18:
complete.complete.op18(sth)
elif rand == 19:
complete.complete.op19(sth)
else:
complete.complete.op20(sth)<file_sep>/output.py
import vars
class build:
def __init__(self):
pass
def yuju1(sth):
rt=str()
rt=vars.yuju1[0]+sth+vars.yuju1[1]
return rt
def yuju2(sth):
rt=str()
rt=sth+vars.yuju2[0]+sth+vars.yuju2[1]
return rt
def yuju3(sth):
rt=str()
rt=sth+vars.yuju3[0]+sth+vars.yuju3[1]+sth+vars.yuju3[2]
return rt
def yuju4(sth):
rt=str()
rt=vars.yuju4[0]+sth+vars.yuju4[1]
return rt
def yuju5(sth):
rt=str()
rt=vars.yuju5[0]
return rt
def yuju6(sth):
rt=str()
rt=vars.yuju6[0]+sth+vars.yuju6[1]
return rt
def yuju7(sth):
rt=str()
rt=vars.yuju7[0]
return rt
def yuju8(sth):
rt=str()
rt=sth+vars.yuju8[0]
return rt
def yuju9(sth):
rt=str()
rt=vars.yuju9[0]+sth+vars.yuju9[1]
return rt
def yuju10(sth):
rt=str()
rt=vars.yuju10[0]
return rt
def yuju11(sth):
rt=str()
rt=vars.yuju11[0]
return rt
def yuju12(sth):
rt=str()
rt=vars.yuju12[0]
return rt
def yuju13(sth):
rt=str()
rt=vars.yuju13[0]
return rt
def yuju14(sth):
rt=str()
rt=vars.yuju14[0]
return rt
def yuju15(sth):
rt=str()
rt=vars.yuju15[0]
return rt
def yuju16(sth):
rt=str()
rt=vars.yuju16[0]
return rt
def yuju17(sth):
rt=str()
rt=vars.yuju17[0]
return rt
def yuju18(sth):
rt=str()
rt=vars.yuju18[0]
return rt
def yuju19(sth):
rt=str()
rt=vars.yuju19[0]
return rt
def yuju20(sth):
rt=str()
rt=vars.yuju20[0]+sth+vars.yuju20[1]
return rt<file_sep>/complete.py
import output
class complete:
def __init__(self):
pass
def op1(sth):
print(output.build.yuju1(sth))
def op2(sth):
print(output.build.yuju2(sth))
def op3(sth):
print(output.build.yuju3(sth))
def op4(sth):
print(output.build.yuju4(sth))
def op5(sth):
print(output.build.yuju5(sth))
def op6(sth):
print(output.build.yuju6(sth))
def op7(sth):
print(output.build.yuju7(sth))
def op8(sth):
print(output.build.yuju8(sth))
def op9(sth):
print(output.build.yuju9(sth))
def op10(sth):
print(output.build.yuju10(sth))
def op11(sth):
print(output.build.yuju11(sth))
def op12(sth):
print(output.build.yuju12(sth))
def op13(sth):
print(output.build.yuju13(sth))
def op14(sth):
print(output.build.yuju14(sth))
def op15(sth):
print(output.build.yuju15(sth))
def op16(sth):
print(output.build.yuju16(sth))
def op17(sth):
print(output.build.yuju17(sth))
def op18(sth):
print(output.build.yuju18(sth))
def op19(sth):
print(output.build.yuju19(sth))
def op20(sth):
print(output.build.yuju20(sth)) | d2782eac1510daafd38b54cd511d63f63dc4041b | [
"Python"
] | 3 | Python | C-H-coder-team/dog_pi | cb7712b5f75885f2aba648add9fbfcfb6862a9ac | 1aa91e51edfdc14a31a4cdcf57578350b9f2749a |
refs/heads/master | <repo_name>vkxedeen/weather-app<file_sep>/src/components/MainLayout.js
import React from 'react';
import {Row} from 'antd';
import './MainLayout.css'
export default class MainLayout extends React.Component {
render() {
return (
<Row className={'layout'}>
<Row className={'header'}/>
<Row className={'content'}>
{this.props.children}
</Row>
<Row className={'footer'}/>
</Row>
)
}
}<file_sep>/src/components/App.js
import React from 'react';
import {Provider} from "mobx-react";
import cityStore from "../stores/CityStore";
import MainHomePage from "./MainHomePage";
const App = () => {
return (
<Provider cityStore={cityStore}>
<MainHomePage/>
</Provider>
)
};
export default App
<file_sep>/src/components/Paper.js
import React from 'react';
import './Paper.css'
import Row from "antd/es/grid/row";
export default class Paper extends React.Component {
render() {
return (
<Row className={'paper'}>
{this.props.children}
</Row>
)
}
}<file_sep>/src/stores/CityEntity.js
import {computed, observable} from "mobx";
export default class CityEntity {
id;
@observable isLoaded = false;
@observable name;
@observable temperature;
@observable pressure;
@observable wind;
@observable humidity;
icon;
constructor(city) {
this.id = city.id;
this.name = city.name;
this.temperature = (city.main.temp - 273.15).toFixed(1);
this.pressure = city.main.pressure;
this.wind = city.wind.speed;
this.humidity = city.main.humidity;
this.icon = city.weather[0].icon;
this.isLoaded = true;
this.info = city.sys
}
@computed
get src() {
return this.isLoaded ? `http://openweathermap.org/img/wn/${this.icon}@2x.png` : ''
}
}
<file_sep>/src/components/CardBox.js
import React from 'react';
import {Row, Avatar, Typography} from 'antd';
import './CardBox.css'
import cityStore from "../stores/CityStore";
export default class CardBox extends React.Component {
render() {
const {active, name, temperature, humidity, wind, pressure, src, id} = this.props;
const colorClass = temperature > 5 ? 'warmColor' : 'coldColor';
const activeClass = active ? 'activeCard' : '';
return (
<Row className={`card ${colorClass} ${activeClass}`}
onClick={() => {
cityStore.active = id;
if (cityStore.input) {
cityStore.inputVisibleToggle()
}
}}>
<Row type={'flex'} justify={'start'}>
<Typography className={'cardHeader'}>{name} </Typography>
<Avatar className={'image'} src={src}/>
</Row>
<Row className={'row'} type={'flex'} justify={'space-between'}>
<Typography className={'text'}>{`Temperature: `}</Typography>
<Typography className={'temp'}>{` ${temperature}°C`}</Typography>
</Row>
<Row>
<Typography className={'text'}>Wind: {wind} m/s</Typography>
</Row>
<Row>
<Typography className={'text'}>Pressure: {pressure}</Typography>
</Row>
<Row>
<Typography className={'text'}>Humidity: {humidity}</Typography>
</Row>
<Typography className={'deleteText'} onClick={() => cityStore.deleteCity(id)}>
Удалить
</Typography>
</Row>
)
}
}
<file_sep>/src/components/InputBox.js
import React, {Fragment} from 'react';
import {Input} from 'antd';
import {inject, observer} from "mobx-react";
import './Input.css'
export default @inject('cityStore')
@observer
class InputBox extends React.Component {
render() {
const {cityStore} = this.props;
const {cityName, input} = cityStore;
return (
<Fragment>
{input && <Input
autoFocus={true}
placeholder="Type your city name"
className={'input'}
value={cityName}
onChange={(e) => cityStore.cityName = e.target.value}
onKeyDown={e => {
if (e.keyCode === 13) {
cityStore.load()
}
}}
/>}
</Fragment>
)
}
}
<file_sep>/src/services/FakeApiService.js
export default class FakeApiService {
WEATHER_API_KEY = '2417412f059437d0d042a7841175d870';
_fakeCity = {
"coord": {"lon": 55.3, "lat": 25.27},
"weather": [{"id": 721, "main": "Haze", "description": "haze", "icon": "50d"}],
"base": "stations",
"main": {"temp": 298.11, "pressure": 1012, "humidity": 74, "temp_min": 297.15, "temp_max": 300.15},
"visibility": 4500,
"wind": {"speed": 3.6, "deg": 150},
"clouds": {"all": 0},
"dt": 1572060213,
"sys": {"type": 1, "id": 7537, "country": "AE", "sunrise": 1572056551, "sunset": 1572097372},
"timezone": 14400,
"id": 292223,
"name": "FakeCity",
"cod": 200
}
getCity() {
return new Promise(resolve => {
setTimeout(() => resolve(this._fakeCity), 500)
})
}
}
<file_sep>/src/components/AddCityBox.js
import React from 'react';
import {Row} from 'antd';
import './AddCityBox.css'
import './CardBox.css'
export default class AddCityBox extends React.Component {
render() {
return (
<Row className={'card addCard '} onClick={this.props.onClick}>
<div className={'plus'}/>
</Row>
)
}
}<file_sep>/src/components/CityBox.js
import React from 'react';
import './LayoutCities.css'
import Paper from "./Paper";
import {inject, observer} from "mobx-react";
import {Button, Row, Typography} from "antd";
import * as moment from 'moment';
export default @inject('cityStore')
@observer
class CityBox extends React.Component {
render() {
const {cityStore} = this.props
const {active: city} = cityStore
if (!city) {
return null
}
return (
<Paper>
<Row>
<Typography>
{city.name}
</Typography>
</Row>
<Row>
<Typography>
Восход: {moment(city.info.sunset).format('DD-MM-YY; h:mm:ss a')}
</Typography>
</Row>
<Row>
<Typography>
Закат: {moment(city.info.sunrise).format('h:mm:ss a')}
</Typography>
</Row>
<Button onClick={() => cityStore.getFiveDaysWeather()}>
Hourly forecast
</Button>
</Paper>
)
}
}
| aee7e3ac363cf88755911f38579dbe6173e81cb3 | [
"JavaScript"
] | 9 | JavaScript | vkxedeen/weather-app | ef89dde505226045bcf1ababd8ec2238c4e34aa1 | 0cf140dd69d12c70a6ef5b86c652b49a446bf515 |
refs/heads/master | <file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ShopComponent } from './shop/shop.component';
import { RosterComponent } from './roster/roster.component';
import { LoginComponent } from './login/login.component';
import { PortalComponent } from './portal/portal.component';
import { BasketComponent } from './basket/basket.component';
@NgModule({
declarations: [
AppComponent,
ShopComponent,
RosterComponent,
LoginComponent,
PortalComponent,
BasketComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>var mongoose = require('mongoose');
var OrderSchema = require('./order');
var UserSchema = new mongoose.Schema({
firstname: {
type: String,
required: [true, 'Required']
},
lastname: {
type: String,
required: [true, 'Required']
},
email: {
type: String,
required: [true, 'Required']
},
password: {
type: String,
required: [true, 'Required']
},
_orders: [{
type: mongoose.Schema.Types.ObjectId, ref: "Order"
}],
level: {
type: String,
default: "client"
},
}, {timestamps: true});
module.exports = mongoose.model("User", UserSchema)<file_sep>export class Order{
constructor (
public size: string = "",
public due_date: Date = new Date(),
public colors: [],
public message: string = "",
public add_ons: [],
public florist_name: string = "",
public shipping: boolean = True,
public recipient: string = "",
public address1: string = "",
public address2: string = "",
public city: string = "",
public state: string = "",
public zip: number = 0,
public created_at: Date = new Date(),
public updated_at: Date = new Date()
){}
}<file_sep>export class User {
constructor (
public firstname: string = "",
public lastname: string = "",
public email: string = "",
password: string = "",
public level: number = 1,
public created_at: Date = new Date(),
public updated_at: Date = new Date()
){}
}<file_sep>var mongoose = require('mongoose');
var session = require('express-session');
var sortBy = require('array-sort-by');
var User = require('../models/user');
var Order = require('../models/order');
var Client = require('../models/client');
module.exports = {
index: function(req, res){
console.log("inside of orders/index")
Order.find({})
.populate('_florist')
.exec(function(err, orders){
if (err) {
console.log(err)
console.log("trouble finding orders at index")
return res.json({error:err.errors})
}
console.log("yo, here are your orders:", orders)
return res.json({orders:orders})
});
},
add: function(req, res){
console.log("arrived at orders/add")
Client.findOne({_id: req.clientId}, function(err, client){
if (err){
console.log('error finding client at orders/add')
return res.json({error: err.errors})
}
console.log('here is your client: ', client)
var order = new Order(req.body)
order._client = client._id
order.save(function(err){
if (err){
console.log('error saving order')
return res.json({error: err.errors})
}
console.log('order saved')
client._orders.push(order)
client.save(function(err){
if (err){
console.log('error saving client')
return res.json({error: err.errors})
}
console.log('client saved')
return res.json({status:"success"})
})
})
})
},
assign: function(req, res){
console.log("arrived at orders/assign")
Order.findOne({_id: req.orderId}, function(err, order){
if(err) {
console.log("error finding order at orders/assign")
return res.json({error: err.errors})
}
console.log('here is your order: ', order)
User.findOne({_id: req.userId}, function(err, user){
if(err) {
console.log('error finding user')
return res.json({error: err.errors})
}
console.log('here is your user: ', user)
order._florist = user._id
order.florist_name = user.firstname
order.save(function(err){
if(err){
console.lod('error saving order')
return res.json({error:err.errors})
}
user._orders.push(order)
user.save(function(err){
if(err){
console.lod('error saving user')
return res.json({error:err.errors})
}
})
})
})
})
},
}
| 2b17797dcbb7c9ada7f61f3a2adcdaecb3bef8b3 | [
"JavaScript",
"TypeScript"
] | 5 | TypeScript | kkneville/flower_shop | c371456c1ee443e82575d242cdee72b393f874b6 | f2db899e0d8d765759a9f99b0a4c0dc8d2804d18 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Helpers{
class ConversorDeMorse{
static Dictionary<string, string> CodigoMorse = new Dictionary<string, string>(){
{"a", ".-"}, {"b", "-..."}, {"c", "-.-."}, {"d", "-.."},
{"e", "."}, {"f", "..-."}, {"g", "--."}, {"h", "...."},
{"i", ".."}, {"j", ".---"}, {"k", "-.-"}, {"l", ".-.."},
{"m", "--"}, {"n", "-."}, {"o", "---"}, {"p", ".--."},
{"q", "--.-"}, {"r", ".-."}, {"s", "..."}, {"t", "-"},
{"u", "..-"}, {"v", "...-"}, {"w", ".--"}, {"x", "-..-"},
{"y", "-.--"}, {"z", "--.."}, {"0", "-----"}, {"1", ".----"},
{"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."},
{"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."},
{" ", "/"}
};
static public void Usar(){
Console.WriteLine("Ingrese texto a convertir en morse: ");
string texto = Console.ReadLine();
TextoAMorse(texto);
string fecha = DateTime.Now.ToString("yy-MM-dd_hh-mm-ss");
string path = @"Morse/morse_" + fecha + ".txt";
List<string> morse = File.ReadLines(path).ToList();
foreach(string linea in morse){
if(linea != null) MorseATexto(linea);
}
}
//recibe un string en morse y devuelve la traduccion
static public void MorseATexto(string morse){
string texto = "";
string[] text = morse.Split(" ");
foreach(string letra in text){
foreach(KeyValuePair<string, string> a in CodigoMorse){
if(a.Value == letra) texto += a.Key;
}
}
//crea un archivo con el texto traducido
if(!Directory.Exists(@"Texto")) Directory.CreateDirectory(@"Texto");
string path = @"Texto/texto_";
CrearArchivo(texto, path);
}
//recibe un string en texto y lo devuelve en morse
static public void TextoAMorse(string texto){
string morse = "";
texto = texto.ToLower();
foreach(char letra in texto){
morse += CodigoMorse[letra.ToString()] + " ";
}
//crea un archivo con el texto en morse
if(!Directory.Exists(@"Morse")) Directory.CreateDirectory(@"Morse");
string path = @"Morse/morse_";
CrearArchivo(morse, path);
}
static public void CrearArchivo(string texto, string path){
string fecha = DateTime.Now.ToString("yy-MM-dd_hh-mm-ss");
path += fecha + ".txt";
Console.WriteLine("Revise el archivo: " + path);
File.WriteAllText(path, texto);
}
}
}<file_sep>using System;
using Helpers;
namespace Program{
class MainClass{
static public void Main(){
Console.WriteLine("-------------------------------------");
ConversorDeMorse.Usar();
Console.WriteLine("-------------------------------------");
}
}
} | b734f1e8a7d4ffd76b1a45957dc85c8ba09913ac | [
"C#"
] | 2 | C# | TallerDeLenguajes1/tpn9-LuxMG | c5154bb513bda3f13f7cc88fac1687b1a83af627 | 1dca17d5205eac85a2e81ad557c1cc578a576801 |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use App\Operation;
use App\User;
use App\StatusType;
use App\TransactionType;
use Illuminate\Http\Request;
use Exception;
use Response;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
class OperationsController extends Controller
{
/*
Busca todas operações com paginaçāo (10 operações por pagina)
@param $operation (id)
*/
public function index()
{
try
{
return Operation::paginate(10);
}
catch (Exception $e)
{
return response()->json(['message' => $e->getMessage()], 400);
}
}
/*
Busca uma operaçāo especifica pelo seu id
@param $operation (id)
*/
public function show(Operation $operation)
{
try
{
return $operation;
}
catch (Exception $e)
{
return response()->json(['message' => $e->getMessage()], 400);
}
}
/*
Busca operações pelo id usuario e seus dados pessoais com paginaçāo (10 operações por pagina)
@param $user (id)
*/
public function showUser(User $user)
{
try
{
return Operation::join('users','users.id','operations.id_user')
->where('id_user', $user->id)
->paginate(10);
}
catch (Exception $e)
{
return response()->json(['message' => $e->getMessage()], 400);
}
}
/*
Busca operações pelo seu tipo de status
@param $status (id)
*/
public function showStatus(StatusType $status)
{
try
{
return Operation::all()->where('id_status_type', $status->id);
}
catch (Exception $e)
{
return response()->json(['message' => $e->getMessage()], 400);
}
}
/*
Busca operações pelo seu tipo de transaçāo
@param $transaction (id)
*/
public function showTransaction(TransactionType $transaction)
{
try
{
return Operation::all()->where('id_transaction_type', $transaction->id);
}
catch (Exception $e)
{
return response()->json(['message' => $e->getMessage()], 400);
}
}
/*
Deleta uma operaçāo relacionado a um usuario especifico
@param $operation
@param $user
*/
public function eliminate(Operation $operation, User $user)
{
try
{
Operation::where([
['id','=',$operation->id],
['id_user','=',$user->id]
])->delete();
return response()->json(['success'=>true], 201);
}
catch (Exception $e)
{
return response()->json(['message' => $e->getMessage()], 400);
}
}
/*
Relatorio CSV via GET
@param $request (value)
*/
public function reportGet($param, User $user=null)
{
$month = '';
$year = '';
if(strlen($param)>2)
{
$month = substr($param, 0,2);
$year = substr($param, 2,2);
$param = 2;
}
switch($param){
case '30': // Filtro = Operações dos ultimos 30 dias
$condition = 'operations.created_at >= "'.Carbon::today()->subDays(30).'"';
break;
case '2': // Filtro = Operações do mês e ano especifico
$condition = 'MONTH(operations.created_at) = '.$month.' AND SUBSTRING(year(operations.created_at),1,2) = '.$year;
break;
case '0': // Filtro = Todas as operações
$condition = '1=1';
break;
default: // Filtro = Default todas as operações
return response()->json(['message' => 'Parâmetro Invalido', 'valid' => array('30 = Ultimos 30 dias','MMAA = Mês e Ano de Referência (Ex.: 0620)','0 = Todos os Registro')], 400);
break;
}
$whereUser = ($user) ? ' AND users.id = '.$user->id.'' : '';
$return = Operation::select('operations.id',
'operations.value',
'operations.created_at',
'users.name as userName',
'transaction_types.name as transactionName',
'status_types.name as status')
->join('users','users.id','operations.id_user')
->join('transaction_types','transaction_types.id','operations.id_transaction_type')
->join('status_types','status_types.id','operations.id_status_type')
->whereRaw($condition.$whereUser)
->get();
// consulta o saldo atual do usuario
$dataUser = ($user) ? $this->amountUser($user) : '';
$columns = array('Id', 'Usuario', 'Tipo_Transacao', 'Status', 'Valor', 'Data');
$callback = function() use ($return, $columns, $user, $dataUser)
{
$file = fopen('php://output', 'w');
if($user){
$nome = trim($dataUser->pluck('name'),'"[""""]"');
$email = trim($dataUser->pluck('email'),'"[""""]"');
$balance = trim($dataUser->pluck('current_balance'),'"[""""]"');
fputcsv($file, array("Nome", $nome),';');
fputcsv($file, array("Email", $email),';');
fputcsv($file, array("Saldo", $balance), ';');
}
fputcsv($file, $columns,';');
foreach($return as $data) {
$date = date('d/m/Y', strtotime($data->created_at));
fputcsv($file, array($data->id, $data->userName, $data->transactionName, $data->status, $data->value, $date),';');
}
fclose($file);
};
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=".Carbon::now().".csv",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);
return Response::stream($callback, 200, $headers);
}
/*
Relatorio CSV via POST
@param $request (value)
*/
public function reportPost(Request $request)
{
$value = $request->input('value');
$month = '';
$year = '';
if (strpos($value, '/') !== false)
{
$period = explode('/', $value);
$collection = collect($period);
$month = $collection[0];
$year = $collection[1];
$value = 2;
}
switch($value){
case '30': // Filtro = Operações dos ultimos 30 dias
$condition = 'operations.created_at >= "'.Carbon::today()->subDays(30).'"';
break;
case '2': // Filtro = Operações do mês e ano especifico
$condition = 'MONTH(operations.created_at) = '.$month.' AND SUBSTRING(year(operations.created_at),1,2) = '.$year;
break;
case '0': // Filtro = Default todas as operações
$condition = '1=1';
break;
default:
return response()->json(['message' => 'Parâmetro value Invalido', 'valid' => array('30 = Ultimos 30 dias','08/20 = Mês e Anos de Referência (Fomato: MM/AA)','0 = Todos os Registros')], 400);
break;
}
$return = Operation::select('operations.id',
'operations.value',
'operations.created_at',
'users.name as userName',
'transaction_types.name as transactionName',
'status_types.name as status')
->join('users','users.id','operations.id_user')
->join('transaction_types','transaction_types.id','operations.id_transaction_type')
->join('status_types','status_types.id','operations.id_status_type')
->whereRaw($condition)
->get();
$columns = array('Id', 'Usuario', 'Tipo_Transacao', 'Status', 'Valor', 'Data');
$callback = function() use ($return, $columns)
{
$file = fopen('php://output', 'w');
fputcsv($file, $columns, ';');
foreach($return as $data) {
$date = date('d/m/Y', strtotime($data->created_at));
fputcsv($file, array($data->id, $data->userName, $data->transactionName, $data->status, $data->value, $date), ';');
}
fclose($file);
};
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=file.csv",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);
return Response::stream($callback, 200, $headers);
}
/*
Soma de todas as movimentações de um usuario
@param $user (id)
*/
public function amountUser(User $user)
{
try
{
$return = Operation::selectRaw('operations.id_user,
users.name,
users.email,
((users.opening_balance +
(select COALESCE(SUM(value),0) FROM base_ow.operations WHERE id_transaction_type IN (2,3) and id_user = '.$user->id.')) -
(select COALESCE(SUM(value),0) FROM base_ow.operations WHERE id_transaction_type = 1 and id_user = '.$user->id.')
) as current_balance')
->join('users','users.id','operations.id_user')
->where('operations.id_user', $user->id)
->groupBy('operations.id_user','users.email')
->get();
return $return;
}
catch (Exception $e)
{
return response()->json(['message' => $e->getMessage()], 400);
}
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
class UserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
factory(App\User::class)->create([
'name' => 'Administrador', 'email' => '<EMAIL>', 'birthday' => '1970-12-05', 'password' => <PASSWORD>::<PASSWORD>('<PASSWORD>')
]);
factory(App\User::class)->create([
'name' => '<NAME>', 'email' => '<EMAIL>', 'birthday' => '1970-12-05', 'password' => <PASSWORD>('<PASSWORD>')
]);
factory(App\User::class)->create([
'name' => '<NAME>', 'email' => '<EMAIL>', 'birthday' => '1985-05-08', 'password' => <PASSWORD>::<PASSWORD>('<PASSWORD>')
]);
factory(App\User::class)->create([
'name' => '<NAME>', 'email' => '<EMAIL>', 'birthday' => '1990-08-12', 'password' => <PASSWORD>::<PASSWORD>('<PASSWORD>')
]);
}
}
<file_sep># Desafio Back-End - OW Interactive 20/21
## Informações
- Desenvolvido com PHP 7.1, Laravel Framework 5.8, MySQL 8.0;
## Preparando o Projeto
- Crie uma base de dados com o nome de **base_ow**, ou com o nome de sua preferência.
- Clone o projeto
- git clone https://github.com/tiagoalvesdev/desafio-backend.git
- Após o download, acesso o projeto
- cd desafio-backend/ow
- Agora você precisa ajustar seu arquivo de conexāo com o banco (.env)
- cp .env.example .env
- Abra o arquivo **.env** e altere o valor da váriavel DB_DATABASE para **base_ow**, ou o nome que escolheu para sua base e salve o arquivo
- DB_DATABASE=base_ow
- Instale o composer
- composer install
- Agora vamos preparar as informações da nossa base, utilizando **migration** e **seeds**
- php artisan migrate
- php artisan db:seed
- Para a autenticação no sistema, utilizaremos a biblioteca **passport**
- php artisan passport:install
- php artisan key:generate
## Iniciando a aplicação
- Agora iremos subir a aplicação. Após a execução do comando abaixo, você deverá acessar seu nevegador e na URL digitar http://127.0.0.1:8000/
- php artisan serve
- Agora com nossa aplicação funcionando, iremos executar a limpeza de cache e o autoload de nossa aplicação
- php artisan cache:clear
- composer dump-autoload
## Rotas disponiveis no sistema
Method | URI | Action
----------- | ---------------------------------------- | -------------------------------------------------------
POST | api/auth/login | App\Http\Controllers\AuthenticationController@login
POST | api/auth/logout | App\Http\Controllers\AuthenticationController@logout
POST | api/auth/register | App\Http\Controllers\AuthenticationController@register
GET HEAD | api/operations | App\Http\Controllers\OperationsController@index
GET HEAD | api/operations/amount/{user} | App\Http\Controllers\OperationsController@amountUser
GET HEAD | api/operations/status/{status} | App\Http\Controllers\OperationsController@showStatus
GET HEAD | api/operations/transaction/{transaction} | App\Http\Controllers\OperationsController@showTransaction
GET HEAD | api/operations/user/{user} | App\Http\Controllers\OperationsController@showUser
GET HEAD | api/operations/{operation} | App\Http\Controllers\OperationsController@show
DELETE | api/operations/{operation}/{user} | App\Http\Controllers\OperationsController@eliminate
POST | api/report | App\Http\Controllers\OperationsController@reportPost
GET HEAD | api/report/{param} | App\Http\Controllers\OperationsController@reportGet
GET HEAD | api/report/{param}/{user} | App\Http\Controllers\OperationsController@reportGet
- Testes no Postman
- Os testes realizados nas rotas, foram com o [Postman](https://www.postman.com/)
- Para os parametros dos métodos POST
- Inseri os dados em *Body* e *x-www-form-urlencoded*
- Lembrando que para acessar os métodos, os mesmos precisam de autenticação, desta forma é necessário:
- Efetuar um login no sistema (Ex.: email: <EMAIL> / password: <PASSWORD>)
- O token gerado no acesso deverá ser inserido em *Headers*
- No campo **KEY** = Authorization e no campo **VALUE** = Bearer + *token gerado*
- Documentação das rotas [neste link](https://documenter.getpostman.com/view/12479411/TVCcXV7d/)
- Caso utilize o **Postman** para relizar os testes, você pode baixar este [arquivo json](https://drive.google.com/file/d/1PXNiROjPJHbqGmqhIu_t1CHX1sMqR6YT/view?usp=sharing) e upar na ferramenta e obter todos os rotas ja configuradas.<file_sep><?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\Model;
use Faker\Generator as Faker;
$factory->define(App\Operation::class, function (Faker $faker) {
return [
'id_user' => $faker->name,
'id_transaction_type' => $faker->name,
'id_status_type' => $faker->name,
'value' => $faker->name,
'authorization' => mt_rand(100000, 999999)
];
});
<file_sep><?php
use Illuminate\Database\Seeder;
class OperationsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
factory(App\Operation::class)->create([
'id_user' => 1, 'id_transaction_type' => 3, 'id_status_type' => 2, 'value' => 120.00
]);
factory(App\Operation::class)->create([
'id_user' => 2, 'id_transaction_type' => 2, 'id_status_type' => 2, 'value' => 59.90
]);
factory(App\Operation::class)->create([
'id_user' => 3, 'id_transaction_type' => 1, 'id_status_type' => 1, 'value' => 580.00
]);
factory(App\Operation::class)->create([
'id_user' => 3, 'id_transaction_type' => 1, 'id_status_type' => 2, 'value' => 100.00
]);
factory(App\Operation::class)->create([
'id_user' => 2, 'id_transaction_type' => 1, 'id_status_type' => 2, 'value' => 800.00
]);
factory(App\Operation::class)->create([
'id_user' => 1, 'id_transaction_type' => 3, 'id_status_type' => 2, 'value' => 99.90
]);
factory(App\Operation::class)->create([
'id_user' => 2, 'id_transaction_type' => 1, 'id_status_type' => 3, 'value' => 74.00
]);
factory(App\Operation::class)->create([
'id_user' => 3, 'id_transaction_type' => 1, 'id_status_type' => 1, 'value' => 33.90
]);
factory(App\Operation::class)->create([
'id_user' => 1, 'id_transaction_type' => 1, 'id_status_type' => 1, 'value' => 50.00
]);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\User;
use App\Operation;
use Illuminate\Http\Request;
use Exception;
use Carbon\Carbon;
class UsersController extends Controller
{
/*
Busca todos os usuarios
@param
*/
public function index()
{
try
{
return User::all()->sortBy('created_at');
}
catch (Exception $e)
{
return response()->json(['message' => $e->getMessage()], 400);
}
}
/*
Busca um usuario especifico
@param $user (id)
*/
public function show(User $user)
{
try
{
return $user;
}
catch (Exception $e)
{
return response()->json(['message' => $e->getMessage()], 400);
}
}
/*
Deleta um usuario especifico
@param $user (id)
*/
public function eliminate(User $user)
{
try
{
$returnMoves = $this->showBalance($user);
$moves = trim($returnMoves->pluck('moves'), '[]');
$balance = $user->opening_balance;
if($balance > 0){
return response()->json(['message' => 'Nāo foi possivel exclusāo. Existe saldo na conta deste usuário!'], 400);
}else if($moves > 0){
return response()->json(['message' => 'Nāo foi possivel exclusāo. Existem movientações para este usuário!'], 400);
}else{
$user->delete();
return response()->json(['success'=>true], 201);
}
}
catch (Exception $e)
{
return response()->json(['message' => $e->getMessage()], 400);
}
}
/*
Atualiza saldo inicial do usuario
@param $user (id)
*/
public function updateBalance(User $user, Request $request)
{
try
{
$user->opening_balance = $request->input('opening_balance');
$user->save();
return response()->json(['success'=>true], 201);
}
catch (Exception $e)
{
return response()->json(['message' => $e->getMessage()], 400);
}
}
/*
Consulta a quantidade de movimentacoes do usuario
@param $user (id)
*/
public function showBalance(User $user)
{
try
{
$return = Operation::selectRaw('COUNT(id) as moves')
->where('id_user', $user->id)
->get();
return $return;
}
catch (Exception $e)
{
return response()->json(['message' => $e->getMessage()], 400);
}
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
class StatusTypeTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
factory(App\StatusType::class)->create([
'name' => 'Aprovada'
]);
factory(App\StatusType::class)->create([
'name' => 'Rejeitada'
]);
factory(App\StatusType::class)->create([
'name' => 'Aguardando'
]);
}
}
<file_sep><?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
/*Authentication*/
Route::prefix('auth')->group(function(){
Route::post("register", "AuthenticationController@register"); // cadastro do usuario
Route::post("login", "AuthenticationController@login");
Route::middleware('auth:api')->group(function(){
Route::post("logout", "AuthenticationController@logout");
});
});
Route::middleware('auth:api')->group(function(){
/*Users*/
Route::prefix('users')->group(function(){
Route::get("", "UsersController@index");
Route::get("{user}", "UsersController@show");
Route::delete("{user}", "UsersController@eliminate");
Route::patch("{user}", "UsersController@updateBalance");
});
/*Operations*/
Route::prefix('operations')->group(function(){
Route::get("", "OperationsController@index");
Route::get("{operation}", "OperationsController@show");
Route::get("user/{user}", "OperationsController@showUser");
Route::get("status/{status}", "OperationsController@showStatus");
Route::get("transaction/{transaction}", "OperationsController@showTransaction");
Route::delete("{operation}/{user}", "OperationsController@eliminate");
Route::get("amount/{user}", "OperationsController@amountUser");
});
/* Report via POST */
Route::prefix('report')->group(function(){
Route::post("", "OperationsController@reportPost");
});
});
/* Reports via GET*/
Route::get("report/{param}", "OperationsController@reportGet");
Route::get("report/{param}/{user}", "OperationsController@reportGet");
Route::any('', function () {
return response()->json(['message' => 'Rota nāo localizada'], 401);
});
Route::fallback(function () {
return response()->json(['message' => 'Rota nāo localizada'], 401);
});
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Exception;
class AuthenticationController extends Controller
{
/*
Inserir usuario
$param request
*/
public function register(Request $request)
{
try
{
$date = new Carbon();
$ages = $date->subYears(18)->format("Y-m-d");
$request->validate([
'name' => 'required|string|max:255|min:1',
'email' => 'required|string|email',
'birthday' => 'required|date|before:'.$ages,
'password' => '<PASSWORD>',
]);
$user = User::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'birthday' => $request->input('birthday'),
'password' => <PASSWORD>($request->input('password'))
]);
return response()->json(['success'=>true], 201);
}
catch (Exception $e)
{
return response()->json(['message' => $e->getMessage()], 400);
}
}
/*
Login com token
$param request
*/
public function login(Request $request)
{
try
{
$request->validate([
'email' => 'required|string|email',
'password' => '<PASSWORD>',
]);
$credentials = [
'email' => $request->input('email'),
'password' => $request->input('password'),
];
if(!Auth::attempt($credentials)){
return response()->json(['message' => 'Erro na autenticaçāo'], 401);
}
$user = $request->user();
$token = $user->createToken('AccessToken')->accessToken;
return response()->json(['message' => 'Logado com sucesso', 'token' => $token], 200);
}
catch (Exception $e)
{
return response()->json(['message' => $e->getMessage()], 400);
}
}
/*
Logout
$param request
*/
public function logout(Request $request)
{
try
{
$request->user()->token()->revoke();
return response()->json(['message' => 'Deslogado com sucesso'], 200);
}
catch (Exception $e)
{
return response()->json(['message' => $e->getMessage()], 400);
}
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Operation extends Model
{
protected $fillable = ['id_user', 'id_transaction_type', 'id_status_type', 'value', 'authorization'];
}
<file_sep><?php
use Illuminate\Database\Seeder;
class TransactionTypeTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
factory(App\TransactionType::class)->create([
'name' => 'Débito'
]);
factory(App\TransactionType::class)->create([
'name' => 'Crédito'
]);
factory(App\TransactionType::class)->create([
'name' => 'Estorno'
]);
}
}
<file_sep>version: '2'
services:
app-ow:
container_name: app-ow
image: httpd
ports:
- "8000:80"
volumes:
- ./:/usr/share/nginx
networks:
- app-network
mysql-ow:
container_name: mysql-ow
image: mysql:5.7.22
ports:
- "3306:3306"
environment:
MYSQL_DATABASE: root
MYSQL_ROOT_PASSWORD: <PASSWORD>
MYSQL_DATABASE: base_ow
networks:
- app-network
networks:
app-network:
driver: bridge | 065de0ef756d4a00e5ddb54aeece49a96b12270e | [
"Markdown",
"YAML",
"PHP"
] | 12 | PHP | tiagoalvesdev/desafio-backend | 805087f2591dd9f5196f9df94f7b75acfb8efffd | dc174023cf4ddc0412ea86f998bdf1d9d3d256cb |
refs/heads/master | <repo_name>thoamsy/codemod<file_sep>/transform/byteui-icon-default-import.js
import { Transform } from 'jscodeshift';
const transform: Transform = (file, api, options) => {
const j = api.jscodeshift;
const root = j(file.source);
const printOptions = options.printOptions || { quote: 'single' };
const libraryName = '@bytedesign/web-react/icon';
const transform = (iconName) => libraryName + '/react-icon/' + iconName;
let iconNames = [];
root
.find(j.ImportDeclaration, {
source: {
value: libraryName,
},
})
.forEach((path) => {
iconNames.push(
...path.value.specifiers.map((specifier) => specifier.imported.name)
);
})
.insertAfter(
iconNames.map((icon) => {
return j.importDeclaration(
[j.importDefaultSpecifier(j.identifier(icon))],
j.literal(transform(icon)),
'value'
);
})
);
root
.find(j.ImportDeclaration, {
source: {
value: libraryName,
},
})
.remove();
return root.toSource(printOptions);
};
export default transform;
<file_sep>/generate-export-to-index.mjs
import path from 'path';
import program from 'commander';
import fs from 'fs';
import j from 'jscodeshift';
program
.requiredOption('-d, --dir <dir>', '生成 index 文件的路径')
.parse(process.argv);
const cur = new URL(path.dirname(import.meta.url)).pathname;
const dir = path.resolve(cur, '..', program.dir);
const jtsx = j.withParser('tsx');
try {
console.group('读取开始');
const statusOfExported = fs
.readdirSync(dir)
.filter(name => !name.startsWith('index.') && name.endsWith('.ts'))
.reduce((result, name) => {
const source = fs.readFileSync(path.resolve(dir, './' + name), {
encoding: 'utf8',
});
const hasExportNamed =
jtsx(source).find(j.ExportNamedDeclaration).length > 0;
const hasExportDefault =
jtsx(source).find(j.ExportDefaultDeclaration).length > 0;
result[name] = [hasExportNamed, hasExportDefault];
console.log(`读取 ${name} 成功`);
return result;
}, {});
console.groupEnd();
const indexPath = path.resolve(dir, './index.ts');
let wroteExportNamed = new Set();
let wroteExportDefault = new Set();
try {
const source = fs.readFileSync(indexPath, {
encoding: 'utf8',
});
const getNameWithoutPrefix = node =>
node.value.source.value.replace(/^\.\//, '');
wroteExportNamed = new Set(
jtsx(source)
.find(j.ExportAllDeclaration)
.paths()
.map(getNameWithoutPrefix),
);
wroteExportDefault = new Set(
jtsx(source)
.find(j.ExportNamedDeclaration)
.paths()
.filter(node => {
// export const a = 1 这种是没有 source 的
if (!node.value.source) {
return false;
}
return (
statusOfExported[getNameWithoutPrefix(node) + '.ts'] &&
node.value.specifiers.findIndex(
specifier => specifier.local.name === 'default',
) > -1
);
})
.map(getNameWithoutPrefix),
);
} catch (err) {
console.log('index 文件不存在,将会自动创建');
}
const content = Object.entries(statusOfExported)
.flatMap(([name, [hasExportNamed, hasExportDefault]]) => {
const noSuffix = name.replace(/\..+$/, '');
const res = [];
if (!wroteExportNamed.has(noSuffix) && hasExportNamed) {
res.push(`export * from './${noSuffix}';`);
}
if (!wroteExportDefault.has(noSuffix) && hasExportDefault) {
res.push(`export { default as ${noSuffix} } from './${noSuffix}';`);
}
return res;
})
.join('\n');
if (!content) {
console.log('没有可写入的 export');
} else {
fs.appendFileSync(indexPath, content, {
encoding: 'utf8',
});
console.info(`写入 export to ${dir} 成功!`);
}
} catch (err) {
console.error(err.message);
}
<file_sep>/transform/merge-import-to-index.js
import { Transform } from 'jscodeshift';
// const urls = process.argv.slice(2).length
// ? process.argv.slice(2)
// : ['util', 'services', 'constants'];
const urls = ['util'];
const transform: Transform = (file, api, options) => {
const j = api.jscodeshift;
const printOptions = options.printOptions || { quote: 'single' };
const root = j(file.source);
let hasModifications = false;
function mergePrefixURLWith(prefix) {
const imported = root.find(j.ImportDeclaration).filter(e => {
return e.value.source.value.startsWith(prefix);
});
// console.log(imported.paths().map((path) => path.value.source.value));
const firstIndexImport = imported
.filter(e => e.value.source.value === prefix + '/index')
.paths()[0];
if (!firstIndexImport) {
return;
}
const otherImport = imported.filter(e => e !== firstIndexImport);
const otherImportSpecifiers = otherImport.find(j.ImportSpecifier).nodes();
const otherImportDefaultSpecifiers = otherImport
.find(j.ImportDefaultSpecifier)
.replaceWith(node =>
j.importSpecifier.from({
imported: node.value.local,
}),
)
.nodes();
imported.replaceWith(node => {
if (node !== firstIndexImport) {
return null;
}
node.value.specifiers = node.value.specifiers
.concat(otherImportDefaultSpecifiers)
.concat(otherImportSpecifiers);
hasModifications = true;
return j.importDeclaration(node.value.specifiers, node.value.source);
});
}
urls.forEach(mergePrefixURLWith);
if (!hasModifications) {
return;
}
return root.toSource(printOptions);
};
export default transform;
<file_sep>/test/test.ts
import safeGet from './safeGet';
import _ from 'lodash';
import { get, set } from 'lodash';
const obj = { a: 1 };
safeGet('a', obj, 0);
// obj?.a ?? 0
safeGet('a', { a: 1 }, 0);
safeGet('a.b.c.', { a: 1 }, 0);
_.get(obj, 'o', 0);
<file_sep>/README.md
# CodeMod 集合
https://astexplorer.net/
https://github.com/facebook/jscodeshift/
## icon 迁移
因为组件库大更新,名字发生了变更。
思路:通过一个 Map 对应 imported.name,接着搜索所有的 JSX element,替换它们
总体比较简单
参考文档: https://skovy.dev/jscodeshift-custom-transform/
## 合并 import
用于合并同一个文件夹下的 import 到 `xxx/index` 中,让代码更加整洁。
```js
import a, { f } from 'util/index';
import b from 'util/a';
import c, {d, e} from 'util/b';
```
转化成
```js
import a, { f, b, c, d, e } from 'util/index';
```
同时如果需要在 index 生成 export 文件,可以使用 [generate-export-to-index.mjs](./generate-export-to-index.mjs), 目前功能简单,不支持文件夹递归
## 参考文献
https://nec.is/writing/transform-your-codebase-using-codemods/
https://medium.com/@andrew_levine/writing-your-very-first-codemod-with-jscodeshift-7a24c4ede31b
https://padraig.io/automate-refactoring-jscodeshift/
<file_sep>/test/test-icon.ts
import React, { FC, useCallback, useEffect, useState } from 'react';
import { Button } from '@bytedesign/web-react';
import { IconPlusCircle, IconAdd } from '@bytedesign/web-react/icon';
import _ from 'lodash';
const BackTop: FC<{
el: HTMLDivElement | null;
}> = ({ el }) => {
const [visible, setVisible] = useState(false);
useEffect(() => {
if (!el) return;
const handler = _.debounce(() => setVisible(el.scrollTop > 100), 100);
el.addEventListener('scroll', handler);
return () => {
el.removeEventListener('scroll', handler);
};
}, [el]);
const scrollToTop = useCallback(() => {
if (!el) {
return;
}
el.scrollTop = 0;
}, [el]);
if (!visible || !el) {
return null;
}
return (
<div
style={{
position: 'fixed',
bottom: '0.08rem',
right: 0,
}}
>
<Button
type="dashed"
style={{
background: 'transparent',
width: '0.24rem',
height: '0.24rem',
lineHeight: '0.24rem',
padding: 0,
}}
onClick={scrollToTop}
>
<IconPlusCircle
style={{
color: 'var(--primary-color)',
fontSize: '0.2rem',
verticalAlign: 'middle',
margin: 0,
}}
/>
<IconAdd style={{ height: 30 }}></IconAdd>
</Button>
</div>
);
};
export default BackTop;
<file_sep>/transform/transform-icon-to-v2.js
import { Transform } from 'jscodeshift';
const iconMap = {
IconAddCircle: 'IconPlusCircle',
IconAdd: 'IconPlus',
IconAudioFileOutline: 'IconFileAudio',
IconCreate: 'IconPen',
IconError: 'IconCloseCircleFill',
IconFavoriteOutline: 'IconHeart',
IconFavorite: 'IconHeartFill',
IconFileOutline: 'IconFile',
IconHeartOutline: 'IconHeart',
IconHelp: 'IconQuestionCircleFill',
IconImageFileOutline: 'IconFileImage',
IconInfoFill: 'IconInfoCircleFill',
IconInfoOutline: 'IconInfoCircle',
IconLike: 'IconThumbUp',
IconMuteOutline: 'IconMute',
IconPauseCircleOutline: 'IconPauseCircle',
IconPdfFileOutline: 'IconFilePdf',
IconPeople: 'IconUserGroup',
IconPerson: 'IconUser',
IconPlace: 'IconLocation',
IconPlayCircleOutline: 'IconPlayCircle',
IconRemoveCircle: 'IconMinusCircleFill',
IconRemove: 'IconMinus',
IconSoundOutline: 'IconSound',
IconStarOutline: 'IconStar',
IconSyncGreen: 'IconSync',
IconVideoFileOutline: 'IconFileVideo',
IconWarningCircle: 'IconExclamationCircle',
IconWarningFill: 'IconExclamationCircleFill',
IconFaceNoExpression: 'IconFaceMehFill',
IconFaceSmile: 'IconFaceSmileFill',
IconFaceUnsmile: 'IconFaceFrownFill',
IconReport: 'IconExclamationPolygonFill',
};
const libraryName = '@bytedesign/web-react/icon';
const transform: Transform = (file, api, options) => {
const j = api.jscodeshift;
const printOptions = options.printOptions || { quote: 'single' };
const root = j(file.source);
let hasModifications = false;
root
.find(j.ImportDeclaration)
.filter(e => {
if (e.value.source.value === libraryName) {
return (
e.value.specifiers.filter(icon => {
if (iconMap[icon.imported.name]) {
return true;
}
}).length > 0
);
}
})
.forEach(node => {
hasModifications = true;
node.value.specifiers = node.value.specifiers.map(specifier => {
if (iconMap[specifier.imported.name]) {
return j.importSpecifier(
j.identifier(iconMap[specifier.imported.name]),
);
} else {
return specifier;
}
});
});
if (!hasModifications) {
return;
}
root
.findJSXElements()
.filter(e => {
if (e.value.openingElement) {
const { openingElement } = e.value;
if (iconMap[openingElement.name.name]) {
return true;
}
}
})
.replaceWith(node => {
const newName = j.jsxIdentifier(
iconMap[node.value.openingElement.name.name],
);
const element = {
...node.value,
name: newName,
openingElement: {
...node.value.openingElement,
name: newName,
},
};
if (!element.openingElement.selfClosing) {
element.closingElement = {
...node.value.closingElement,
name: newName,
};
}
return j.jsxElement.from(element);
});
return root.toSource();
};
export default transform;
| 86157b3ee802e34d77955aefdbf1b058e0032796 | [
"JavaScript",
"TypeScript",
"Markdown"
] | 7 | JavaScript | thoamsy/codemod | aac69c247535ff4d5aa3b4c670e152ca882dd89d | 9e48845a01ee148d893ddad8d1444d352383449f |
refs/heads/master | <repo_name>progfay/mac-setup<file_sep>/.macos
#!/usr/bin/env bash
# https://mths.be/macos
# Close any open System Preferences panes, to prevent them from overriding
# settings we’re about to change
osascript -e 'tell application "System Preferences" to quit'
# Ask for the administrator password upfront
sudo -v
# Keep-alive: update existing `sudo` time stamp until `.macos` has finished
while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null &
###############################################################################
# Keyboard #
###############################################################################
defaults write com.apple.HIToolbox AppleSelectedInputSources -array "
<dict>
<key>Bundle ID</key><string>com.apple.inputmethod.Kotoeri</string>
<key>Input Mode</key><string>com.apple.inputmethod.Roman</string>
<key>InputSourceKind</key><string>Input Mode</string>
</dict>"
defaults write com.apple.inputmethod.Kotoeri JIMPrefAutocorrectionKey -int 0
defaults write com.apple.inputmethod.Kotoeri JIMPrefCandidateWindowFontKey -string "HiraMinProN-W3"
defaults write com.apple.inputmethod.Kotoeri JIMPrefCharacterForYenKey -int 0
defaults write com.apple.inputmethod.Kotoeri JIMPrefLiveConversionKey -int 0
vid=$(ioreg -r -n 'Apple Internal Keyboard / Trackpad' | grep -E 'idVendor' | awk '{ print $4 }')
pid=$(ioreg -r -n 'Apple Internal Keyboard / Trackpad' | grep -E 'idProduct' | awk '{ print $4 }')
defaults -currentHost write -g "com.apple.keyboard.modifiermapping.${vid}-${pid}-0" -array-add "
<dict>
<key>HIDKeyboardModifierMappingDst</key>
<integer>30064771300</integer>
<key>HIDKeyboardModifierMappingSrc</key>
<integer>30064771129</integer>
</dict>"
function shortcut_config () {
if [ $1 = 0 ]; then
defaults write com.apple.symbolichotkeys AppleSymbolicHotKeys -dict-add $1 "
<dict>
<key>enabled</key><false/>
</dict>"
else
defaults write com.apple.symbolichotkeys AppleSymbolicHotKeys -dict-add $1 "
<dict>
<key>enabled</key><true/>
<key>value</key>
<dict>
<key>parameters</key>
<array>
$( for parameter in $(echo $2); do printf "<integer>${parameter}</integer>"; done )
</array>
<key>type</key><string>standard</string>
</dict>
</dict>"
fi
}
shortcut_config 7 0
shortcut_config 8 0
shortcut_config 9 0
shortcut_config 10 0
shortcut_config 11 0
shortcut_config 12 0
shortcut_config 13 0
shortcut_config 27 0
shortcut_config 32 1 "107 40 1310720"
shortcut_config 33 1 "106 38 1310720"
shortcut_config 34 1 "107 40 1441792"
shortcut_config 35 1 "106 38 1441792"
shortcut_config 36 0
shortcut_config 37 0
shortcut_config 51 0
shortcut_config 52 0
shortcut_config 57 0
shortcut_config 59 0
shortcut_config 60 0
shortcut_config 61 0
shortcut_config 64 0
shortcut_config 65 0
shortcut_config 79 1 "104 4 1310720"
shortcut_config 80 1 "104 4 1441792"
shortcut_config 81 1 "108 37 1310720"
shortcut_config 82 1 "108 37 1441792"
shortcut_config 118 0
shortcut_config 119 0
shortcut_config 120 0
shortcut_config 121 0
shortcut_config 162 0
###############################################################################
# Trackpad #
###############################################################################
defaults write com.apple.AppleMultitouchTrackpad ActuateDetents -bool true
defaults write com.apple.AppleMultitouchTrackpad Clicking -bool true
defaults write com.apple.AppleMultitouchTrackpad Dragging -bool false
defaults write com.apple.AppleMultitouchTrackpad FirstClickThreshold -bool false
defaults write com.apple.AppleMultitouchTrackpad ForceSuppressed -bool false
defaults write com.apple.AppleMultitouchTrackpad HIDScrollZoomModifierMask -int 1048576
defaults write com.apple.AppleMultitouchTrackpad SecondClickThreshold -bool false
defaults write com.apple.AppleMultitouchTrackpad TrackpadCornerSecondaryClick -bool false
defaults write com.apple.AppleMultitouchTrackpad TrackpadFiveFingerPinchGesture -int 2
defaults write com.apple.AppleMultitouchTrackpad TrackpadFourFingerHorizSwipeGesture -int 2
defaults write com.apple.AppleMultitouchTrackpad TrackpadFourFingerPinchGesture -int 2
defaults write com.apple.AppleMultitouchTrackpad TrackpadFourFingerVertSwipeGesture -int 2
defaults write com.apple.AppleMultitouchTrackpad TrackpadHandResting -bool true
defaults write com.apple.AppleMultitouchTrackpad TrackpadHorizScroll -bool true
defaults write com.apple.AppleMultitouchTrackpad TrackpadMomentumScroll -bool true
defaults write com.apple.AppleMultitouchTrackpad TrackpadPinch -bool false
defaults write com.apple.AppleMultitouchTrackpad TrackpadRightClick -bool true
defaults write com.apple.AppleMultitouchTrackpad TrackpadRotate -bool true
defaults write com.apple.AppleMultitouchTrackpad TrackpadScroll -bool true
defaults write com.apple.AppleMultitouchTrackpad TrackpadThreeFingerDrag -bool true
defaults write com.apple.AppleMultitouchTrackpad TrackpadThreeFingerHorizSwipeGesture -int 0
defaults write com.apple.AppleMultitouchTrackpad TrackpadThreeFingerTapGesture -int 0
defaults write com.apple.AppleMultitouchTrackpad TrackpadThreeFingerVertSwipeGesture -int 0
defaults write com.apple.AppleMultitouchTrackpad TrackpadTwoFingerDoubleTapGesture -int 1
defaults write com.apple.AppleMultitouchTrackpad TrackpadTwoFingerFromRightEdgeSwipeGesture -int 3
defaults write NSGlobalDomain com.apple.trackpad.forceClick -bool true
defaults write NSGlobalDomain com.apple.trackpad.scaling -float 0.6875
defaults write NSGlobalDomain com.apple.trackpad.scrolling -float 1.7
defaults write NSGlobalDomain AppleEnableSwipeNavigateWithScrolls -bool true
# Enable "natural" scrolling
defaults write NSGlobalDomain com.apple.swipescrolldirection -bool true
# Trackpad: map bottom right corner to right-click
defaults -currentHost write NSGlobalDomain com.apple.trackpad.trackpadCornerClickBehavior -int 1
defaults -currentHost write NSGlobalDomain com.apple.trackpad.enableSecondaryClick -bool true
###############################################################################
# Finder #
###############################################################################
defaults write com.apple.finder AppleShowAllFiles -bool true
defaults write com.apple.finder FinderSounds -bool false
defaults write com.apple.finder FinderSpawnTab -bool false
defaults write com.apple.finder FXDefaultSearchScope -string "SCcf"
defaults write com.apple.finder FXEnableExtensionChangeWarning -bool false
defaults write com.apple.finder FXEnableRemoveFromICloudDriveWarning -bool false
defaults write com.apple.finder FXEnableSlowAnimation -bool false
defaults write com.apple.finder FXICloudDriveDeclinedUpgrade -bool false
defaults write com.apple.finder FXICloudDriveDesktop -bool false
defaults write com.apple.finder FXICloudDriveDocuments -bool false
defaults write com.apple.finder FXICloudDriveEnabled -bool false
defaults write com.apple.finder FXICloudDriveDesktop -bool false
defaults write com.apple.finder FXICloudDriveFirstSyncDownComplete -bool false
defaults write com.apple.finder FXInfoPanesExpanded -dict General -bool true OpenWith -bool true Privileges -bool true
defaults write com.apple.finder FXPreferredViewStyle -string "clmv"
defaults write com.apple.finder NewWindowTarget -string "PfDe"
defaults write com.apple.finder NewWindowTargetPath -string "file://${HOME}/Desktop/"
defaults write com.apple.finder OpenWindowForNewRemovableDisk -bool true
defaults write com.apple.finder ShowExternalHardDrivesOnDesktop -bool true
defaults write com.apple.finder ShowHardDrivesOnDesktop -bool false
defaults write com.apple.finder ShowMountedServersOnDesktop -bool false
defaults write com.apple.finder ShowPathbar -bool true
defaults write com.apple.finder ShowPreviewPane -bool false
defaults write com.apple.finder ShowRecentTags -bool false
defaults write com.apple.finder ShowRemovableMediaOnDesktop -bool false
defaults write com.apple.finder ShowSidebar -bool true
defaults write com.apple.finder ShowStatusBar -bool false
defaults write com.apple.finder ShowTabView -bool false
defaults write com.apple.finder SidebarShowingSignedIntoiCloud -bool false
defaults write com.apple.finder SidebarShowingiCloudDesktop -bool false
defaults write com.apple.finder WarnOnEmptyTrash -bool true
defaults write com.apple.finder _FXSortFoldersFirst -bool true
###############################################################################
# Dock, Dashboard, and hot corners #
###############################################################################
defaults write com.apple.dock autohide -bool true
defaults write com.apple.dock autohide-delay -float 0
defaults write com.apple.dock autohide-time-modifier -float 1
defaults write com.apple.dock expose-group-apps -bool true
defaults write com.apple.dock largesize -int 16
defaults write com.apple.dock magnification -bool false
defaults write com.apple.dock mineffect -string "genie"
defaults write com.apple.dock minimize-to-application -bool true
defaults write com.apple.dock mru-spaces -bool false
defaults write com.apple.dock no-bouncing -bool false
defaults write com.apple.dock orientation -string "left"
defaults write com.apple.dock show-process-indicators -bool true
defaults write com.apple.dock showMissionControlGestureEnabled -bool true
defaults write com.apple.dock showAppExposeGestureEnabled -bool true
defaults write com.apple.dock showDesktopGestureEnabled -bool true
defaults write com.apple.dock showLaunchpadGestureEnabled -bool true
defaults write com.apple.dock tilesize -int 16
defaults write com.apple.dock wvous-tl-corner -int 0
defaults write com.apple.dock wvous-tl-modifier -int 0
defaults write com.apple.dock wvous-tr-corner -int 0
defaults write com.apple.dock wvous-tr-modifier -int 0
defaults write com.apple.dock wvous-bl-corner -int 0
defaults write com.apple.dock wvous-bl-modifier -int 0
defaults write com.apple.dock wvous-br-corner -int 0
defaults write com.apple.dock wvous-br-modifier -int 0
###############################################################################
# Miscs #
###############################################################################
# Disable Siri
defaults write com.apple.Siri StatusMenuVisible -bool false
defaults write com.apple.Siri UserHasDeclinedEnable -bool true
defaults write com.apple.assistant.support 'Assistant Enabled' 0
# Disable Screen Saver
defaults -currentHost write com.apple.screensaver idleTime -int 0
# Disable Crash Reporter
defaults write com.apple.CrashReporter DialogType none
# Show Percentage of battery
defaults write com.apple.menuextra.battery ShowPercent -string YES
# Show hidden files (dot files)
defaults write com.apple.finder AppleShowAllFiles -boolean true
defaults write com.apple.screencapture disable-shadow -bool true
defaults write com.apple.screencapture location -string "${HOME}/Desktop"
defaults write com.apple.screencapture target -string clipboard
defaults write com.apple.screencapture type -string 'png'
# Avoid creating .DS_Store files on network or USB volumes
defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true
defaults write com.apple.desktopservices DSDontWriteUSBStores -bool true
defaults write com.apple.universalaccess closeViewPanningMode -int 1
defaults write com.apple.universalaccess closeViewScrollWheelToggle -bool true
defaults write com.apple.universalaccess closeViewSmoothImages -bool true
defaults write com.apple.universalaccess closeViewZoomMode -int 0
defaults write com.apple.universalaccess closeViewScrollWheelModifiersInt -int 1048576
# Disable press-and-hold for keys in favor of key repeat
defaults write NSGlobalDomain ApplePressAndHoldEnabled -bool false
# Set a blazingly fast keyboard repeat rate
defaults write NSGlobalDomain KeyRepeat -int 6
defaults write NSGlobalDomain InitialKeyRepeat -int 25
defaults write NSGlobalDomain AppleInterfaceStyle -string "Dark"
defaults write NSGlobalDomain AppleTemperatureUnit -string "Celsius"
defaults write NSGlobalDomain AppleMeasurementUnits -string "Centimeters"
defaults write NSGlobalDomain AppleMetricUnits -bool true
defaults write NSGlobalDomain com.apple.sound.beep.flash -int 0
defaults write NSGlobalDomain com.apple.sound.beep.volume -int 1
# Set sidebar icon size to medium
defaults write NSGlobalDomain NSTableViewDefaultSizeMode -int 2
# Show scrollbars when scrolling
defaults write NSGlobalDomain AppleShowScrollBars -string "WhenScrolling"
# Disable automatic termination of inactive apps
defaults write NSGlobalDomain NSDisableAutomaticTermination -bool true
# Disable automatic capitalization
defaults write NSGlobalDomain NSAutomaticCapitalizationEnabled -bool false
# Disable smart dashes as they’re annoying when typing code
defaults write NSGlobalDomain NSAutomaticDashSubstitutionEnabled -bool false
# Disable automatic period substitution as it’s annoying when typing code
defaults write NSGlobalDomain NSAutomaticPeriodSubstitutionEnabled -bool false
# Disable smart quotes as they’re annoying when typing code
defaults write NSGlobalDomain NSAutomaticQuoteSubstitutionEnabled -bool false
# Disable auto-correct
defaults write NSGlobalDomain NSAutomaticSpellingCorrectionEnabled -bool false
# Disable text completion
defaults write NSGlobalDomain NSAutomaticTextCompletionCollapsed -bool false
defaults write NSGlobalDomain NSAutomaticTextCompletionEnabled -bool false
# Disable automatic animation
defaults write NSGlobalDomain NSAutomaticWindowAnimationsEnabled -bool false
# Show language menu in the top right corner of the boot screen
sudo defaults write /Library/Preferences/com.apple.loginwindow showInputMenu -bool true
# Enable HiDPI display modes (requires restart)
sudo defaults write /Library/Preferences/com.apple.windowserver DisplayResolutionEnabled -bool true
defaults write com.apple.systempreferences NSQuitAlwaysKeepsWindows -bool false
defaults write com.apple.systempreferences ShowAllMode -bool false
# Enable subpixel font rendering on non-Apple LCDs
# Reference: https://github.com/kevinSuttle/macOS-Defaults/issues/17#issuecomment-266633501
defaults write NSGlobalDomain AppleFontSmoothing -int 1
# Enable spring loading for directories
defaults write NSGlobalDomain com.apple.springing.enabled -bool true
# Remove the spring loading delay for directories
defaults write NSGlobalDomain com.apple.springing.delay -float 0.5
# Show the ~/Library and /Volumes folder
sudo chflags nohidden /Volumes ~/Library
# Disable Notification Center and remove the menu bar icon
launchctl unload -w /System/Library/LaunchAgents/com.apple.notificationcenterui.plist 2> /dev/null
# Disable the sound effects on boot
sudo nvram SystemAudioVolume=" "
###############################################################################
# Energy saving #
###############################################################################
# Enable lid wakeup
sudo pmset -a lidwake 1
# Sleep the display after 15 minutes
sudo pmset -b displaysleep 15
sudo pmset -c displaysleep 0
# Set machine sleep to 5 minutes on battery
sudo pmset -b sleep 5
# Disable machine sleep while charging
sudo pmset -c sleep 0
# Set standby delay to 24 hours (default is 1 hour)
sudo pmset -a standbydelay 86400
# Hibernation mode
sudo pmset -a hibernatemode 3
# Restart automatically if the computer freezes
sudo systemsetup -setrestartfreeze on
# Never go into computer sleep mode
sudo systemsetup -setcomputersleep Off > /dev/null
# Remove the sleep image file to save disk space
# sudo rm /private/var/vm/sleepimage
# Create a zero-byte file instead…
# sudo touch /private/var/vm/sleepimage
# …and make sure it can’t be rewritten
# sudo chflags uchg /private/var/vm/sleepimage
###############################################################################
# Kill affected applications #
###############################################################################
for app in \
"cfprefsd" \
"Dock" \
"Finder" \
"SystemUIServer"; do
killall "${app}" &> /dev/null
done
echo "Done. Note that some of these changes require a logout/restart to take effect."
<file_sep>/README.md
# mac-setup
```sh
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/progfay/mac-setup/master/init.sh)"
```
<file_sep>/init.sh
#!/bin/sh
function heading () {
printf '\n\e[30;46;1m %s \e[m\n' "$1"
}
function confirm () {
printf '\e[36;1m%s, and press Enter...\e[m' "$1"
read
}
heading 'XCode'
xcode-select --install
heading 'Homebrew'
if [ ! -x "`which brew`" ]; then /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"; fi
brew update
brew upgrade
brew -v
heading '1Password'
brew cask install 1password
open '/Applications/1Password*.app'
confirm 'Please login to 1Password'
heading 'Google Drive'
brew cask install google-backup-and-sync
open '/Applications/Backup and Sync.app'
confirm 'Login with Google Drive to Google Backup and Sync'
heading 'Mackup'
brew install mackup
# First restoring, restore only default applications (.mackup, .mackup.cfg)
echo '[storage]\nengine = google_drive' > ~/.mackup.cfg
mackup restore
# Second restoring, restore with .mackup & .mackup.cfg that is backed up
mackup restore --force
heading 'brew bundle'
open '/System/Applications/App Store.app'
confirm 'Login to App Store'
brew install mas
brew bundle --global install
heading 'node'
n stable
xargs npm install --global < ~/.npm/npm-global.packages
heading 'System Prefernces'
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/progfay/mac-setup/master/.macos)"
heading 'Restart'
confirm 'Restart PC to take effect of init'
sudo shutdown -r now
| 1b1cd92687372c5dab0ce8f5b25e5ad115f6c0a6 | [
"Markdown",
"Shell"
] | 3 | Shell | progfay/mac-setup | 3d3d617f14c6c5ce4cf521a883167cb7b467b3e8 | 39d143228cfa52208dae8e0e7521ce9931827f82 |
refs/heads/master | <file_sep>import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy import stats
def viz(static_path, csv_filename, plot_filename):
full_csv_path = static_path + "/" + csv_filename
full_plot_path = static_path + "/" + plot_filename
fig, ax = plt.subplots(4)
df = pd.read_csv(full_csv_path)
b_z = np.abs(stats.zscore(df['b']))
g_z = np.abs(stats.zscore(df['g']))
r_z = np.abs(stats.zscore(df['r']))
df['b_z'] = b_z
df['g_z'] = g_z
df['r_z'] = r_z
rgb_array = []
false_pos = []
true_neg = []
last_color = []
for i in range(0, df.count()[0]):
c = [df['b'][i],df['g'][i],df['r'][i]]
if max(b_z[i], max(g_z[i], r_z[i])) < 4:
rgb_array.append(c)
true_neg.append(c)
else:
rgb_array.append([0,0,0])
false_pos.append([df['r'][i],df['g'][i],df['b'][i]])
if i == df.count()[0] - 1:
last_color.append([df['r'][i],df['g'][i],df['b'][i]])
img = np.array(rgb_array, dtype=int).reshape((1, len(rgb_array), 3))
ax[0].imshow(img, extent=[0, len(rgb_array), 0, 1], aspect='auto')
ax[0].set_ylabel('Timeline')
ax[0].set_yticklabels([])
img2 = np.array(false_pos, dtype=int).reshape((1, len(false_pos), 3))
ax[1].imshow(img2, extent=[0, len(false_pos), 0, 1], aspect='auto')
ax[1].set_ylabel('Shiny/False-Pos')
ax[1].set_yticklabels([])
img3 = np.array(true_neg, dtype=int).reshape((1, len(true_neg), 3))
ax[2].imshow(img3, extent=[0, len(true_neg), 0, 1], aspect='auto')
ax[2].set_ylabel('Not-shiny')
ax[2].set_yticklabels([])
img4 = np.array(last_color, dtype=int).reshape((1, len(last_color), 3))
ax[3].imshow(img4, extent=[0, len(last_color), 0, 1], aspect='auto')
ax[3].set_ylabel('Last Color')
ax[3].set_yticklabels([])
plt.xlabel('Encounters')
plt.savefig(full_plot_path)<file_sep>import os
import sys
# Returns the directory the current script (or interpreter) is running in
def get_script_directory():
path = os.path.realpath(sys.argv[0])
if os.path.isdir(path):
return path
else:
return os.path.dirname(path)<file_sep>import cv2
import logging
import time
import os
import numpy as np
import threading
import boto3
try:
from vision.DominantColor import DominantColor
from vision.CameraHelper import CameraHelper
from vision.helpers import get_script_directory
except:
from DominantColor import DominantColor
from CameraHelper import CameraHelper
from helpers import get_script_directory
class PokeVision(CameraHelper):
def __init__(self, poke_to_match=None, base_path='/home/pi/Projects/poke-bot',dom_color_file='dominant_color.csv', z_thresh=2.0, log_name='PokeVision', asset_folder='assets', image_size=[720, 1280]):
CameraHelper.__init__(self)
self._base_path = base_path
self._logger = logging.getLogger(log_name)
self._script_dir = get_script_directory()
self._asset_folder = asset_folder
self._color_file = dom_color_file
self._tmp_filename = f'{self._base_path}/static/image_to_check.jpg'
self._backup_check_dir = f'{self._base_path}/static/checks/'
self._color_file_fullpath = self._get_dom_color_filename(poke_to_match)
# y, x image height and width
self._img_size = image_size
self._dc = DominantColor(self._color_file_fullpath, z_thresh, log_name=log_name)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
return self
def _get_dom_color_filename(self, poke_to_match=None):
return f'{self._base_path}/{self._asset_folder}/shiny_hunt/{self._color_file}' if poke_to_match==None else f'{self._script_dir}/{self._asset_folder}/shiny_hunt/{poke_to_match}/{self._color_file}'
def check_shiny(self, shiny_focus={'x':[583,797], 'y':[240,470]}):
filename = self._tmp_filename
time.sleep(6)
self._take_still_image(filename)
img = self._read_pixel_image(filename)
clean_img = self._clean_image(img, shiny_focus)
dominant_color = self._dc._get_dominant_color(clean_img, k=3)
self._save_bkp_img(clean_img, shiny_focus, w_overlay=True, color_overlay=dominant_color)
return self._dc._check_results(dominant_color)
def _focus(self, img, focus):
return self._crop_img(img, focus)
def threaded_template_match(self, img_rgb, template_objs):
threads = [None] * len(template_objs)
results = [None] * len(template_objs)
for i in range(len(threads)):
template_path = template_objs[i]['path']
conf = template_objs[i]['conf']
th = threading.Thread(target=self.template_match, args=(img_rgb,template_path,conf,results,i,))
th.start()
threads[i] = th
for i in range(len(threads)):
threads[i].join()
return results
def _make_path(self, template_name_list, template_folder):
path_list = []
for t in template_name_list:
path_list.append(f'{self._base_path}/{self._asset_folder}/state_templates/{template_folder}/{t}.jpg')
return path_list
def template_match(self, img_rgb, template_path, confidence_thresh=0.7, results=[], i=0):
try:
# Convert it to grayscale
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
except Exception as e:
print("Failed to transform base image to gray")
return [], 0, 0
try:
# Read the template
template_rgb = cv2.imread(template_path)
template = cv2.cvtColor(template_rgb, cv2.COLOR_BGR2GRAY)
# Store width and height of template in w and h
w, h = template.shape[::-1]
except Exception as e:
print(f"Failed to transform template to gray {template_path}")
return [], 0, 0
# Perform match operations.
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
# Specify a threshold
threshold = 0.7
# Store the coordinates of matched area in a numpy array
loc = np.where( res >= threshold )
# If results list is long enough to store our results
if len(results) > i:
results[i] = True if len(list(zip(*loc[::-1]))) > 0 else False
# Logic to draw boxes on the picture. For debugging purposes
# if True==False:
# pts = list(zip(*loc[::-1]))
# for p in matched_pts:
# img_rgb = self._draw_rec(img_rgb, pts[0][0], pts[0][1], pts[0][0]+w, pts[0][1] + h)
# cv2.imwrite(f'{self._base_path}/test_2.jpg',img_rgb)
return list(zip(*loc[::-1])), w, h
def _draw_rec(self, img_rgb, x_1, y_1, x_2, y_2):
return cv2.rectangle(img_rgb, (x_1,y_1), (x_2,y_2), (0,255,255), 1)
def detect_text(self):
"""Calls an API on AWS to detect text in an image. $1 per 1,000 requests"""
ui_words = ['']
image = cv2.imread('test.jpg')
is_success, im_buf_arr = cv2.imencode(".jpg", image)
byte_im = im_buf_arr.tobytes()
client=boto3.client('rekognition', region_name='us-east-2')
response=client.detect_text(Image={'Bytes':byte_im})
textDetections=response['TextDetections']
text_map = {}
print ('Detected text\n----------')
for t in textDetections:
if float(t['Confidence']) > 85.0:
pid = t.get('ParentId','')
if pid != '':
id = t['Id']
text = t['DetectedText']
if text not in ui_words:
if text_map.get(pid, '') == '':
text_map[pid] = { id: text }
else:
text_map[pid][id] = text
print(text_map)
return text_map
def _test_templates(self, img_path):
focus_list = []
#focus_list.append({'name':'fight','x':[2100,2500],'y':[420,800]})
#focus_list.append({'name':'pokemon','x':[2000,2300],'y':[1600,2000]})
#focus_list.append({'name':'bag','x':[2400,2700],'y':[1600,2000]})
#focus_list.append({'name':'run','x':[2700,2870],'y':[1000,1400]})
#focus_list.append({'name':'drifloon','x':[180,250],'y':[670,900]})
#focus_list.append({'name':'gastly','x':[127,184],'y':[750,928]})
#focus_list.append({'name':'murkrow','x':[314,371],'y':[722,928]})
#focus_list.append({'name':'rotoface','x':[1700,1920],'y':[600,2100]})
focus_list.append({'name':'smeargle','x':[280,330],'y':[737,943]})
# Read the main image
img_rgb = cv2.imread(f'{self._base_path}/{img_path}')
for focus in focus_list:
img_rgb = self._draw_rec(img_rgb, focus['x'][0], focus['y'][0], focus['x'][1], focus['y'][1])
cv2.imwrite(f'{self._base_path}/test_out_temp.jpg',img_rgb)
def set_templates(self, img_path):
focus_list = []
#focus_list.append({'name':'fight','x':[2100,2500],'y':[420,800]})
#focus_list.append({'name':'pokemon','x':[2000,2300],'y':[1600,2000]})
#focus_list.append({'name':'bag','x':[2400,2700],'y':[1600,2000]})
#focus_list.append({'name':'run','x':[2700,2870],'y':[1000,1400]})
#focus_list.append({'name':'drifloon','x':[180,250],'y':[670,900]})
#focus_list.append({'name':'gastly','x':[127,184],'y':[750,928]})
#focus_list.append({'name':'murkrow','x':[314,371],'y':[722,928]})
#focus_list.append({'name':'rotoface','x':[1700,1920],'y':[600,1950]})
focus_list.append({'name':'smeargle','x':[280,330],'y':[737,943]})
# Read the main image
img_rgb = cv2.imread(f'{self._base_path}/{img_path}')
for focus in focus_list:
img_rgb = self._focus(img_rgb, focus)
cv2.imwrite(f'{self._base_path}/{self._asset_folder}/state_templates/pname/{focus["name"]}.jpg',img_rgb)
def is_battle_screen(self, img_path):
ui_to_check = ['fight','bag','run','pokemon']
mons_to_check = ['drifloon', 'gastly', 'murkrow']
wild_check = ['rotoface']
temp_names = ui_to_check + mons_to_check + wild_check
template_paths = self._make_path(ui_to_check, 'battle') + self._make_path(mons_to_check, 'pname') + self._make_path(wild_check, 'wild')
try:
img_rgb = cv2.imread(img_path)
#if img_rgb == None:
# self._logger.error(f'Unable to read image from {img_path}')
# return {}
except:
self._logger.error(f'Unable to read image from {img_path}')
return {}
template_objs = []
for i in range(len(template_paths)):
conf = 0.6 if temp_names[i] in ui_to_check else 0.7
name = temp_names[i]
path = template_paths[i]
template_objs.append({'conf':conf,'name':name,'path':path})
results = self.threaded_template_match(img_rgb, template_objs)
ui_results = []
in_wild = False
mon_found = ''
for i in range(0, len(temp_names)):
if temp_names[i] in ui_to_check:
ui_results.append(results[i])
elif temp_names[i] in mons_to_check:
if results[i] == True:
mon_found = temp_names[i]
elif temp_names[i] in wild_check:
if results[i] == True:
in_wild = True
ret = {
'battle_screen':{
'is_battle': True if (False not in ui_results) and (None not in ui_results) else False,
'pname': mon_found,
'is_wild':in_wild
}
}
return ret
def get_base_path(self):
return self._base_path
if __name__=="__main__":
cm = PokeVision(asset_folder='ultrasun_assets')
s = time.time()
#os.popen(f'{cm.get_base_path()}/take_picture.sh test.jpg')
#print(cm.is_battle_screen('test.jpg'))
#pname_list = ['drifloon','gastly']
#print(cm.check_battle_mon('test.jpg', pname_list))
cm.set_templates('test.jpg')
#cm.set_templates('test.jpg')
print(f'time took {time.time() - s}')
<file_sep>import time
import os
try:
from gamesystem.ThreeDsComm import ThreeDsComm
except:
from ThreeDsComm import ThreeDsComm
from PokeVision import PokeVision
from CameraHelper import CameraHelper
from PokeVisionApi import PokeVisionApi
class UiManager():
def __init__(self):
self.last_state = 'startup'
self.last_press = 's_down'
def wild_next_press(self):
ret = 's_up' if self.last_press == 's_down' else 's_down'
self.last_press = ret
return ret
class UltraSunComm(ThreeDsComm):
def __init__(self):
ThreeDsComm.__init__(self)
self._ui = UiManager()
self.asset_folder = 'ultrasun_assets'
self._pvision_api = PokeVisionApi(domain='192.168.86.202', port=5000)
def game_start(self, options={}):
self._opening_sequence_a()
shiny_found = False
self._logger.info('Begin starter shiny hunt')
shiny_found = self._starter_shiny_hunt(options=options)
if shiny_found == False:
self._logger.warning('Not a shiny...soft restarting')
self._send_three_ds_command('sr', resp_timeout=5.0)
time.sleep(15)
self._com.flush()
self._send_three_ds_command('flush')
self.game_start(options=options)
def wild_shiny_hunt_loop(self, options={}):
shiny_found = False
self._logger.info('Hunting a shiny in the wild')
shiny_found = self._wild_shiny_hunt(options=options)
if shiny_found == False:
self._logger.warning('Not a shiny...trying again')
self.wild_shiny_hunt_loop(options=options)
def _opening_sequence_a(self):
self._logger.info('Skipping intro and selecting save')
for _ in range(0,6):
a_succ = self._send_three_ds_command('a')
time.sleep(1)
time.sleep(1)
def _starter_shiny_hunt(self, options={}):
# Reading macro in early so we can just kick things off
cmd_list = self._get_macro('opening_sequence_macro')
self._logger.info('Kicking off cutscene')
s_up_succ = False
while(s_up_succ != True):
s_up_succ = self._send_three_ds_command('s_up', resp_timeout=5.0)
time.sleep(1)
if self._execute_macro(cmd_list)==True:
return self._check_shiny(options.get('z_thresh', 0))
return False
def _wild_shiny_hunt(self, options={}):
mon = ''
os.popen(f'./take_picture.sh test.jpg')
time.sleep(1)
print(f"Upload of test.jpg: {self._pvision_api.upload('test.jpg', out_filename='upload.png')}")
is_battle = False
in_wild = True
while is_battle == False:
if in_wild:
print("Walking through the grass...")
# loop until screen change (?): s_up, s_down, check screen
next_button = self._ui.wild_next_press()
self._send_three_ds_command('s_down',5)
next_button = self._ui.wild_next_press()
self._send_three_ds_command('s_up',5)
else:
print("No longer in the wild, hold on")
time.sleep(7)
os.popen(f'./take_picture.sh test.jpg')
time.sleep(1)
print(f"Upload of test.jpg: {self._pvision_api.upload('test.jpg', out_filename='upload.png')}")
batt_ret = self._pvision_api.check_screen(path_to_check='upload.png')
is_battle = batt_ret['is_battle']
in_wild = batt_ret['is_wild']
mon = batt_ret['pname']
last_state = 'battle'
print(f"Ran into {mon} in the wild!")
# assume: battle screen, tap a, read text, check if correct mon to catch
# if is mon, format Pokemon obj for cur mon using screen text
# Execute move # (?)
# wait
# go to bag and catch
return True
def _check_shiny(self, z_thresh):
_shiny_checker = PokeVision(dom_color_file='dominant_color.csv', z_thresh=z_thresh, log_name=self._logger_name)
is_shiny = _shiny_checker.check_shiny()
if is_shiny==False:
self._logger.info("Not shiny...trying again")
return False
self._logger.critical("Pokémon flagged as shiny!")
return True
if __name__=="__main__":
usc = UltraSunComm()
usc._wild_shiny_hunt()<file_sep>import os
import csv
import time
try:
from gamesystem.SerialManager import SerialManager
except:
from SerialManager import SerialManager
class GameSystem(SerialManager):
def __init__(self, logger_name='GameSystem'):
SerialManager.__init__(self, logger_name=logger_name)
self.asset_folder = 'assets'
def __command_lookup(self, short_cmd):
return self.COMMANDS.get(short_cmd, '')
def __get_all_commands(self):
return self.COMMANDS
def _send_game_system_command(self, cmd, resp_timeout=1.0):
msg = ''
if cmd in self.__get_all_commands():
msg = self.__command_lookup(cmd)
if msg != '':
return self._send_serial_message(msg, resp_timeout)
else:
self._logger.warning('Invalid 3DS Command!')
return False
def _get_macro(self, macro_name):
lines = []
col_names = []
fname = f"{os.getcwd()}/{self.asset_folder}/macros/{macro_name}.csv"
with open(fname) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
col_names = row
if set(col_names) != set(['press_num','cmd','sec_from_last_press','desc']):
self._logger.info('Macro CSV file has invalid header...')
return None
line_count += 1
else:
lines.append({col_names[1]:row[1],col_names[2]:row[2],col_names[3]:row[3]})
line_count += 1
csv_file.close()
self._logger.info(f'Read in {fname}')
return lines
return None
def _execute_macro(self, cmd_list):
if cmd_list == None:
return False
for cmd_set in cmd_list:
start_time = time.time()
time_to_elapse = cmd_set['sec_from_last_press']
if cmd_set['desc'] != "":
self._logger.info(f'Macro info: {cmd_set["desc"]}')
time.sleep(float(time_to_elapse))
a_succ = False
while a_succ == False:
a_succ = self._send_game_system_command(cmd_set['cmd'])
return True
def _run_macro(self, macro_name):
return self._execute_macro(self._get_macro(macro_name))
def command_mode(self):
inp = ''
while inp!='q' or inp!='quit':
cmd = input('Button to Press:\n')
to = 1.0
if cmd in ['q','quit']:
self._logger.info('Exiting...')
break
elif cmd == 'flush':
self._com.flush()
elif cmd == 'sr':
to = 5.0
elif cmd=='':
cmd = 'a'
time.sleep(5)
msg_succ = self._send_game_system_command(cmd, to)<file_sep>import math
import argparse
def calculate_chance(start_rate, full_rate, encounters):
chance = get_probability(start_rate,full_rate,encounters)
return_obj = {}
if (start_rate >= 1 and full_rate >= 1 and encounters>= 1):
return_obj['chance_not_get_per'] = chance["miss"]
return_obj['chance_to_get_per'] = chance["get"]
return_obj['next_chance_per'] = chance["next_chance"]
return_obj['start_rate'] = str(start_rate)
return_obj['full_rate'] = str(full_rate)
return_obj['encounters'] = str(encounters)
return(return_obj)
def get_probability(base_chance, total_outcomes, num_encounters):
p1 = base_chance
p2 = total_outcomes
p3 = num_encounters
v1 = p2-p1
v6 = v1/p2
v3 = math.pow(v6, p3)
v12 = (1-v3)*100
v5 = v3*100
if (v12 > 0.001 and v5 > 0.001):
v12 = round(v12*100,2)/100
v5 = round(v5*100,2)/100
elif (v5 < 0.001):
v12 = ">99.999"
v5 = "<0.001"
elif (v12 < 0.001):
v12 = "<0.001"
v5 = ">99.999"
tot_chance = round((base_chance/total_outcomes)*10000,4)/100
chance = {}
chance["encounters"] = str(num_encounters)
chance["miss"] = str(round(v5,2))
chance["get"] = str(round(v12,2))
chance["next_get"] = str(base_chance)+" in "+str(total_outcomes)
chance["next_chance"] = str(round(tot_chance,2))
return chance
if __name__=="__main__":
# Initialize parser
parser = argparse.ArgumentParser()
# Set cli args
parser.add_argument('-s', '--start_rate', default=1, help = 'Base chance in ratio')
parser.add_argument('-f', '--full_rate', default=4096, help = 'Full chance in ratio')
parser.add_argument('-n', '--num_encounters', default=1, help = 'Number of encounters so far')
# Read arguments from command line
args = parser.parse_args()
calculate_chance(int(args.start_rate), int(args.full_rate), int(args.num_encounters))<file_sep>#!/usr/bin/env python3
import serial
import time
import argparse
import logging
import os
from gamesystem.ThreeDsComm import ThreeDsComm
from gamesystem.UltraSunComm import UltraSunComm
from vision.PokeVision import PokeVision
if __name__ == '__main__':
# Initialize parser
parser = argparse.ArgumentParser()
# Set cli args
parser.add_argument('-c', '--mode', choices=['command', 'vision','ultrasun_start','ultrasun_wild'], default='command', help = 'Change mode')
parser.add_argument('-p', '--pokemon', choices=['rowlet'], default='rowlet', help = 'Change pokemon to hunt')
parser.add_argument('-f', '--log_file_name', default='poke-handler.log', help = 'File to send log outputs')
parser.add_argument('-l', '--log_level', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], default='INFO', help = 'Log severity level')
parser.add_argument('-z', '--z_threshold', default=2.0, help = 'Threshold for dominant poke colors to flag for shinies')
# Read arguments from command line
args = parser.parse_args()
logging.basicConfig(filename=f'{os.getcwd()}/{args.log_file_name}', filemode='a', format='%(asctime)s.%(msecs)03d: %(levelname)s - %(message)s', datefmt='%Y%m%d %H:%M:%S', level=args.log_level)
log_name = 'poke-handler'
logging.info('Program starting')
if args.mode=='ultrasun_start':
logging.info('Running communication with 3DS: Pokémon: Ultra Sun. Mode: Starter Shiny Hunt')
with UltraSunComm(log_name) as usc:
usc.game_start(options={'z_thresh':float(args.z_threshold)})
elif args.mode=='ultrasun_wild':
logging.info('Running communication with 3DS: Pokémon: Ultra Sun. Mode: Wild Shiny Hunt')
with UltraSunComm(log_name) as usc:
usc.wild_shiny_hunt_loop(options={'z_thresh':float(args.z_threshold)})
elif args.mode == 'vision':
logging.info('Running vision check...')
with PokeVision(log_name=log_name, asset_folder='ultrasun_assets') as pv:
pv.template_match()
else:
logging.info('Entering command mode')
with ThreeDsComm(log_name) as tds:
tds.command_mode()<file_sep>import logging
import time
import serial
"""A class to connect to Arduino via serial connection.
The class implements a COMMAND -> RESPONSE pattern and relies on
the Arduino application code to follow the same pattern.
The class is purposefully single threaded and blocking upon write/read.
This is to prevent I/O errors caused by simultaneous writes/reads.
Example event timeline:
SerialArduino sends command 'HI'
Arduino recieves 'HI'
Arduino does some process
Arduino sends command 'HI_SUCC'
SerialArduino recieves 'HI_SUCC', indicating the Arduino processed the message properly
"""
class SerialManager():
def __init__(self, logger_name='SerialManager', valid_ports=['/dev/ttyACM0', '/dev/ttyACM1'], baud=31250):
"""
Params:
logger_name - name of logger to write to, 'SerialArduino' if none is passed
valid_ports - list of ports to attempt to connect to. Used in handling reinit failures
baud - rate at which bytes are sent on serial line. Must match on the Arduino
"""
# Attach to a logger
self._logger_name=logger_name
self._logger = logging.getLogger(logger_name)
# Set baud and port list for serial connection
self.__baud_rate = baud
self.__valid_ports = valid_ports
# All SerialArduino objects should have a command to tell Arduino to flush the line
self.COMMANDS = {'flush':'FLUSH_SER'}
print("Initializing serial communication...")
self._com = self.__init_serial_communication()
time.sleep(2)
# Tell arduino to flush it's serial line a couple of times. This prevents dropped first messages
for _ in range(0,2):
succ = self._send_serial_message(self.COMMANDS['flush'], 1)
if succ:
break
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Close port on application exit"""
self.__close_port()
def __close_port(self):
"""Safely close the serial port"""
try:
self._com.close()
except serial.SerialException as e:
self._logger.critical(f"Failed to close serial port.\nException-\n{e}")
self._logger.info("Serial port closed")
def __init_serial_communication(self):
"""Connect to serial port using parameters passed at object initialization
Returns:
serial_com - successfully connected to serial device
exit() - abort process and exit application
"""
for _ in range(0,2):
exceptions = []
for port in self.__valid_ports:
try:
# Connect to serial port
serial_com = serial.Serial(port, self.__baud_rate, timeout=1, rtscts=1)
except serial.SerialException as e:
self._logger.error(f'Failed to connect to serial port {port}...')
exceptions.append(e)
time.sleep(1.5)
else:
self._logger.info(f'Connected to {port} successfully')
# Flush line and return serial connection
serial_com.flush()
return serial_com
self._logger.critical(f'Failed to connect to all ports in {self.__valid_ports}...aborting.\nException(s)-\n{exceptions}')
exit()
def _send_serial_message(self, command, resp_timeout):
"""Write serial message and wait for a success response message
Params:
command - command to send to Arduino
resp_timeout - time to wait for response before failing
Returns:
True - successfully sent and recieved expected response
False - serial write failed/serial read failed/invalid response message
"""
self._logger.info(f'Sending command: {command}')
# Append newline char to command. Arduino looks for end of message as \n
full_command = f'{command}\n'
try:
# Flush before starting COMMAND -> RESPONSE pattern
self._com.flush()
self._com.write(full_command.encode('utf-8'))
except Exception as e:
# Failed while trying to write serial message, close port and reinitialize
self._logger.warning('Failed to write command...reinitializing serial communication.')
self.__close_port()
self._com = self.__init_serial_communication()
self._logger.error(f'Serial write error:\nException-{e}')
return False
# Wait for response from Arduino
resp = self._wait_for_serial_response(resp_timeout)
# Check if this is our expected message. If no message, return False. If matches, return True
if resp == f'{command}_SUCC':
self._logger.info(f'Got success message: {command}_SUCC')
return True
elif resp is None:
return False
# Message didn't match, return True
self._logger.error(f'Invalid return message! Expecting {command}_SUCC. Got {resp}')
return False
def _wait_for_serial_response(self, resp_timeout):
"""Wait for a message on the serial line, or time out
Params:
resp_timeout - time to wait before exiting function
Returns:
line - return message recieved via serial line
None - nothing received/timeout/failed to read from serial line
"""
try:
# Only wait for 5 seconds to recieve a response
start_time = time.time()
while (time.time() - start_time) < resp_timeout:
# Check if there is a waiting serial message
if self._com.in_waiting > 0:
# Read message in waiting
line = self._com.readline().decode('utf-8').rstrip()
# Flush line after we recieve a message
self._com.flush()
self._logger.debug(f'Recieved message: {line}')
return line
# Timed out
self._logger.warning(f'Response timeout. Waited {str(resp_timeout)} seconds.')
return None
except Exception as e:
# Failed read, close port and reinit
self._logger.error(f'Failed to read serial response...\nException-\n{e}')
self.__close_port()
time.sleep(2)
self._com = self.__init_serial_communication()
return None<file_sep>python3 poke-handler.py --mode ultrasun --log_level WARNING --z_threshold 4<file_sep>from datetime import datetime
import cv2
class CameraHelper():
def __init__(self):
self._backup_check_dir = '/'
def _take_still_image(self, out_filename):
os.popen(f'./take_picture.sh {out_filename}')
def _read_pixel_image(self, filename):
return cv2.imread(filename, 1)
def _crop_img(self, pixel_array, image_focus):
return pixel_array[image_focus['y'][0]:image_focus['y'][1], image_focus['x'][0]:image_focus['x'][1]]
def _flip_img(self, pixel_array):
return cv2.flip(pixel_array, 0)
def _clean_image(self, pixel_array, image_focus):
# 720x1280
crop = self._crop_img(pixel_array, image_focus)
crop = self._flip_img(pixel_array)
return crop
def _save_bkp_img(self, img, image_focus, w_overlay=False, color_overlay=[0,0,0]):
now = datetime.now() # current date and time
date_time = now.strftime("%Y-%m-%dT%H-%M-%S")
x_end = image_focus['y'][1] - image_focus['y'][0]
x_middle = int(x_end / 2)
y_end = image_focus['y'][1] - image_focus['y'][0]
y_middle = int(x_end / 2)
if w_overlay == True:
img[0:y_middle, 0:x_middle] = color_overlay
img[y_middle:y_end, x_middle:x_end] = color_overlay
cv2.imwrite(self._backup_check_dir + date_time + '_pixel_check.png', img)
<file_sep>import numpy as np
import cv2
import os
import logging
import time
from collections import Counter
from sklearn.cluster import KMeans
from scipy import stats
import pandas as pd
class DominantColor():
def __init__(self, dominant_color_fullpath, z_threshold, log_name='DominantColor'):
self._logger = logging.getLogger(log_name)
self._z_threshold = z_threshold
self._full_filepath = dominant_color_fullpath
self._file_headers = ['b','g','r','b_z','g_z','r_z','z_thresh']
self._file_header_str = self._set_file_header_str()
if os.path.isfile(self._full_filepath) == False:
f = open(self._full_filepath, "w")
f.write(self._file_header_str)
def _set_file_header_str(self):
header_str = ''
for h in self._file_headers:
header_str += h if header_str == '' else f',{h}'
header_str += '\n'
return header_str
def _make_record_str(self, record):
record_str = ''
for h in self._file_headers:
if h in record.keys():
record_str += record[h] if record_str == '' else f',{record[h]}'
else:
return ''
return(record_str + '\n')
def write_to_file(self, record):
try:
f = open(self._full_filepath, "a")
f.write(self._make_record_str(record))
f.close()
self._logger.info("Wrote record to dominant color file!")
return True
except Exception as e:
self._logger.error(f"Failed to write to dominant color file.\nException-\n{e}")
return False
def _get_dominant_color(self, image, k=4, image_processing_size = None):
"""
takes an image as input
returns the dominant color of the image as a list
dominant color is found by running k means on the
pixels & returning the centroid of the largest cluster
processing time is sped up by working with a smaller image;
this resizing can be done with the image_processing_size param
which takes a tuple of image dims as input
>>> get_dominant_color(my_image, k=4, image_processing_size = (25, 25))
[56.2423442, 34.0834233, 70.1234123]
"""
#resize image if new dims provided
if image_processing_size is not None:
image = cv2.resize(image, image_processing_size,
interpolation = cv2.INTER_AREA)
#reshape the image to be a list of pixels
image = image.reshape((image.shape[0] * image.shape[1], 3))
#cluster and assign labels to the pixels
clt = KMeans(n_clusters = k)
labels = clt.fit_predict(image)
#count labels to find most popular
label_counts = Counter(labels)
#subset out most popular centroid
dominant = list(clt.cluster_centers_[label_counts.most_common(1)[0][0]])
return dominant
def _check_results(self, dominant_color):
z_thresh = self._z_threshold
try:
df = pd.read_csv(self._full_filepath)
except pd.errors.EmptyDataError as e:
df = pd.DataFrame({'b': [float(dominant_color[0])], 'g': [float(dominant_color[1])], 'r':[float(dominant_color[2])]},index=['b', 'g', 'r'])
try:
b_z = np.abs(stats.zscore(np.append(df['b'],dominant_color[0])))
g_z = np.abs(stats.zscore(np.append(df['g'],dominant_color[1])))
r_z = np.abs(stats.zscore(np.append(df['r'],dominant_color[2])))
except Exception as e:
self._logger.error(f'Failed z-score caclulation on dominant color file data.\nException-\n{e}')
b_z = [100.0]
g_z = [100.0]
r_z = [100.0]
self._logger.warning("Blue z score: " + str(b_z[len(b_z) - 1]) + "; Green z score: " + str(g_z[len(g_z) - 1]) + "; Red z score: " + str(r_z[len(r_z) - 1]))
record = {
'b':str(dominant_color[0]),
'g':str(dominant_color[1]),
'r':str(dominant_color[2]),
'b_z':str(b_z[len(b_z) - 1]),
'g_z':str(g_z[len(g_z) - 1]),
'r_z':str(r_z[len(r_z) - 1]),
'z_thresh':str(z_thresh)
}
self.write_to_file(record)
if b_z[len(b_z) - 1] > z_thresh or g_z[len(g_z) - 1] > z_thresh or r_z[len(r_z) - 1] > z_thresh:
return True
return False<file_sep>arduino-cli compile --fqbn arduino:avr:uno arduino/three-ds/three-ds.ino
arduino-cli upload -p /dev/ttyACM$1 --fqbn arduino:avr:uno arduino/three-ds/three-ds.ino<file_sep>from flask import Flask, render_template, request
import pandas as pd
import numpy as np
import os
import cv2
from shiny_calc import calculate_chance
from viz import viz
import PokeVision as pv
app = Flask(__name__)
class PokeWeb():
def is_running():
stream = os.popen('./is_running.sh')
out = stream.read()
print(out)
if out is not None and out != "":
return ["Running...", out.split(' ')[3]]
return ["Not running!", "00:00:00"]
@app.route('/')
def index():
csv_filename = 'dominant_color.csv'
plot_filename = 'viz.png'
df = pd.read_csv(f'{app.static_folder}/{csv_filename}')
num_checks = int(df.count()[0])
output_obj = calculate_chance(1, 4096, num_checks)
is_run = is_running()
output_obj['is_running'] = is_run[0]
output_obj['cur_runtime'] = is_run[1]
output_obj['is_running_col'] = "lightgreen" if "Running" in is_run[0] else "crimson"
viz(app.static_folder, csv_filename, plot_filename)
return render_template('index.html', value=output_obj)
@app.route("/upload-complete", methods=["POST"])
def handle_upload_response():
"""This will be called after every upload, but we can ignore it"""
return "Success"
@app.route("/upload/<path_to_upload>", methods=["POST"])
def upload(path_to_upload):
io_file = request.files["media"]
contents = io_file.read()
if contents == b'':
return { 'statusCode': 405 }
jpg_as_np = np.frombuffer(contents, dtype=np.uint8)
img = cv2.imdecode(jpg_as_np, flags=1)
cv2.imwrite(f'{app.static_folder}/{path_to_upload}', img)
return { 'statusCode': 200 }
@app.route("/screen-check/<path_to_check>", methods=["GET"])
def screen_check_w_path(path_to_check):
cm = pv.PokeVision(base_path='/home/waklky/poke-bot',asset_folder='ultrasun_assets')
res = cm.is_battle_screen(f'{app.static_folder}/{path_to_check}')
return { 'statusCode': 200, 'response': res }
# No caching at all for API endpoints.
@app.after_request
def add_header(response):
response.cache_control.no_store = True
if 'Cache-Control' not in response.headers:
response.headers['Cache-Control'] = 'no-store'
return response
if __name__ == '__main__':
app.config.from_object('config')
# config file has STATIC_FOLDER='/core/static'
app.static_url_path=app.config.get('STATIC_FOLDER')
print(f"Current static folder: {app.static_url_path}")
print(f"Current static url path: {app.root_path}/..{app.static_url_path}")
app.static_folder=app.root_path + "/.." + app.static_url_path
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
app.run(host='0.0.0.0', debug=True)<file_sep>import requests
import time
class PokeVisionApi():
def __init__(self, domain='192.168.86.202', port=5000):
self._base_url = f"http://{domain}:{str(port)}"
def upload(self, in_filename, out_filename='upload.png'):
files = { 'media': open(in_filename, 'rb') }
return requests.post(f'{self._base_url}/upload/{out_filename}', files=files )
def check_screen(self, path_to_check='upload.png'):
r = requests.get(f'{self._base_url}/screen-check/{path_to_check}')
return r.json()['response'].get('battle_screen', {})
if __name__=="__main__":
s = time.time()
api = PokeVisionApi()
api.upload("/home/pi/Projects/poke-bot/test.jpg")
print(api.check_screen())
print(time.time() - s)<file_sep>raspistill -o $1<file_sep>ps -a -o cmd -o time | grep 'python3 poke-handler.py' | grep -v grep<file_sep>try:
from gamesystem.GameSystem import GameSystem
except:
from GameSystem import GameSystem
class ThreeDsComm(GameSystem):
def __init__(self, logger_name='ThreeDsComm'):
GameSystem.__init__(self, logger_name=logger_name)
self.TDS_COMMANDS = {
'a':'PRESS_A',
'b':'PRESS_B',
'x':'PRESS_X',
'y':'PRESS_Y',
'select':'PRESS_SEL',
'start':'PRESS_STA',
'r':'PRESS_R',
'l':'PRESS_L',
's_up':'STICK_UP',
's_down':'STICK_DOWN',
's_up_s':'STICK_UP_SMALL',
's_down_s':'STICK_DOWN_SMALL',
's_left':'STICK_LEFT',
's_right':'STICK_RIGHT',
'd_up':'PRESS_D_UP',
'd_down':'PRESS_D_DOWN',
'd_left':'PRESS_D_LEFT',
'd_right':'PRESS_D_RIGHT',
'sr':'SOFT_RESET',
'sel':'PRESS_SEL'
}
self.COMMANDS.update(self.TDS_COMMANDS)
def _send_three_ds_command(self, cmd, resp_timeout=1.0):
return self._send_game_system_command(cmd, resp_timeout)
<file_sep>#include <Servo.h>
class ThreeDsServo {
private:
int _pin_num;
public:
Servo _srvo;
int _start_pos;
int _end_pos;
bool _is_reverse;
ThreeDsServo(int pin, int start, int end, bool reverse) {
_is_reverse = reverse;
if(_is_reverse) {
_end_pos= start;
_start_pos = end;
} else {
_start_pos = start;
_end_pos = end;
}
_pin_num = pin;
}
void setup() {
_srvo.attach(_pin_num);
_srvo.write(_start_pos);
}
void move_servo(int from_pos, int to_pos, int delay_sec) {
int pos = 0;
if(from_pos < to_pos) {
for (pos = from_pos; pos <= to_pos; pos += 1) {
// in steps of 1 degree ( += 1 )
_srvo.write(pos); // tell servo to go to position in variable 'pos'
delay(delay_sec); // waits x ms for the servo to reach the position
}
} else {
for (pos = from_pos; pos >= to_pos; pos -= 1) {
// in steps of 1 degree ( += 1 )
_srvo.write(pos); // tell servo to go to position in variable 'pos'
delay(delay_sec); // waits x ms for the servo to reach the position
}
}
}
void tap_button_servo(int delay_sec=5) {
move_servo(_start_pos, _end_pos, delay_sec);
delay(1);
move_servo(_end_pos, _start_pos, delay_sec);
}
int get_start_pos() {
return _start_pos;
}
int get_end_pos() {
return _end_pos;
}
};
void led_on_off(bool on, int pin_num){
int out = LOW;
if(on){
out = HIGH;
}
digitalWrite(pin_num, out);
}
void flash_led(int pin_num, int num_flashes, int blink_time){
for(int i=0;i<num_flashes;i++){
digitalWrite(pin_num,HIGH);
delay(blink_time/2);
digitalWrite(pin_num,LOW);
delay(blink_time/2);
}
}
String recieve_serial_message() {
if (Serial.available() > 0) {
String data = Serial.readStringUntil('\n');
Serial.flush();
return data;
}
return "";
}
void send_serial_message(String msg) {
Serial.flush();
Serial.println(msg);
delay(1);
}
ThreeDsServo servo_a(7, 50, 75, false);
ThreeDsServo servo_l(10, 50, 90, true);
ThreeDsServo servo_r(9, 0, 30, false);
ThreeDsServo servo_select(6, 145, 122, false);
ThreeDsServo servo_up(12, 60, 95, true);
ThreeDsServo servo_down(5, 80, 125, false);
ThreeDsServo servo_d_left(11,80, 100, false);
ThreeDsServo servo_d_right(13, 67, 80, true);
// init on off switch pin
const int switch_pin = 3;
const int baud = 31250;
void setup() {
servo_a.setup();
servo_l.setup();
servo_r.setup();
servo_select.setup();
servo_up.setup();
servo_down.setup();
servo_d_left.setup();
servo_d_right.setup();
pinMode(LED_BUILTIN, OUTPUT);
pinMode(switch_pin, INPUT);
Serial.begin(baud);
Serial.flush();
}
void soft_reset() {
servo_r.move_servo(servo_r._start_pos, servo_r._end_pos, 1);
servo_l.move_servo(servo_l._start_pos, servo_l._end_pos, 1);
servo_select.move_servo(servo_select._start_pos, servo_select._end_pos, 1);
delay(1200);
servo_select.move_servo(servo_select._end_pos, servo_select._start_pos, 1);
servo_l.move_servo(servo_l._end_pos, servo_l._start_pos, 1);
servo_r.move_servo(servo_r._end_pos, servo_r._start_pos, 1);
}
void loop() {
// Only check serial comm if switch is on
if(digitalRead(switch_pin) == HIGH) {
// Check serial comms
String msg = recieve_serial_message();
if(msg=="PRESS_A") {
servo_a.tap_button_servo(5);
send_serial_message("PRESS_A_SUCC");
} else if(msg=="PRESS_R") {
servo_r.tap_button_servo();
send_serial_message("PRESS_R_SUCC");
} else if(msg=="PRESS_L") {
servo_l.tap_button_servo();
send_serial_message("PRESS_L_SUCC");
} else if(msg=="PRESS_SEL") {
servo_select.tap_button_servo();
send_serial_message("PRESS_SEL_SUCC");
} else if(msg=="STICK_UP") {
servo_up.move_servo(servo_up._start_pos, servo_up._end_pos, 1);
delay(1200);
servo_up.move_servo(servo_up._end_pos, servo_up._start_pos, 1);
send_serial_message("STICK_UP_SUCC");
} else if(msg=="STICK_DOWN") {
servo_down.move_servo(servo_down._start_pos, servo_down._end_pos, 1);
delay(1200);
servo_down.move_servo(servo_down._end_pos, servo_down._start_pos, 1);
send_serial_message("STICK_DOWN_SUCC");
} else if(msg=="STICK_UP_SMALL") {
servo_up.move_servo(servo_up._start_pos, servo_up._end_pos, 1);
delay(300);
servo_up.move_servo(servo_up._end_pos, servo_up._start_pos, 1);
send_serial_message("STICK_UP_SMALL_SUCC");
} else if(msg=="STICK_DOWN_SMALL") {
servo_down.move_servo(servo_down._start_pos, servo_down._end_pos, 1);
delay(300);
servo_down.move_servo(servo_down._end_pos, servo_down._start_pos, 1);
send_serial_message("STICK_DOWN_SMALL_SUCC");
} else if(msg=="PRESS_D_LEFT") {
servo_d_left.move_servo(servo_d_left._start_pos, servo_d_left._end_pos, 1.2);
delay(300);
servo_d_left.move_servo(servo_d_left._end_pos, servo_d_left._start_pos, 1.2);
send_serial_message("PRESS_D_LEFT_SUCC");
} else if(msg=="PRESS_D_RIGHT") {
servo_d_right.move_servo(servo_d_right._start_pos, servo_d_right._end_pos, 1.2);
delay(1200);
servo_d_right.move_servo(servo_d_right._end_pos, servo_d_right._start_pos, 1.2);
send_serial_message("PRESS_D_RIGHT_SUCC");
} else if(msg=="SOFT_RESET") {
soft_reset();
send_serial_message("SOFT_RESET_SUCC");
} else if(msg=="FLUSH_SER") {
Serial.flush();
send_serial_message("FLUSH_SER_SUCC");
}
} else {
Serial.flush();
}
} | 08b253f51c8f0ba52cd59f5397cc7aae2905c2be | [
"Python",
"C++",
"Shell"
] | 18 | Python | walkyd12/poke-bot | 8622a1bbc14ca1a4ced236e5f9e8bfa2f09cdfc5 | 9c35009e794851e9cf9c19e698c9b169de64e68a |
refs/heads/master | <file_sep>module StaticPagesHelper
def link_to_gravatar(email, size=150)
"http://www.gravatar.com/avatar/#{Digest::MD5.hexdigest(email)}?d=wavatar&s=#{size}"
end
end
<file_sep>require 'spec_helper'
describe "StaticPages" do
describe "Home page" do
before(:each) do
visit '/static_pages/home'
end
it "has correct title" do
page.should have_selector('title', text: 'Ruby Gardens :: Home')
end
it "has welcome content" do
page.should have_content('Welcome to Ruby Gardens Home')
end
end
describe "About page" do
before(:each) do
visit '/static_pages/about'
end
it "has correct title" do
page.should have_selector('title', text: 'Ruby Gardens :: About')
end
it "has about content" do
page.should have_content('About Ruby Gardens')
end
end
describe "About page" do
before(:each) do
visit who_we_are_path
end
it "has correct title" do
page.should have_selector('title', text: 'Ruby Gardens :: Who We Are')
end
it "has about content" do
page.should have_content('Who We Are')
end
end
end<file_sep>Admin.create({ nick: 'admin', password: '123'})
Participant.create([{ name: '<NAME>', email: '<EMAIL>' },
{ name: '<NAME>', email: '<EMAIL>' },
{ name: '<NAME>', email: '<EMAIL>' },
{ name: '<NAME>', email: '<EMAIL>' },
{ name: '<NAME>', email: '<EMAIL>' },
{ name: '<NAME>', email: '<EMAIL>' },
{ name: '<NAME>', email: '<EMAIL>' },
{ name: '<NAME>', email: '<EMAIL>' },
{ name: '<NAME>', email: '<EMAIL>' },
{ name: '<NAME>', email: '<EMAIL>' },
{ name: '<NAME>', email: '<EMAIL>' },
{ name: '<NAME>', email: '<EMAIL>' }])
<file_sep>class Admin < ActiveRecord::Base
attr_accessible :nick, :password
end
<file_sep>require 'spec_helper'
describe "ApplicationHelper" do
describe "#menu_links" do
it "has correct return value" do
expect(helper.menu_links({"tratata" => "/trololo"})).to have_selector('a', href: '/trololo')
end
end
end<file_sep>require "spec_helper"
describe 'Routing to StaticPagesController' do
it 'routes GET /who-we-are to #who_we_are' do
{get: '/who-we-are'}.should route_to('static_pages#who_we_are')
end
end<file_sep>class StaticPagesController < ApplicationController
def home
end
def about
end
def who_we_are
@participants = Participant.all
end
end
<file_sep>require 'spec_helper'
describe "StaticPagesHelper" do
describe "#link_to_gravatar" do
it "has correct return value" do
expect(helper.link_to_gravatar("<EMAIL>")).to match /http:\/\/www.gravatar.com\/avatar\/[a-z0-9]+\?d=wavatar&s=150/
end
end
end<file_sep>module ApplicationHelper
def menu_links(links={})
links.merge! 'Home' => home_path, 'Who We Are' => who_we_are_path, 'About' => about_path
links.map { |k,v| content_tag(:li, link_to(k, v))}.join.html_safe
end
end
| d411af56eda419adba56828f000f3d564ee5093f | [
"Ruby"
] | 9 | Ruby | simpl1g/static-pages | 23715a31c6e382e2e1a390caac205daa87ed9600 | 6bdb6b2920bad5419b1eb5dc83f70677829164ad |
refs/heads/master | <file_sep><?php
/**
* propertySets transport file for sharecontrol extra
*
* Copyright 2016 by <NAME> <http://stuntrocket.co>
* Created on 02-23-2016
*
* @package sharecontrol
* @subpackage build
*/
if (! function_exists('stripPhpTags')) {
function stripPhpTags($filename) {
$o = file_get_contents($filename);
$o = str_replace('<' . '?' . 'php', '', $o);
$o = str_replace('?>', '', $o);
$o = trim($o);
return $o;
}
}
/* @var $modx modX */
/* @var $sources array */
/* @var xPDOObject[] $propertySets */
$propertySets = array();
$propertySets[1] = $modx->newObject('modPropertySet');
$propertySets[1]->fromArray(array (
'id' => 1,
'name' => 'ShareControlPropertySet',
'description' => 'Description for ShareControlPropertySet',
'properties' => NULL,
), '', true, true);
return $propertySets;
<file_sep><?php
$cats = array (
0 => 'Sharecontrol',
);
return $cats;
| 0bf2d662a8ef2bc2f27905e117efa4f879f8475a | [
"PHP"
] | 2 | PHP | FolkSite/sharecontrol | c93fa6e19bc58a292664678b1cd1918444e54ada | 568d840c9124f8f77688f19c99984db576bb543e |
refs/heads/master | <repo_name>xiaoyuMo/spring-cloud-zookeeper<file_sep>/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/ZookeeperServerIntrospector.java
/*
* Copyright 2015-2019 the original author or authors.
*
* Licensed 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 org.springframework.cloud.zookeeper.discovery;
import java.util.Map;
import com.netflix.loadbalancer.Server;
import org.apache.curator.x.discovery.ServiceInstance;
import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector;
/**
* @author <NAME>
*/
public class ZookeeperServerIntrospector extends DefaultServerIntrospector {
@Override
public boolean isSecure(Server server) {
if (server instanceof ZookeeperServer) {
ZookeeperServer zookeeperServer = (ZookeeperServer) server;
Integer sslPort = zookeeperServer.getInstance().getSslPort();
return sslPort != null && sslPort > 0;
}
return super.isSecure(server);
}
@Override
public Map<String, String> getMetadata(Server server) {
if (server instanceof ZookeeperServer) {
ZookeeperServer zookeeperServer = (ZookeeperServer) server;
ServiceInstance<ZookeeperInstance> instance = zookeeperServer.getInstance();
if (instance != null && instance.getPayload() != null) {
return instance.getPayload().getMetadata();
}
}
return super.getMetadata(server);
}
}
<file_sep>/docs/src/main/asciidoc/intro.adoc
This project provides Zookeeper integrations for Spring Boot applications through
autoconfiguration and binding to the Spring Environment and other Spring programming model
idioms. With a few annotations, you can quickly enable and configure the common patterns
inside your application and build large distributed systems with Zookeeper based
components. The provided patterns include Service Discovery and Configuration. Integration
with Spring Cloud Netflix provides Intelligent Routing (Zuul), Client Side Load Balancing
(Ribbon), and Circuit Breaker (Hystrix).
<file_sep>/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependenciesBasedLoadBalancer.java
/*
* Copyright 2015-2019 the original author or authors.
*
* Licensed 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 org.springframework.cloud.zookeeper.discovery.dependency;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.DynamicServerListLoadBalancer;
import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import com.netflix.loadbalancer.RoundRobinRule;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ServerList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* LoadBalancer that delegates to other rules depending on the provided load balancing
* strategy in the {@link ZookeeperDependency#getLoadBalancerType()}.
*
* @author <NAME>
* @since 1.0.0
*/
public class DependenciesBasedLoadBalancer extends DynamicServerListLoadBalancer {
private static final Log log = LogFactory.getLog(DependenciesBasedLoadBalancer.class);
private final Map<String, IRule> ruleCache = new ConcurrentHashMap<>();
private final ZookeeperDependencies zookeeperDependencies;
public DependenciesBasedLoadBalancer(ZookeeperDependencies zookeeperDependencies,
ServerList<?> serverList, IClientConfig config, IPing iPing) {
super(config);
this.zookeeperDependencies = zookeeperDependencies;
setServersList(serverList.getInitialListOfServers());
setPing(iPing);
setServerListImpl(serverList);
}
@Override
public Server chooseServer(Object key) {
String keyAsString;
if ("default".equals(key)) { // this is the default hint, use name instead
keyAsString = getName();
}
else {
keyAsString = (String) key;
}
ZookeeperDependency dependency = this.zookeeperDependencies
.getDependencyForAlias(keyAsString);
log.debug(String.format("Current dependencies are [%s]",
this.zookeeperDependencies));
if (dependency == null) {
log.debug(String.format(
"No dependency found for alias [%s] - will use the default rule which is [%s]",
keyAsString, this.rule));
return this.rule.choose(key);
}
cacheEntryIfMissing(keyAsString, dependency);
log.debug(String.format(
"Will try to retrieve dependency for key [%s]. Current cache contents [%s]",
keyAsString, this.ruleCache));
updateListOfServers();
return this.ruleCache.get(keyAsString).choose(key);
}
private void cacheEntryIfMissing(String keyAsString, ZookeeperDependency dependency) {
if (!this.ruleCache.containsKey(keyAsString)) {
log.debug(String.format("Cache doesn't contain entry for [%s]", keyAsString));
this.ruleCache.put(keyAsString,
chooseRuleForLoadBalancerType(dependency.getLoadBalancerType()));
}
}
private IRule chooseRuleForLoadBalancerType(LoadBalancerType type) {
switch (type) {
case ROUND_ROBIN:
return getRoundRobinRule();
case RANDOM:
return getRandomRule();
case STICKY:
return getStickyRule();
default:
throw new IllegalArgumentException("Unknown load balancer type " + type);
}
}
private RoundRobinRule getRoundRobinRule() {
return new RoundRobinRule(this);
}
private IRule getRandomRule() {
RandomRule randomRule = new RandomRule();
randomRule.setLoadBalancer(this);
return randomRule;
}
private IRule getStickyRule() {
StickyRule stickyRule = new StickyRule(getRoundRobinRule());
stickyRule.setLoadBalancer(this);
return stickyRule;
}
}
<file_sep>/spring-cloud-zookeeper-core/src/test/java/org/springframework/cloud/zookeeper/ZookeeperAutoConfigurationEnsembleTests.java
/*
* Copyright 2015-2019 the original author or authors.
*
* Licensed 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 org.springframework.cloud.zookeeper;
import org.apache.curator.ensemble.EnsembleProvider;
import org.apache.curator.ensemble.fixed.FixedEnsembleProvider;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.test.TestingServer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author <NAME>
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {
ZookeeperAutoConfigurationEnsembleTests.TestConfig.class,
ZookeeperAutoConfiguration.class })
public class ZookeeperAutoConfigurationEnsembleTests {
@Autowired(required = false)
CuratorFramework curator;
@Autowired
TestingServer testingServer;
@Test
public void should_successfully_inject_Curator_with_ensemble_connection_string() {
assertThat(curator.getZookeeperClient().getCurrentConnectionString())
.isEqualTo(testingServer.getConnectString());
assertThat(curator.getZookeeperClient().getCurrentConnectionString())
.isNotEqualTo(TestConfig.DUMMY_CONNECTION_STRING);
}
static class TestConfig {
static final String DUMMY_CONNECTION_STRING = "dummy-connection-string:2111";
@Bean
EnsembleProvider ensembleProvider(TestingServer testingServer) {
return new FixedEnsembleProvider(testingServer.getConnectString());
}
@Bean
ZookeeperProperties zookeeperProperties() {
ZookeeperProperties properties = new ZookeeperProperties();
properties.setConnectString(DUMMY_CONNECTION_STRING);
return properties;
}
@Bean(destroyMethod = "close")
TestingServer testingServer() throws Exception {
return new TestingServer();
}
}
}
<file_sep>/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyRibbonAutoConfiguration.java
/*
* Copyright 2015-2019 the original author or authors.
*
* Licensed 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 org.springframework.cloud.zookeeper.discovery.dependency;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.cloud.zookeeper.ConditionalOnZookeeperEnabled;
import org.springframework.cloud.zookeeper.discovery.ConditionalOnRibbonZookeeper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
*
* Provides LoadBalancerClient that at runtime can pick proper load balancing strategy
* basing on the Zookeeper dependencies from properties.
*
* @author <NAME>
* @since 1.0.0
*/
@Configuration
@ConditionalOnZookeeperEnabled
@ConditionalOnRibbonZookeeper
@ConditionalOnDependenciesPassed
@AutoConfigureBefore(RibbonAutoConfiguration.class)
public class DependencyRibbonAutoConfiguration {
private static final Log log = LogFactory
.getLog(DependencyRibbonAutoConfiguration.class);
@Autowired
ApplicationContext applicationContext;
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(value = "spring.cloud.zookeeper.dependency.ribbon.enabled", matchIfMissing = true)
public LoadBalancerClient loadBalancerClient(
SpringClientFactory springClientFactory) {
return new RibbonLoadBalancerClient(springClientFactory) {
@Override
protected Server getServer(String serviceId) {
ILoadBalancer loadBalancer = this.getLoadBalancer(serviceId);
return loadBalancer == null ? null
: chooseServerByServiceIdOrDefault(loadBalancer, serviceId);
}
private Server chooseServerByServiceIdOrDefault(ILoadBalancer loadBalancer,
String serviceId) {
log.debug(String.format(
"Dependencies are set - will try to load balance via provided load balancer [%s] for key [%s]",
loadBalancer, serviceId));
Server server = loadBalancer.chooseServer(serviceId);
log.debug(
String.format("Retrieved server [%s] via load balancer", server));
return server != null ? server : loadBalancer.chooseServer("default");
}
};
}
}
<file_sep>/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/StickyRule.java
/*
* Copyright 2015-2019 the original author or authors.
*
* Licensed 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 org.springframework.cloud.zookeeper.discovery.dependency;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Load balancing rule that returns always the same instance.
*
* Ported from {@code org.apache.curator.x.discovery.strategies.StickyStrategy}
*
* @author <NAME>
* @since 1.0.0
*/
public class StickyRule extends AbstractLoadBalancerRule {
private static final Log log = LogFactory.getLog(StickyRule.class);
private final IRule masterStrategy;
private final AtomicReference<Server> ourInstance = new AtomicReference<>(null);
private final AtomicInteger instanceNumber = new AtomicInteger(-1);
public StickyRule(IRule masterStrategy) {
this.masterStrategy = masterStrategy;
}
@Override
public void initWithNiwsConfig(IClientConfig iClientConfig) {
}
@Override
public Server choose(Object key) {
final List<Server> instances = getLoadBalancer().getServerList(true);
log.debug(String.format("Instances taken from load balancer [%s]", instances));
Server localOurInstance = this.ourInstance.get();
log.debug(String.format("Current saved instance [%s]", localOurInstance));
if (!instances.contains(localOurInstance)) {
this.ourInstance.compareAndSet(localOurInstance, null);
}
if (this.ourInstance.get() == null) {
Server instance = this.masterStrategy.choose(key);
if (this.ourInstance.compareAndSet(null, instance)) {
this.instanceNumber.incrementAndGet();
}
}
return this.ourInstance.get();
}
/**
* Each time a new instance is picked, an internal counter is incremented. This way
* you can track when/if the instance changes. The instance can change when the
* selected instance is not in the current list of instances returned by the instance
* provider
* @return instance number
*/
public int getInstanceNumber() {
return this.instanceNumber.get();
}
}
| a8e697597d811c0571bbcc03c6cf3fe6dafa13fb | [
"Java",
"AsciiDoc"
] | 6 | Java | xiaoyuMo/spring-cloud-zookeeper | 8504b7a524d38f4be502e2950c2f97a86df81e05 | af0edf9586776e359b86a13b1a6982c33f576ab5 |
refs/heads/master | <file_sep>#ifndef TERMINAL_H
#define TERMINAL_H
#include <QDialog>
#include <QTextEdit>
#include <QPushButton>
#include <QLineEdit>
#include <QGridLayout>
#include <QtSerialPort/QSerialPort>
#include <QTextStream>
#include <QObject>
#include <QTimer>
#include <QString>
#include <QByteArray>
#include <QLabel>
#include <QtSerialPort/QSerialPort>
#include <QTextStream>
#include <QTimer>
#include <QByteArray>
#include <QObject>
#include <QComboBox>
QT_USE_NAMESPACE
QT_BEGIN_NAMESPACE
QT_END_NAMESPACE
class terminal : public QDialog
{
Q_OBJECT
public:
terminal(QSerialPort *serial_port, QWidget *parent = 0);
~terminal();
int writeText(const QByteArray &array);
void showBtn();
void setSerialPortName(QString &portName);
public slots:
void configSerialPort();
void disconnectSerialPort();
void showText();
void baudRateComboIndexChanged(int);
void serialPortNameComboIndexChanged(int);
private:
QPushButton *connectBtn;
QPushButton *disconnectBtn;
QComboBox *baudRateCombo;
QComboBox *serialPortNameCombo;
QSerialPort *port;
qint64 baudRate;
QString portName;
qint8 baudRateIsSet;
qint8 serialPortNameIsSet;
QByteArray writeData;
QTextStream standardOutput;
QLabel *baudRateLabel;
QLabel *serialPortNameLabel;
QTextEdit *text;
};
#endif // TERMINAL_H
<file_sep>#include "terminal.h"
#include <QCoreApplication>
#include <QApplication>
#include <QRegExp>
#include <QtSerialPort/QSerialPort>
#include <QObject>
QT_USE_NAMESPACE
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTextStream standardOutput(stdout);
QSerialPort serial_port;
terminal w(&serial_port);
w.show();
return a.exec();
}
<file_sep>#include "terminal.h"
#include <QRegExpValidator>
#include <QMessageBox>
#include <QColor>
terminal::terminal(QSerialPort *serial_port, QWidget *parent)
: QDialog(parent),
port(serial_port),
standardOutput(stdout)
{
baudRateIsSet = 0;
serialPortNameIsSet = 0;
QGridLayout *mainLayout = new QGridLayout(this);
baudRateLabel = new QLabel(tr("Baud Rate"),this);
baudRateCombo = new QComboBox;
baudRateCombo->insertItem(0,"115200");
baudRateCombo->insertItem(0,"38400");
baudRateCombo->insertItem(0,"9600");
serialPortNameLabel = new QLabel(tr("serial Port Name"),this);
serialPortNameCombo = new QComboBox;
serialPortNameCombo->insertItem(0,"ttyUSB0");
serialPortNameCombo->insertItem(0,"ttyUSB1");
connectBtn = new QPushButton(tr("connect"),this);
disconnectBtn = new QPushButton(tr("disconnect"),this);
disconnectBtn->hide();
//connectBtn->hide();
text = new QTextEdit();
text->setReadOnly(true);
//text->setTextBackgroundColor(QColor(0,0,255,127));
mainLayout->addWidget(serialPortNameLabel,0,0);
mainLayout->addWidget(serialPortNameCombo,0,1);
mainLayout->addWidget(baudRateLabel,1,0);
mainLayout->addWidget(baudRateCombo,1,1);
mainLayout->addWidget(connectBtn,0,2);
mainLayout->addWidget(disconnectBtn,1,2);
mainLayout->addWidget(text,2,0,2,3);
resize(600,450);
connect(connectBtn,SIGNAL(clicked()),this, SLOT(configSerialPort()));
connect(disconnectBtn,SIGNAL(clicked()),this, SLOT(disconnectSerialPort()));
connect(port,SIGNAL(readyRead()),this,SLOT(showText()));
connect(baudRateCombo,SIGNAL(currentIndexChanged(int)),this,\
SLOT(baudRateComboIndexChanged(int)));
connect(serialPortNameCombo,SIGNAL(currentIndexChanged(int)),this,\
SLOT(serialPortNameComboIndexChanged(int)));
// connect(text,SIGNAL())
//connect(baudRateLine,SIGNAL(activated(int)), this, SLOT(showBtn()));
/*
* QRegExp regExpNameLine = "[A-Z]{0,6}[0-9]+";
* QRegExp regExpbaudRateLine = "[0-9]*";
* baudRateLine->setValidator(new QRegExpValidator(regExpNameLine, this));
* baudRateLine->setValidator(new QRegExpValidator(regExpbaudRateLine, this));
*/
}
terminal::~terminal()
{
}
void terminal::configSerialPort()
{
if(serialPortNameIsSet == 0)
{
portName = serialPortNameCombo->itemText(serialPortNameCombo->count()-1);
//standardOutput<<"port name :"<<portName << endl;
}
if(baudRateIsSet == 0)
{
baudRate = baudRateCombo->itemText(baudRateCombo->count()-1).toInt();
//standardOutput<<"baud rate :"<<baudRate << endl;
}
port->setBaudRate(baudRate);
port->setPortName(portName);
if (!port->open(QIODevice::ReadOnly)) {
standardOutput << QObject::tr("Failed to open port %1, error: %2")\
.arg(portName).\
arg(port->error())\
<< endl;
return;
}
disconnectBtn->show();
standardOutput << "+--------------------------+" << endl;
standardOutput << "+ serial port is alive." << endl;
standardOutput<<"+ baud: "<< baudRate << endl;
standardOutput<<"+ port: "<< portName << endl;
standardOutput << "+--------------------------+" << endl;
}
void terminal::disconnectSerialPort()
{
port->close();
disconnectBtn->hide();
standardOutput << "+--------------------------+" << endl;
standardOutput << "+ serial port is closed" << endl;
standardOutput << "+--------------------------+" << endl;
}
void terminal::showBtn()
{
}
void terminal::showText()
{
QByteArray str;
text->moveCursor(QTextCursor::End,QTextCursor::MoveAnchor);
str = port->readAll();
text->insertPlainText(str);
text->moveCursor(QTextCursor::End,QTextCursor::MoveAnchor);
}
void terminal::baudRateComboIndexChanged(int index)
{
baudRate = baudRateCombo->itemText(index).toInt();
/* QMessageBox::information(this,tr("baudRate Changed"), \
tr("baudRate:%1").arg(baudRate));
*/
baudRateIsSet = 1;
}
void terminal::serialPortNameComboIndexChanged(int index)
{
portName = serialPortNameCombo->itemText(index);
/* QMessageBox::information(this,tr("serialPortName Changed"), \
tr("serialPortName:%1").arg(portName));
*/
serialPortNameIsSet = 1;
}
<file_sep>qt_serial_com_interface
=======================
Users who use this App can receive data from COM port and display them on one textEdit. But this version can't be used for interacting with the COM.
| dbbdc83af09f384fd1494df7154b592b6ac6b9c5 | [
"Markdown",
"C++"
] | 4 | C++ | eastmoutain/qt_serial_com_interface | f81c66fc5bf5bfebdf812c2cca89ad7cb8549fc1 | 57d0f0b86c7fbddff241186b956ae4273776b823 |
refs/heads/master | <repo_name>rdcarter24/WebApp<file_sep>/webapp.py
from flask import Flask, render_template, request
import hackbright_app
app = Flask(__name__)
@app.route("/")
def get_github():
return render_template("get_github.html")
@app.route("/student")
def get_student():
hackbright_app.connect_to_db()
student_github = request.args.get("student_github")
if request.args.get("grade"):
project = request.args.get("project_title")
grade = request.args.get("grade")
enter_grade = hackbright_app.make_new_grade(student_github, project, grade)
row = hackbright_app.get_student_by_github(student_github)
grades = hackbright_app.get_student_grades(student_github)
if row is None:
html = render_template("student_info.html", first_name="You", last_name="Boo",
student_github="No", grade_list=[])
else:
html = render_template("student_info.html", first_name=row[0], last_name=row[1],
student_github=row[2], grade_list=grades)
return html
@app.route("/project")
def get_project_info():
hackbright_app.connect_to_db()
project = request.args.get("project")
row = hackbright_app.get_grades_by_project(project)
html = render_template("project_info.html", project_list=row)
return html
@app.route("/create_new_student")
def create_new_student():
return render_template("create_new_student.html")
@app.route("/new_student")
def new_student():
hackbright_app.connect_to_db()
first_name = request.args.get("first_name")
last_name = request.args.get("last_name")
github = request.args.get("github")
create = hackbright_app.make_new_student(first_name, last_name, github)
row = hackbright_app.get_student_by_github(github)
html = render_template("new_student.html", first_name=row[0], last_name=row[1],
github=row[2])
return html
@app.route("/create_new_project")
def create_new_project():
return render_template("create_new_project.html")
@app.route("/new_project")
def new_project():
hackbright_app.connect_to_db()
# all args need to be sent together
title = request.args.get("title")
description = request.args.get("description")
grade = request.args.get("number")
create = hackbright_app.make_new_project(title, description, grade)
row = hackbright_app.get_project_by_title(title)
html = render_template("new_project.html", title=row[0], description=row[1],
max_grade=row[2])
return html
@app.route("/enter_student_grade")
def create_student_grade():
return render_template("enter_student_grade.html")
if __name__ == "__main__":
app.run(debug=True) | 60e9376e83154d692dccb1fbfb0b1e4bd1f6b793 | [
"Python"
] | 1 | Python | rdcarter24/WebApp | 7b67cd35719a272319211d8dab6de41764d9a87b | 1fa03346eaac640adfb181c33e4bbd8885a47a3d |
refs/heads/master | <repo_name>AlbanoBorba/video_exposition<file_sep>/dataloader.py
from __future__ import print_function, division
import os
import sys
import numpy as np
import pandas as pd
import torch
import random
import cv2
import time
import datetime
from scipy import ndimage, misc
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
def transforms_list():
return [
#transforms.ToPILImage(),
transforms.Resize((400, 720)),
transforms.CenterCrop((400, 400)),
transforms.ToTensor(),
#transforms.Lambda(lambda x: rescale(x)),
transforms.Normalize(mean=(0.279, 0.293, 0.290), std=(0.197, 0.198, 0.201))
#transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
]
def custom_collate(batch):
data = torch.stack([item['x'] for item in batch], dim=0)
target = torch.stack([item['y'] for item in batch], dim=0)
return {'x':data, 'y':target}
class BddDaloaderFactory():
def __init__(self, csv_path, exposure, batch_size, n_samples=40, window_size=3):
if exposure == 'under':
self.gamma = [0.1, 0.2, 0.4]
elif exposure == 'over':
self.gamma = [2.5, 5, 10]
else:
sys.exit("O tipo de exposiçao deve ser 'under' ou 'over'!")
self.batch_size = batch_size
self.n_samples = n_samples
self.windo_size = window_size
self.video_loader = pd.read_csv(csv_path)
def __len__(self):
return len(video_loader.index)
def __getitem__(self):
random_video = video_loader.sample(n=1)
video_path = random_video['video_path'].tolist()[0] # str
dataset = SingleVideoDataset(video_path, self.n_samples, self.window_size, random.choice(self.gamma))
dataloader = DataLoader(dataset=dataset,
batch_size=self.batch_size,
num_workers=0,
collate_fn=custom_collate)
return dataloader
class SingleVideoDataset(Dataset):
def __init__(self, video_path, n_samples, window_size, gamma, transform=transforms.Compose(transforms_list())):
self.sample_loader = SampleLoader(video_path, window_size)
self.n_samples = n_samples
self.gamma = gamma
self.transform = transform
def __len__(self):
return self.n_samples
# Enumerate call
def __getitem__(self, idx):
# Get window_size frames
frames = self.sample_loader.get_sample()
# Preprocess ground-truth
frame_gt = frames[int(len(frames)/2)]
#frame_gt = ndimage.rotate(frame_gt, 90, reshape=True)
frame_gt = transforms.functional.to_pil_image(frame_gt)
frame_gt = self.transform(frame_gt)
# Preprocess window
stack = []
for frame in frames:
frame = self.change_gamma(frame, self.gamma)
frame = self.transform(frame)
stack.append(frame)
stack = torch.stack(stack, dim=0)
# Set sampleW
sample = {
'x': window,
'y': frame_gt
}
return sample
def change_gamma(self, f, gamma):
f = transforms.functional.to_pil_image(f)
f = transforms.functional.adjust_gamma(f, gamma, gain=1)
return f
class SampleLoader():
def __init__(self, video_path, window_size):
self.cap = cv2.VideoCapture(video_path)
self.window_size = window_size
self.index = 0
self.frames = []
def get_sample(self):
if self.index == 0:
for i in range(self.window_size):
_, frame = self.cap.read()
self.frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
self.index = 1
else:
self.frames.pop(0)
_, frame = self.cap.read()
self.frames.append(frame)
return self.frames<file_sep>/utils/val_model.py
# Libs import
import numpy as np
import torch
import torch.nn as nn
from torchvision import transforms, utils
# My imports
from models import UNet3D
from dataloader import BddDaloaderFactory
from train import train_model, test_model
from loss import LossFunction
from utils import log
# Hiperparameters and configurations
RUN_NAME = ''
BATCH_SIZE = 8
VAL_FILE_PATH = ''
MODEL_STATE_PATH = ''
EXPOSURE = 'under'
# Set dataloaders
val_loader = BddDaloaderFactory(EXPOSURE, TRAIN_FILE_PATH, BATCH_SIZE)
# Set model and lod weights
model = UNet3D(3, 3).to(device)
model.load_state_dict(torch.load(MODEL))
# Set optimizer
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
#optimizer = torch.optim.Adam(model.parameters())
# Set criterion
criterion = LossFunction().to(device)
val_loss = []
# Iterate over videos.
for video_step, video_loader in enumerate(val_loader):
# Iterate over frames.
for sample_step, sample in enumerate(video_loader):
# Send data to device
y, x = sample['y'].to(device), sample['x'].to(device)
# Test model with sample
loss = test_model(model, {'x': x, 'y': y}, criterion, optimizer)
test_loss.append(loss)
if sample_step == 0:
#log.log_images(x, y,'<PATH>/{}_'.format(n_samples))
# Logs after test
log.log_time('Total Loss: {:.6f}\tAvg Loss: {:.6f}'
.format(np.sum(test_loss), np.average(test_loss)))
<file_sep>/data_utils/video_map.py
import os
import numpy as np
from skimage import io, transform
import cv2
import matplotlib.pyplot as plt
def read_video(video_path, frames=40):
cap = cv2.VideoCapture(video_path)
global file
count = 0
x = []
while True:
ret, frame = cap.read()
if ret:
x.append(np.average(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)))
if cv2.waitKey(1) & 0xFF == ord('q'):
break
count += 1
if count == n_frames: break
else:
break
file.write(str(np.average(x))+'\t'+str(np.std(x))+'\n')
cap.release()
cv2.destroyAllWindows()
def read_image(path):
img = io.imread(path)
medians.append(np.median(img))
file = open("histogram_distrib/all_distrib_40f.txt", "w")
if __name__ == '__main__':
path = '/media/albano/external'
#path = './'
for root, dirs, files in os.walk(path):
for f in files:
if f.endswith('.mov'):
read_video(os.path.join(root,f))<file_sep>/run.py
# Libs import
import numpy as np
import torch
import torch.nn as nn
from torchvision import transforms, utils
# My imports
from models import UNet3D
from dataloader import BddDaloaderFactory
from train import train_model, test_model
from loss import LossFunction
from utils import log
# Hiperparameters and configurations
RUN_NAME = ''
SEED = 12
BATCH_SIZE = 8
EPOCHS = 100
TRAIN_FILE_PATH = 'data_utils/bdd_day[90-110]_train_5k_40.csv'
TEST_FILE_PATH = ''
EXPOSURE = 'under'
TEST_INTERVAL = 500 #video unit
CHECKPOINT_INTERVAL = 500 #video unit
# Set host or device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
#torch.cuda.empty_cache()
# Set seeds
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
# Set dataloaders
train_loader = BddDaloaderFactory(EXPOSURE, TRAIN_FILE_PATH, BATCH_SIZE)
test_loader = BddDaloaderFactory(EXPOSURE, TEST_FILE_PATH, BATCH_SIZE)
# Set model
model = UNet3D(3, 3).to(device)
# Set optimizer
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
#optimizer = torch.optim.Adam(model.parameters())
# Set criterion
criterion = LossFunction().to(device)
# Log model configurations
#log.log_model_eval(model)
#log.log_model_params(model)
n_samples = 0
for epoch in range(num_epochs):
log.log_time('Epoch {}/{}'.format(epoch, num_epochs - 1))
# Iterate over videos.
for video_step, video_loader in enumerate(train_loader):
video_loss = []
# Iterate over frames.
for _, sample in enumerate(video_loader):
n_samples += 1
# Send data to device
y, x = sample['y'].to(device), sample['x'].to(device)
# Train model with sample
loss = train_model(model, {'x':x, 'y':y}, criterion, optimizer)
video_loss.append(loss)
# Logs per video
log.log_time('Video: {}\tTotal Loss: {:.6f}\tAvg Loss: {:.6f}'
.format(n_samples, np.sum(video_loss), np.average(video_loss)))
# Test model
# NOTE: len(train_loader) must be >> len(test_loader)
if video_step % TEST_INTERVAL == 0:
test_loss = []
# Iterate over videos.
for video_step, video_loader in enumerate(test_loader):
# Iterate over frames.
for _, sample in enumerate(video_loader):
# Send data to device
y, x = sample['y'].to(device), sample['x'].to(device)
# Test model with sample
loss = test_model(model, {'x':x, 'y':y}, criterion, optimizer)
test_loss.append(loss)
#log.log_images(x, y,'<PATH>/{}_'.format(n_samples))
# Logs after test
log.log_time('Test: {}\tTotal Loss: {:.6f}\tAvg Loss: {:.6f}'
.format(n_samples, np.sum(test_loss), np.average(test_loss)))
# Checkpoint
if video_step % TEST_INTERVAL == 0:
torch.save(model.state_dict(), './results/{}/3dcnn_weigths_{}_{}.pth'.format(RUN_NAME, epoch, video_step))<file_sep>/data_utils/synthetic_frame.py
import os
import cv2
import numpy as np
def getPath(path):
#path = './a/b'
path = path.split('/')
folder = path.pop(-1)
path = '/'.join(path)
if path != '':
path = path + '/'
return path, folder
def under(rgb, percent):
rgb = rgb/255.
rgb = saturate(rgb, [np.percentile(rgb, percent),1.])*255
return (rgb).astype(np.uint8)
def over(rgb, percent):
rgb = rgb/255.
rgb = saturate(rgb, [0.,np.percentile(rgb, percent)])*255
return (rgb).astype(np.uint8)
def saturate(rgb, threshold = [0, .6]):
rgb_clipped = np.clip(rgb, threshold[0], threshold[1])
rgb_clipped = rgb_clipped - np.min(rgb_clipped)
rgb_clipped = rgb_clipped / np.max(rgb_clipped)
return rgb_clipped
def process(path, threshold=25, exposure='over under', out_ext='jpg'):
# get name files in path
files = [file for file in sorted(os.listdir(path)) if file.split('.')[-1] == out_ext]
# get np frames by opencv
frames = [cv2.imread(path+'/'+file) for file in files]
# get under and over exposures for each frame
if 'under' in exposure:
under_results = [under(frame, threshold) for frame in frames]
if 'over' in exposure:
over_results = [over(frame, 100-threshold) for frame in frames]
# set save path
path, folder = getPath(path)
if 'under' in exposure:
save_path = path+'/'+folder+'_under'
os.mkdir(save_path)
# save new frames
for result in under_results:
file_name = str(under_results.index(result))+'.'+out_ext
cv2.imwrite(save_path+'/'+file_name,result)
if 'over' in exposure:
save_path = path+'/'+folder+'_over'
os.mkdir(save_path)
# save new frames
for result in over_results:
file_name = str(over_results.index(result))+'.'+out_ext
cv2.imwrite(save_path+'/'+file_name,result)
if __name__ == '__main__':
path = "./bdd_test/00"
process(path)<file_sep>/data_utils/join_frames.py
import os
import cv2
def joinFrames(path, name, ext='jpg', fps=19.0):
files = [file for file in sorted(os.listdir(path)) if file.split('.')[-1] == ext]
frames = [cv2.imread(path+'/'+file) for file in files]
fourcc = 0 # no compression
#fourcc = 0x7634706d # mp4
#fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
width = frames[0].shape[1]
height = frames[0].shape[0]
fps = fps
out_writer = cv2.VideoWriter(path+'/'+name, fourcc, fps, (width, height))
for frame in frames:
out_writer.write(frame)
out_writer.release()
if __name__ == '__main__':
joinFrames('./bdd_test/00', 'out.avi')<file_sep>/data_utils/histogram_distrib/plot_distrib.py
import matplotlib.pyplot as plt
import numpy as np
f = open('all_distrib.txt', "r")
means = f.read().split('\n')
n = len(means)
means = [float(x) for x in means]
plt.hist(means, color = 'blue', edgecolor = 'black', bins = 50)
plt.title('Luminanica de todos os vídeos')
plt.xlabel('Intensidade média dos pixels')
plt.ylabel('Número de vídeos')
plt.xticks(np.arange(0, 255, 25))
plt.show()<file_sep>/loss.py
import torch
import torch.nn as nn
from loss_utils.vgg import Vgg16
class LossFunction(nn.Module):
def __init__(self, weight=1):
super().__init__()
#self.weight = weight
#self.vgg = Vgg16(requires_grad=False)
self.mse = nn.MSELoss()
def forward(self, x, y):
#print('*'*10)
#print(x.shape)
#print(y.shape)
loss_mse = self.mse(x, y)
#x_vgg = self.vgg(x)
#y_vgg = self.vgg(y)
#print(x_vgg.relu2_2.shape)
#print(y_vgg.relu2_2.shape)
#loss_vgg = self.mse(x_vgg.relu2_2, y_vgg.relu2_2)
#loss = loss_mse + loss_vgg #ajustar
return loss_mse<file_sep>/data_utils/concat_videos.py
import os
import cv2
import numpy as np
def getPath(path):
#path = './a/b'
path = path.split('/')
folder = path.pop(-1)
path = '/'.join(path)
if path != '':
path = path + '/'
return path
def concat(paths, out_path, out_ext='avi'):
# Read videos
caps = []
for path in paths:
caps.append(cv2.VideoCapture(path))
# Count videos
w = h = 1
if len(caps) == 2:
w += 1
elif len(caps) == 3:
w += 2
elif len(caps) == 4:
w += 1
h += 1
elif len(caps) == 6:
w += 2
h += 2
else:
print("Invalid number of videos")
# Set fourcc
fourcc = 0
# Get video properties
fps = 10.0
width = int(caps[0].get(cv2.CAP_PROP_FRAME_WIDTH)) * w
height = int(caps[0].get(cv2.CAP_PROP_FRAME_HEIGHT)) * h
# Get all frames
frames = []
for cap in caps:
print('Video')
aux = []
while cap.isOpened():
ret, frame = cap.read()
if ret:
aux.append(frame)
else:
break
cap.release()
frames.append(aux)
# Concatenate
concat = []
if w == 2:
# concat 1 e 2
aux = []
for a,b in zip(frames[0], frames[1]):
aux.append(np.concatenate((a,b), axis=1))
if h == 2:
# concat 3 e 4
aux2 = []
for a,b in zip(frames[2], frames[3]):
aux2.append(np.concatenate((a,b), axis=1))
# concat (1,2) e (3,4)
for a,b in zip(aux, aux2):
concat.append(np.concatenate((a,b), axis=0))
else:
concat = aux
elif w == 3:
# concat 1, 2 e 3
aux = []
for a,b,c in zip(frames[0], frames[1], frames[2]):
aux.append(np.concatenate((a,b,c), axis=1))
if h == 3:
# concat 4, 5 e 6
aux2 = []
for a,b,c in zip(frames[3], frames[4], frames[5]):
aux2.append(np.concatenate((a,b,c), axis=1))
# concat (1,2,3) e (4,5,6)
for a,b in zip(aux, aux2):
concat.append(np.concatenate((a,b), axis=0))
else:
concat = aux
# Writer object
#path = getPath(path[0])
out = cv2.VideoWriter('{}/concat.{}'.format(out_path, out_ext), fourcc, fps, (width, height))
# Write video
for c in concat:
out.write(c)
out.release()
if __name__ == '__main__':
#path = './bdd_mini/train/08'
#concat([path+'/08_under/out.avi',path+'/08_under_ucan_under/out.avi', path+'/08_over/out.avi', path+'/08_over_ucan_over/out.avi'], path)
#path = './bdd_mini/test/05'
#concat([path+'/out.avi',path+'/05_ucan_over/out.avi'], path)
path = './bdd_mini/test/tinhosa'
concat([path+'/out.avi', path+'/tinhosa_ucan_under/out.avi'], path)
<file_sep>/utils/log.py
from torchvision import utils
def log_time(msg):
print(msg)
print('\t', end='')
print('Datetime: {}'.format(datetime.datetime.now()), end='\n')
def log_images(x, y, path):
utils.save_image(x, path+'x.png')
utils.save_image(y, path+'y.png')
def log_model_eval(model):
print('Model evaluation: ', model.eval())
def log_model_params(model):
model_parameters = filter(lambda p: p.requires_grad, model.parameters())
params = sum([np.prod(p.size()) for p in model_parameters])
print('Model trainable parameters: ', params)
| 71e92212314b48e40e33e51992e244a1d4897a75 | [
"Python"
] | 10 | Python | AlbanoBorba/video_exposition | 58de798954823473373a69f96930dfee1502b6df | 290ba6068945c6c735ed67af869184eb9289ab88 |
refs/heads/main | <repo_name>fancibleunicorn/weather-dashboard<file_sep>/assets/script.js
//API Key a877d2c6ed19aff0fd1776e7df46844f
//Show Current Weather (city name, the date, an icon representation of weather conditions, the temperature, the humidity, the wind speed, and the UV index)
var findCurrentWeather = function(city) {
//current weather by city
var apiCurrentUrl = "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=imperial&appid=a877d2c6ed19aff0fd1776e7df46844f"
fetch(apiCurrentUrl).then(function(response) {
return response.json();
})
.then(function(data){
//Current City
var currentCity = data.name;
$("#current-city").empty().append(currentCity);
// Current Date
var currentDate = moment().format(' (M/DD/YYYY)')
$("#current-city").append(currentDate);
// Current Icon
var iconCode = data.weather[0].icon
var icon = "http://openweathermap.org/img/wn/" + iconCode + "@2x.png"
$("#current-icon").attr('src', icon);
// Current Temp
var currentTemp = data.main.temp
$("#current-temp").empty().append('Temperature: ' + currentTemp +' °F')
//Current Humidity
var currentHumid = data.main.humidity
$("#current-humidity").empty().append('Humidity: ' + currentHumid + "%")
//Current Windspeed
var currentWind = data.wind.speed
$("#current-wind").empty().append('Wind Speed: ' + currentWind +" mph")
//Current Latitude
var currentLat = data.coord.lat
//Current Longitude
var currentLon = data.coord.lon
// Display Current UV Index
findCurrentUvi(currentLat, currentLon);
//Show 5-day forecast (date, an icon representation of weather conditions, the temperature, and the humidity)
var fiveDayWeather = function(lat, lon) {
var apiFiveUrl = "https://api.openweathermap.org/data/2.5/onecall?lat=" + lat + "&lon=" + lon + "&units=imperial&exclude=current,minutely,hourly,alerts&appid=a877d2c6ed19aff0fd1776e7df46844f"
fetch(apiFiveUrl).then(function(response){
return response.json();
})
.then(function(data) {
//Day 1
// 5 Day Date
var currentDate = moment().add(1, 'days').format('M/DD/YYYY');
$("#5-day-date-1").empty().append(currentDate);
// 5 Day Icons
var iconCode = data.daily[0].weather[0].icon
var icon = "http://openweathermap.org/img/wn/" + iconCode + "@2x.png"
$("#5-day-icon-1").attr("src", icon);
// 5 Day Temperature
var currentTemp = data.daily[0].temp.day
$("#5-day-temp-1").empty().append('Temp: ' + currentTemp +' °F')
// 5 Day Humidity
var currentHumid = data.daily[0].humidity
$("#5-day-humid-1").empty().append('Humidity: ' + currentHumid + "%")
//Day 2
// 5 Day Date
var currentDate = moment().add(2, 'days').format('M/DD/YYYY');
$("#5-day-date-2").empty().append(currentDate);
// 5 Day Icons
var iconCode = data.daily[1].weather[0].icon
var icon = "http://openweathermap.org/img/wn/" + iconCode + "@2x.png"
$("#5-day-icon-2").attr("src", icon);
// 5 Day Temperature
var currentTemp = data.daily[1].temp.day
$("#5-day-temp-2").empty().append('Temp: ' + currentTemp +' °F')
// 5 Day Humidity
var currentHumid = data.daily[1].humidity
$("#5-day-humid-2").empty().append('Humidity: ' + currentHumid + "%")
//Day 3
// 5 Day Date
var currentDate = moment().add(3, 'days').format('M/DD/YYYY');
$("#5-day-date-3").empty().append(currentDate);
// 5 Day Icons
var iconCode = data.daily[2].weather[0].icon
var icon = "http://openweathermap.org/img/wn/" + iconCode + "@2x.png"
$("#5-day-icon-3").attr("src", icon);
// 5 Day Temperature
var currentTemp = data.daily[2].temp.day
$("#5-day-temp-3").empty().append('Temp: ' + currentTemp +' °F')
// 5 Day Humidity
var currentHumid = data.daily[2].humidity
$("#5-day-humid-3").empty().append('Humidity: ' + currentHumid + "%")
//Day 4
// 5 Day Date
var currentDate = moment().add(4, 'days').format('M/DD/YYYY');
$("#5-day-date-4").empty().append(currentDate);
// 5 Day Icons
var iconCode = data.daily[3].weather[0].icon
var icon = "http://openweathermap.org/img/wn/" + iconCode + "@2x.png"
$("#5-day-icon-4").attr("src", icon);
// 5 Day Temperature
var currentTemp = data.daily[3].temp.day
$("#5-day-temp-4").empty().append('Temp: ' + currentTemp +' °F')
// 5 Day Humidity
var currentHumid = data.daily[3].humidity
$("#5-day-humid-4").empty().append('Humidity: ' + currentHumid + "%")
//Day 4
// 5 Day Date
var currentDate = moment().add(5, 'days').format('M/DD/YYYY');
$("#5-day-date-5").empty().append(currentDate);
// 5 Day Icons
var iconCode = data.daily[4].weather[0].icon
var icon = "http://openweathermap.org/img/wn/" + iconCode + "@2x.png"
$("#5-day-icon-5").attr("src", icon);
// 5 Day Temperature
var currentTemp = data.daily[4].temp.day
$("#5-day-temp-5").empty().append('Temp: ' + currentTemp +' °F')
// 5 Day Humidity
var currentHumid = data.daily[4].humidity
$("#5-day-humid-5").empty().append('Humidity: ' + currentHumid + "%")
})
}
fiveDayWeather(currentLat, currentLon);
})
}
//Find UV Index for Current City
var findCurrentUvi = function(lat, lon) {
var apiUviUrl = "http://api.openweathermap.org/data/2.5/uvi?lat="+ lat + "&lon=" + lon + "&appid=a877d2c6ed19aff0fd1776e7df46844f"
fetch(apiUviUrl).then(function(response) {
return response.json();
})
.then(function(data){
// UVI Index
var currentUvi = data.value
$("#current-UVI").empty().removeClass().append(currentUvi);
// Change UV Index's Color (favorable:1-2, moderate: 3-5, or severe: 6+)
if (currentUvi < 2.01) {
$("#current-UVI").addClass("bg-success text-white p-2")
}
else if (currentUvi <5.01) {
$("#current-UVI").addClass("bg-warning text-white p-2")
}
else {
$("#current-UVI").addClass("bg-danger text-white p-2")
}
})
}
//When Search Button is clicked
$("#city-btn").click(function(event) {
event.preventDefault();
var cityName = $("#city").val();
findCurrentWeather(cityName);
//Add searched City to Search History
$("#recent").append("<li id='recent-city' class='list-group-item'>" + cityName +"</li>");
})
//When Recent City is clicked
$("#recent").on("click", "li", function (event) {
event.preventDefault();
var recentCity =$(this).text();
findCurrentWeather(recentCity)
})
<file_sep>/README.md
# Weather Dashboard

### Table of Contents
- [Description](#description)
- [Technologies](#technologies)
- [How To Use](#how-to-use)
- [Website](#website)
- [Author Info](#author-info)
---
## Description
An application to show current and 5-day forecasted weathers for cities around the world.
The dashboard allows you to search for cities, as well as view recently viewed cities via the search history.
---
## Technologies
- HTML
- CSS
- Javascript
- JQuery
- Momentsjs
- Open Weather
[Back To The Top](#weather-dashboard)
---
## How To Use
To view a city's weather, type the name of the city you want to view and click the search button. You can also view previously searched cities by clicking on them in the recent history below the search bar.
---
## Website
https://fancibleunicorn.github.io/weather-dashboard/
[Back To The Top](#weather-dashboard)
---
## Author Info
- Github - [@fancibleunciorn](https://github.com/fancibleunicorn)
- Twitter - [@FancibleUnicorn](https://twitter.com/FancibleUnicorn)
[Back To The Top](#weather-dashboard)
| 5f304cf2a2bd61d836a80be07f50ac4274c99ff8 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | fancibleunicorn/weather-dashboard | 119d2eba8f087464bf4093cb2392fe4d66c9fa5e | 8a0011af2b5f55e4b5b0b33086d873a52b3c31d7 |
refs/heads/master | <repo_name>esonpaguia/spring-tutorial-2<file_sep>/module-23/src/main/java/com/esonpaguia/springtutorial/Logger.java
package com.esonpaguia.springtutorial;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
/**
* auto-wired setters
*
*/
public class Logger {
private ConsoleWriter consoleWriter;
private LogWriter fileWriter;
private LogWriter fileWriter2;
@Autowired
public void setConsoleWriter(ConsoleWriter consoleWriter) {
this.consoleWriter = consoleWriter;
}
@Autowired
@Qualifier("fileWriter") // Qualifier declared in the class
public void setFileWriter(LogWriter fileWriter) {
this.fileWriter = fileWriter;
}
@Autowired
@Qualifier("toFile") // Qualifier declared in beans.xml
public void setFileWriter2(LogWriter fileWriter2) {
this.fileWriter2 = fileWriter2;
}
public void writeFile(String text) {
fileWriter.write(text);
}
public void writeFile2(String text) {
fileWriter2.write(text);
}
public void writeConsole(String text) {
if (consoleWriter!=null)
consoleWriter.write(text);
}
}
<file_sep>/module-10/src/main/java/com/esonpaguia/springtutorial/App.java
package com.esonpaguia.springtutorial;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
FruitBasket basket1 = (FruitBasket) context.getBean("basketList");
System.out.println(basket1);
FruitBasket basket2 = (FruitBasket) context.getBean("basketSet"); // removes duplicates
System.out.println(basket2);
((ClassPathXmlApplicationContext) context).close();
}
} <file_sep>/module-4/src/main/java/com/esonpaguia/springtutorial/Person.java
package com.esonpaguia.springtutorial;
public class Person {
private int id;
private String name;
private int a;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public void speak() {
System.out.println("Hello! I'm a person.");
}
public void setTaxId(int b) {
this.a = b;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", taxId=" + a + "]";
}
}<file_sep>/module-21/src/main/java/com/esonpaguia/springtutorial/App.java
package com.esonpaguia.springtutorial;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Logger logger = (Logger) context.getBean("logger");
Logger2 logger2 = (Logger2) context.getBean("logger2");
Logger3 logger3 = (Logger3) context.getBean("logger3");
Logger4 logger4 = (Logger4) context.getBean("logger4");
logger.writeConsole("Hello there");
logger.writeFile("Hi again");
logger2.writeConsole("Hello there 2");
logger2.writeFile("Hi again 2");
logger3.writeConsole("Hello there 3");
logger3.writeFile("Hi again 3");
logger4.writeConsole("Hello there 4");
logger4.writeFile("Hi again 4");
((ClassPathXmlApplicationContext) context).close();
}
} <file_sep>/module-21/src/main/java/com/esonpaguia/springtutorial/Logger2.java
package com.esonpaguia.springtutorial;
import org.springframework.beans.factory.annotation.Autowired;
/**
* auto-wired fields
*
*/
public class Logger2 {
@Autowired
private ConsoleWriter consoleWriter;
@Autowired
private FileWriter fileWriter;
public void setConsoleWriter(ConsoleWriter consoleWriter) {
this.consoleWriter = consoleWriter;
}
public void setFileWriter(FileWriter fileWriter) {
this.fileWriter = fileWriter;
}
public void writeFile(String text) {
fileWriter.write(text);
}
public void writeConsole(String text) {
consoleWriter.write(text);
}
}
<file_sep>/README.md
# Spring Tutorial
## Introduction
This is a concise but not-short of tutorial about Spring framework (v. 4.3.3.RELEASE).
## Requirements
- JDK 8
- Append this to your .profile or .bash_profile or .zprofile if you are using Linux or Mac OS
```
export JAVA_HOME=$(/usr/libexec/java_home)
```
## Repository
```
git clone https://github.com/esonpaguia/spring-tutorial-2.git
```
## Getting Started
1. Run mvn eclipse
```
cd spring-tutorial-2
mvn eclipse:clean eclipse:eclipse
```
2. Import to Eclipse
```
Import > Maven > Existing Maven Projects > Browse > spring-tutorial-2 > Open > Finish
```
## Outline
### Section 1: Contexts
- [File System Context](module-1)
**[App.java](module-1/src/main/java/com/esonpaguia/springtutorial/App.java)**
```
ApplicationContext context = new FileSystemXmlApplicationContext("src/main/resources/beans.xml");
```
- [Class Path Context](module-2)
**[App.java](module-2/src/main/java/com/esonpaguia/springtutorial/App.java)**
```
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
```
### Section 2: Basic Bean Configuration
- [Constructor Arguments](module-3)
- The *name* parameter is optional. If it is not provided, Spring will follow the sequence in the XML. It is better to provide the name to make sure you are setting the right constructor argument.
- The *type* is also optional.
**[beans.xml](module-3/src/main/resources/beans.xml)**
```
<bean id="person" class="Person">
<constructor-arg value="..." name="id"></constructor-arg>
<constructor-arg value="..." name="name"></constructor-arg>
</bean>
```
- [Setting Bean Properties](module-4)
- **JavaBean standard**: The *name* of the property is inferred from the getters and setters, not through any variables in the class.
**[Person.java](module-4/src/main/java/com/esonpaguia/springtutorial/Person.java)**
```
public class Person {
private int a;
public void setTaxId(int b) {...}
}
```
**[beans.xml](module-4/src/main/resources/beans.xml)**
```
<property name="taxId" value="..."></property>
```
This is similar as above.
```
<property name="taxId">
<value>...</value>
</property>
```
- [Dependency Injection](module-5)
- *ref* is the id of another bean that will be injected.
**[beans.xml](module-5/src/main/resources/beans.xml)**
```
<bean id="person" class="Person">
<property name="..." ref="address"></property>
</bean>
<bean id="address" ...>
```
- [Bean Scope](module-6)
- By default, a bean has a *"Singleton"* scope.
- When a bean has a *"Prototype"* scope, Spring will always create new instances of the bean every time you getBean().
**[beans.xml](module-6/src/main/resources/beans.xml)**
```
<bean id="person" class="Person" scope="prototype">
```
- [Init and Destroy Methods](module-7)
- Bean has a lifecycle.
- When a bean has a *"Prototype"* scope, the *"destory-method"* will never run. Spring requires you to manage when destroying beans.
**[beans.xml](module-7/src/main/resources/beans.xml)**
```
<bean id="person" class="..."
init-method="onCreate"
destroy-method="onDestroy">
```
**[Person.java](module-7/src/main/java/com/esonpaguia/springtutorial/Person.java)**
```
public class Person {
public void onCreate() { ... }
public void onDestroy() { ... }
}
```
- When the actual *"default-init-method"* or *"default-destroy-method"* exists, Spring will execute it. Otherwise, no error will occur or Spring will not complain if it cannot find them.
**[beans.xml](module-7/src/main/resources/beans.xml)**
```
<beans ...
default-init-method="init"
default-destroy-method="destroy">
<bean id="..." class="Person">
<bean id="..." class="Address">
</beans>
```
**[Address.java](module-7/src/main/java/com/esonpaguia/springtutorial/Address.java)**
```
public class Address {
public void init() { ... }
// no destroy()
}
```
**[Person.java](module-7/src/main/java/com/esonpaguia/springtutorial/Person.java)**
```
public class Person {
// no init() and destroy()
}
```
- [Factory Beans and Methods](module-8)
- Factory method
- When necessary, modify the actual *"factory-method"* to take the right constructor arguments. You can omit the constructor arguments if not needed.
**[Person.java](module-8/src/main/java/com/esonpaguia/springtutorial/Person.java)**
```
public class Person {
public static Person getInstance(int id, String name) {
return new Person(id, name);
}
}
```
**[beans.xml](module-8/src/main/resources/beans.xml)**
```
<bean id="person" class="Person"
factory-method="getInstance">
<constructor-arg value="..." name="id"></constructor-arg>
<constructor-arg value="..." name="name"></constructor-arg>
</bean>
```
- Factory bean
- When necessary, modify the *"factory-method"* of the *"factory-bean"* to take the right constructor arguments.
**[PersonFactory.java](module-8/src/main/java/com/esonpaguia/springtutorial/PersonFactory.java)**
```
public class PersonFactory {
public Person createPerson(int id, String name) {
return new Person(id, name);
}
}
```
**[beans.xml](module-8/src/main/resources/beans.xml)**
```
<bean id="person2" class="Person"
factory-method="createPerson"
factory-bean="personFactory">
</bean>
<bean id="personFactory"
class="PersonFactory">
<constructor-arg value="..." name="id"></constructor-arg>
<constructor-arg value="..." name="name"></constructor-arg>
</bean>
```
- [P Namespace](module-9)
- P names correspond to the setter's method names.
You can mix and match to use *"property"* definition or *"p"* parameter but you cannot use them both to set the same property name. It will throw an error. Good practice is to stick with one approach.
**[Address.java](module-9/src/main/java/com/esonpaguia/springtutorial/Address.java)**
```
public class Address {
public void setStreet(String street) { ... }
public void setPostalCode(String postalCode) { ... }
}
```
**[beans.xml](module-9/src/main/resources/beans.xml)**
```
<bean id="address2" class="Address"
p:street="..."
p:postalCode="...">
</bean>
```
- [Setting List Properties](module-10)
- The actual constructor argument of the bean is independent from the *"list"* or *"set"* tags defined in the beans descriptor.
- A *"set"* tag omits duplicates.
**[FruitBasket.java](module-10/src/main/java/com/esonpaguia/springtutorial/FruitBasket.java)**
```
public class FruitBasket {
public FruitBasket(String name, List<String> fruits) { ... }
}
```
**[beans.xml](module-10/src/main/resources/beans.xml)**
```
<bean id="basketList"
class="FruitBasket">
<constructor-arg value="basket 1" name="name"></constructor-arg>
<constructor-arg name="fruits">
<list>
<value>apple</value>
<value>banana</value>
<value>cantaloupe</value>
<value>orange</value>
<value>kiwi</value>
<value>orange</value>
</list>
</constructor-arg>
</bean>
<bean id="basketSet"
class="FruitBasket">
<constructor-arg value="basket 2" name="name"></constructor-arg>
<constructor-arg name="fruits">
<set>
<value>apple</value>
<value>banana</value>
<value>cantaloupe</value>
<value>orange</value>
<value>kiwi</value>
<value>orange</value>
</set>
</constructor-arg>
</bean>
```
- [List of Beans](module-11)
**[beans.xml](module-11/src/main/resources/beans.xml)**
```
<bean id="jungle" class="...">
<property name="largest" ref="elephant">
<property name="animals">
<list>
<ref bean="lion"/>
<ref bean="elephant"/>
<ref bean="monkey"/>
</list>
</property>
</bean>
<bean id="lion" ...>
<bean id="elephant" ...>
<bean id="monkey" ...>
```
- [Inner Beans](module-12)
**[beans.xml](module-12/src/main/resources/beans.xml)**
```
<bean id="jungle" class="...">
<property name="largest">
<bean id="elephant" ...>
</property>
<property name="animals">
<list>
<ref bean="lion" />
<ref bean="monkey" />
<bean id="raccoon" ...>
</list>
</property>
</bean>
```
- [Property Maps](module-13)
**[beans.xml](module-13/src/main/resources/beans.xml)**
```
<bean id="jungle" class="...">
<property name="foods">
<props>
<prop key="gorilla">banana</prop>
<prop key="panda">bamboo</prop>
<prop key="snake">eggs</prop>
</props>
</property>
</bean>
```
**[Jungle.java](module-13/src/main/java/com/esonpaguia/springtutorial/Jungle.java)**
```
public class Jungle {
public void setFoods(Map<String, String> foods) { ... }
}
```
- [Arbitrary Maps as Bean Properties](module-14)
**[beans.xml](module-14/src/main/resources/beans.xml)**
```
<bean id="lion" ...>
<bean id="elephant" ...>
<bean id="monkey" ...>
<bean id="jungle" class="Jungle">
<property name="animals">
<map>
<entry key="lion" value-ref="lion"></entry>
<entry key="elephant" value-ref="elephant"></entry>
<entry key="monkey" value-ref="monkey"></entry>
<entry key="raccoon">
<bean id="raccoon" ...>
</entry>
</map>
</property>
</bean>
```
**[Jungle.java](module-14/src/main/java/com/esonpaguia/springtutorial/Jungle.java)**
```
public class Jungle {
public void setAnimals(Map<String, Animal> animals) { ... }
}
```
### Section 3: Autowiring
- [Autowiring by Type](module-15)
- Autowiring "byType" can be used for beans that have different types.
- There are various pitfalls in autowiring:
- If you have a big project and you have a lot of autowiring going on, then it might make it hard to understand what's exactly going on. So if autowiring starts to seem confusing, or your project is huge, then just consider maybe not using it.
- There should be no ambiguity if you try to attempt autowiring. Here, we've got two properties that we want to set. We got two beans and the classes match the properties.
**[beans.xml](module-15/src/main/resources/beans.xml)**
```
<bean id="logger" class="Logger" autowire="byType"></bean>
<bean id="consoleWriter" class="ConsoleWriter"></bean>
<bean id="fileWriter" class="FileWriter"></bean>
```
Spring will not allow autowiring if it's ambiguous. It will only autowire if it's absolutely clear what should be wired where.
**[beans.xml](module-15/src/main/resources/beans.xml)**
```
<bean id="consoleWriter" class="ConsoleWriter"></bean>
<bean id="consoleWriter2" class="ConsoleWriter"></bean>
```
If both beans implements the same interface and you use interface type on the set property. It will cause ambiguity. Spring will not know which type to use because both beans are of the same interface type.
**[Logger.java](module-15/src/main/java/com/esonpaguia/springtutorial/Logger.java)**
```
public class Logger {
private logWriter logWriter;
private ConsoleWriter consoleWriter;
private FileWriter fileWriter;
public void setLogWriter(LogWriter logWriter) {...} // Spring complains.
public void setConsoleWriter(ConsoleWriter consoleWriter) {...}
public void setFileWriter(FileWriter fileWriter) {...}
}
```
- [Autowiring by Name](module-16)
- Spring matches the bean's id or name to the setter's name.
**[beans.xml](module-16/src/main/resources/beans.xml)**
```
<bean id="logger" class="Logger" autowire="byName"></bean>
<bean name="consoleWriter" class="ConsoleWriter"></bean>
<bean id="fileWriter" class="FileWriter"></bean>
```
**[Logger.java](module-16/src/main/java/com/esonpaguia/springtutorial/Logger.java)**
```
public class Logger {
private LogWriter consoleWriter2;
private LogWriter fileWriter2;
public void setConsoleWriter(LogWriter consoleWriter3) { ... }
public void setFileWriter(LogWriter fileWriter3) { ... }
}
```
- [Autowiring by Constructor](module-17)
- When autowiring by constructor, Spring autowires *"by type"* to the constructor arguments.
- Once you set autowire by constructor, you can't autowire by properties.
**[beans.xml](module-17/src/main/resources/beans.xml)**
```
<bean id="logger" class="Logger" autowire="constructor"></bean>
<bean id="consoleWriter" class="ConsoleWriter"></bean>
<bean id="fileWriter" class="FileWriter"></bean>
```
**[Logger.java](module-16/src/main/java/com/esonpaguia/springtutorial/Logger.java)**
```
public class Logger {
public Logger(LogWriter consoleWriter, LogWriter fileWriter) { ... }
}
```
- [Default Autowiring](module-18)
- When you have a lot of beans defined, you can set a default for the whole XML file.
**[beans.xml](module-18-a/src/main/resources/beans.xml)**
```
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
default-init-method="init" default-destroy-method="destroy"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
default-autowire="byName">
<bean id="logger" class="Logger"></bean>
<bean id="consoleWriter" class="ConsoleWriter"></bean
<bean id="fileWriter" class="FileWriter"></bean>
</beans>
```
- To remove ambiguity, you can set autowire candidates. To do this, specify a comma-separated list of beans (no spaces) or use of wildcards.
**[beans.xml](module-18-b/src/main/resources/beans.xml)**
```
<beans ...
default-autowire="byType"
default-autowire-candidates="*Writer">
<bean id="logger" class="Logger"></bean>
<bean id="consoleWriter" class="ConsoleWriter"></bean
<bean id="fileWriter" class="FileWriter"></bean>
<bean id="dummy" class="FileWriter"></bean>
</beans>
```
This is similar as above.
```
<beans ...
default-autowire="byType"
default-autowire-candidates="consoleWriter,fileWriter">
<bean id="logger" class="Logger"></bean>
<bean id="consoleWriter" class="ConsoleWriter"></bean>
<bean id="fileWriter" class="FileWriter"></bean>
<bean id="dummy" class="FileWriter"></bean>
</beans>
```
- [Removing Autowire Ambiguities](module-19)
- You can exclude beans from being candidates for auto-wiring.
**[beans.xml](module-19/src/main/resources/beans.xml)**
```
<beans ...
default-autowire="byType">
<bean id="dummy2" class="..." autowire-candidate="false"></bean>
</beans>
```
- You can set a specific bean as primary. If there is only one primary for that type, Spring will load that bean and ignore the others.
The others will still be considered for auto-wiring (like autowiring *"byName"*)and they might be auto-wired elsewhere and injected into some other bean.
```
<beans ...
default-autowire="byType">
<bean id="consoleWriter" class="ConsoleWriter" primary="true"></bean>
<bean id="dummy1" class="ConsoleWriter"></bean>
</beans>
```
### Section 4: Wiring with Annotations
- [Adding Support for Annotation-Based Wiring](module-20)
- By adding *context* namespace and insert *annotation-config* in your descriptor.
**[beans.xml](module-20/src/main/resources/beans.xml)**
```
<beans ...
xmlns:context="http://www.springframework.org/schema/context">
<context:annotation-config></context:annotation-config>
</beans>
```
- [The *"Autowired"* Annotation](module-21)
- *"Autowired"* annotation auto-wires by type.
- But you can use it in various different positions.
- [In front of setter methods](module-21/src/main/java/com/esonpaguia/springtutorial/Logger.java)
- [In front of property names](module-21/src/main/java/com/esonpaguia/springtutorial/Logger2.java)
- [In front of constructor](module-21/src/main/java/com/esonpaguia/springtutorial/Logger3.java)
- [Mixed auto-wiring](module-21/src/main/java/com/esonpaguia/springtutorial/Logger3.java)
- [Auto-wired fields without the setters](module-21/src/main/java/com/esonpaguia/springtutorial/Logger4.java)
- [Optional Beans](module-22)
- [Using Qualifiers](module-23)
- [The Resource Annotation (JSR-250)](module-24)
- [Annotation-Based Init and Destroy Methods](module-25)
- [The Inject annotation (JSR-330)](module-26)
- Automatic Bean Discovery
- [Using @Inject](module-27-a)
- [Using @Autowired](module-27-b)
- [With @Named](module-27-c)
- [Setting Property Values via Annotations](module-28)
<file_sep>/module-21/src/main/java/com/esonpaguia/springtutorial/Logger3.java
package com.esonpaguia.springtutorial;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Mixed auto-wired constructor and setter
*
*/
public class Logger3 {
private ConsoleWriter consoleWriter;
private FileWriter fileWriter;
@Autowired
public Logger3(ConsoleWriter consoleWriter) {
super();
this.consoleWriter = consoleWriter;
}
public void setConsoleWriter(ConsoleWriter consoleWriter) {
this.consoleWriter = consoleWriter;
}
@Autowired
public void setAsdfg(FileWriter fileWriter) {
this.fileWriter = fileWriter;
}
public void writeFile(String text) {
fileWriter.write(text);
}
public void writeConsole(String text) {
consoleWriter.write(text);
}
}
<file_sep>/module-15/src/main/java/com/esonpaguia/springtutorial/LogWriter.java
package com.esonpaguia.springtutorial;
public interface LogWriter {
void write(String text);
}
<file_sep>/module-21/src/main/java/com/esonpaguia/springtutorial/Logger4.java
package com.esonpaguia.springtutorial;
import org.springframework.beans.factory.annotation.Autowired;
/**
* auto-wired fields without the setters
*
*/
public class Logger4 {
@Autowired
private ConsoleWriter consoleWriter;
@Autowired
private FileWriter fileWriter;
public void writeFile(String text) {
fileWriter.write(text);
}
public void writeConsole(String text) {
consoleWriter.write(text);
}
}
| 41127fe0c6ca3e9738610a0123d9116f958d00f7 | [
"Markdown",
"Java"
] | 9 | Java | esonpaguia/spring-tutorial-2 | dbd0dfb9c9d07bed1f870d6e5007f1ea629688b6 | fbcd6eea743f11a577616b088c0edbbb2207a716 |
refs/heads/master | <file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import java.util.List;
import java.util.Random;
/**
* @author jteuladedenantes
*
* This abstract class contains all attributes and methods similar among the SNN numbers.
*/
public abstract class AbstractGenerateUniqueSsn extends Function<String> {
private static final long serialVersionUID = -2459692854626505777L;
protected GenerateUniqueRandomPatterns ssnPattern;
/**
* Used in some countries to check the SSN number. The initialization can be done in createFieldsListFromPattern
* method if necessary.
*/
protected int checkSumSize = 0;
public AbstractGenerateUniqueSsn() {
List<AbstractField> fields = createFieldsListFromPattern();
ssnPattern = new GenerateUniqueRandomPatterns(fields);
}
@Override
public void setRandom(Random rand) {
super.setRandom(rand);
ssnPattern.setKey(rand.nextInt() % 10000 + 1000);
}
@Override
protected String doGenerateMaskedField(String str) {
if (str == null)
return null;
String strWithoutSpaces = super.removeFormatInString(str);
// check if the pattern is valid
if (strWithoutSpaces.isEmpty() || strWithoutSpaces.length() != ssnPattern.getFieldsCharsLength() + checkSumSize) {
if (keepInvalidPattern)
return str;
else
return null;
}
StringBuilder result = doValidGenerateMaskedField(strWithoutSpaces);
if (result == null) {
if (keepInvalidPattern)
return str;
else
return null;
}
if (keepFormat)
return insertFormatInString(str, result);
else
return result.toString();
}
/**
* @return the list of patterns for each field
*/
protected abstract List<AbstractField> createFieldsListFromPattern();
protected abstract StringBuilder doValidGenerateMaskedField(String str);
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.semantic.model;
public enum CategoryType {
REGEX("RE"),
DICT("DD"),
KEYWORD("KW"),
OTHER("OT");
private String technicalName;
private CategoryType(String technicalName) {
this.technicalName = technicalName;
}
public String getTechnicalName() {
return technicalName;
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Random;
import org.junit.Test;
/**
* created by jgonzalez on 25 juin 2015 Detailled comment
*
*/
public class ReplaceCharactersTest {
private String output;
private String input = "inp456ut value"; //$NON-NLS-1$
private ReplaceCharacters rc = new ReplaceCharacters();
@Test
public void testGood() {
rc.parse("X", false, new Random(42));
output = rc.generateMaskedRow(input);
assertEquals("XXX456XX XXXXX", output); //$NON-NLS-1$
}
@Test
public void testEmpty() {
rc.setKeepEmpty(true);
output = rc.generateMaskedRow("");
assertEquals("", output); //$NON-NLS-1$
}
@Test
public void testParameter() {
rc.parse("5", false, new Random(42));
output = rc.generateMaskedRow(input);
assertEquals("55545655 55555", output); //$NON-NLS-1$
}
@Test
public void testEmptyParameter() {
rc.parse(" ", false, new Random(42));
output = rc.generateMaskedRow(input);
assertEquals("ahw456ma rnqdp", output); //$NON-NLS-1$
}
@Test
public void testWrongParameter() {
try {
rc.parse("12", false, new Random(42));
fail("should get exception with input " + rc.parameters); //$NON-NLS-1$
} catch (Exception e) {
assertTrue("expect illegal argument exception ", e instanceof IllegalArgumentException); //$NON-NLS-1$
}
output = rc.generateMaskedRow(input);
assertEquals("", output); //$NON-NLS-1$
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2015 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.semantic;
import static org.junit.Assert.assertEquals;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import org.junit.Test;
import org.talend.dataquality.duplicating.AllDataqualitySamplingTests;
public class ValueDataMaskerTest {
private static final Map<String[], String> EXPECTED_MASKED_VALUES = new LinkedHashMap<String[], String>() {
private static final long serialVersionUID = 1L;
{
// 0. UNKNOWN
put(new String[] { " ", "UNKNOWN", "string" }, " ");
put(new String[] { "91000", "UNKNOWN", "integer" }, "86622");
put(new String[] { "92000", "UNKNOWN", "decimal" }, "87574");
put(new String[] { "93000", "UNKNOWN", "numeric" }, "88526");
put(new String[] { "2023-06-07", "UNKNOWN", "date" }, "2023-07-01");
put(new String[] { "<EMAIL>", "UNKNOWN", "string" }, "<EMAIL>");
// 1. FIRST_NAME
put(new String[] { "", MaskableCategoryEnum.FIRST_NAME.name(), "string" }, "");
put(new String[] { "John", MaskableCategoryEnum.FIRST_NAME.name(), "string" }, "Josiah");
// 2. LAST_NAME
put(new String[] { "Dupont", MaskableCategoryEnum.LAST_NAME.name(), "string" }, "Robbins");
// 3. EMAIL
put(new String[] { "<EMAIL>", MaskableCategoryEnum.EMAIL.name(), "String" }, "<EMAIL>");
put(new String[] { "\t", MaskableCategoryEnum.FIRST_NAME.name(), "string" }, "\t");
// 4. PHONE
put(new String[] { "3333456789", MaskableCategoryEnum.US_PHONE.name(), "String" }, "3333699941");
// if we put two 1 at the fifth and sixth position, it's not a US valid number, so we replace all the digit
put(new String[] { "3333116789", MaskableCategoryEnum.US_PHONE.name(), "String" }, "2873888808");
put(new String[] { "321938", MaskableCategoryEnum.FR_PHONE.name(), "String" }, "996722");
put(new String[] { "++044dso44aa", MaskableCategoryEnum.DE_PHONE.name(), "String" }, "++287dso38aa");
put(new String[] { "666666666", MaskableCategoryEnum.UK_PHONE.name(), "String" }, "663330954");
put(new String[] { "777777777abc", MaskableCategoryEnum.UK_PHONE.name(), "String" }, "778886113abc");
put(new String[] { "(301) 231-9473 x 2364", MaskableCategoryEnum.US_PHONE.name(), "String" },
"(301) 231-9416 x 7116");
put(new String[] { "(563) 557-7600 Ext. 2890", MaskableCategoryEnum.US_PHONE.name(), "String" },
"(563) 557-7642 Ext. 4410");
// 5. JOB_TITLE
put(new String[] { "CEO", MaskableCategoryEnum.JOB_TITLE.name(), "String" }, "<NAME>");
// 6. ADDRESS_LINE
put(new String[] { "9 Rue Pagès", MaskableCategoryEnum.ADDRESS_LINE.name(), "String" }, "6 Rue XXXXX");
// 7 POSTAL_CODE
put(new String[] { "37218-1324", MaskableCategoryEnum.US_POSTAL_CODE.name(), "String" }, "32515-1655");
put(new String[] { "92150", MaskableCategoryEnum.FR_POSTAL_CODE.name(), "String" }, "32515");
put(new String[] { "63274", MaskableCategoryEnum.DE_POSTAL_CODE.name(), "String" }, "32515");
put(new String[] { "AT1 3BW", MaskableCategoryEnum.UK_POSTAL_CODE.name(), "String" }, "VK5 1ZP");
// 8 ORGANIZATION
// 9 COMPANY
// 10 CREDIT_CARD
put(new String[] { "5300 1232 8732 8318", MaskableCategoryEnum.US_CREDIT_CARD.name(), "String" },
"5332 5151 6550 0021");
put(new String[] { "5300123287328318", MaskableCategoryEnum.MASTERCARD.name(), "String" }, "5332515165500021");
put(new String[] { "4300 1232 8732 8318", MaskableCategoryEnum.VISACARD.name(), "String" }, "4325 1516 5500 0249");
// 11 SSN
put(new String[] { "728931789", MaskableCategoryEnum.US_SSN.name(), "String" }, "528-73-8888");
put(new String[] { "17612 38293 28232", MaskableCategoryEnum.FR_SSN.name(), "String" }, "2210622388880 15");
put(new String[] { "634217823", MaskableCategoryEnum.UK_SSN.name(), "String" }, "RB 87 38 88 D");
// Company
put(new String[] { "Talend", MaskableCategoryEnum.COMPANY.name(), "String" }, "Gilead Sciences");
// FR Commune
put(new String[] { "Amancey", MaskableCategoryEnum.FR_COMMUNE.name(), "String" }, "Dieppe");
// Organization
put(new String[] { "Kiva", MaskableCategoryEnum.ORGANIZATION.name(), "String" }, "Environmental Defense");
// EMPTY
put(new String[] { " ", "UNKNOWN", "integer" }, " ");
put(new String[] { " ", "UNKNOWN", "numeric" }, " ");
put(new String[] { " ", "UNKNOWN", "decimal" }, " ");
put(new String[] { " ", "UNKNOWN", "date" }, " ");
// NUMERIC
put(new String[] { "111", "UNKNOWN", "integer" }, "106");
put(new String[] { "-222.2", "UNKNOWN", "integer" }, "-211.5");
put(new String[] { "333", "UNKNOWN", "numeric" }, "317");
put(new String[] { "444,44", "UNKNOWN", "numeric" }, "423.06");
put(new String[] { "555", "UNKNOWN", "float" }, "528");
put(new String[] { "666.666", "UNKNOWN", "float" }, "634.595");
put(new String[] { "Abc123", "UNKNOWN", "float" }, "Zzp655"); // not numeric, mask by char replacement
// BIG NUMERIC
put(new String[] { "7777777777777777777777777777777777777", "UNKNOWN", "double" },
"7403611837072083888888888888888888888");
put(new String[] { "7777777777777777777777777777777777777.7777", "UNKNOWN", "double" },
"7403611837072083888888888888888888888.8888");
// ENGINEERING FORMAT
put(new String[] { "8e28", "UNKNOWN", "double" }, "7.615143603845572E28");
put(new String[] { "-9.999E29", "UNKNOWN", "double" }, "-9.517977611856484E29");
}
};
/**
* Test method for {@link org.talend.dataquality.datamasking.DataMasker#process(java.lang.Object, boolean)}.
*
* @throws IllegalAccessException
* @throws InstantiationException
*/
@Test
public void testProcess() throws InstantiationException, IllegalAccessException {
for (String[] input : EXPECTED_MASKED_VALUES.keySet()) {
String inputValue = input[0];
String semanticCategory = input[1];
String dataType = input[2];
System.out.print("[" + semanticCategory + "]\n\t" + inputValue + " => ");
final ValueDataMasker masker = new ValueDataMasker(semanticCategory, dataType);
masker.getFunction().setRandom(new Random(AllDataqualitySamplingTests.RANDOM_SEED));
String maskedValue = masker.maskValue(inputValue);
System.out.println(maskedValue);
assertEquals("Test faild on [" + inputValue + "]", EXPECTED_MASKED_VALUES.get(input), maskedValue);
}
// Assert.assertNotEquals(city, masker.process(city));
// masker should generate a city name
// Assert the masked value is in a list of city names
// categories to mask
// First names, last names, email, IP address (v4, v6), localization, GPS coordinates, phone
// Job title , street, address, zipcode, organization, company, full name, credit card number, account number,
//
// for these categories, here are the default functions to use:
// first name -> another first name (from a fixed list loaded from a data file in a resource folder)
// last name -> another last name (from a fixed list)
// email -> mask local part (MaskEmail function)
// phone -> keep 3 first digits and replace last digits
// Job title -> another job title (from a fixed list)
// street -> use MaskAddress
// zipCode -> replace All digits
// organization -> another organization (from a fixed list)
// company -> another company (from a fixed list)
// credit card -> generate a new one
// account number -> generate a new one
//
// Assertions: masked data must never be identical to original data (don't use random seed for the random
// generator to check that)
//
// data types to mask
// date, string, numeric
// create a ValueDataMasker for data that have no semantic category
// use ValueDataMasker masker = SemanticCategoryMaskerFactory.createMasker(dataType);
// here are the default functions to use for the different types:
// date -> DateVariance with parameter 61 (meaning two months)
// string -> use ReplaceAll
// numeric -> use NumericVariance
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import static org.junit.Assert.assertEquals;
import java.util.Random;
import org.junit.Before;
import org.junit.Test;
/**
* @author dprot
*/
public class GenerateSsnChnTest {
private String output;
private GenerateSsnChn gnf = new GenerateSsnChn();
@Before
public void setUp() throws Exception {
gnf.setRandom(new Random(42));
}
@Test
public void testEmpty() {
gnf.setKeepEmpty(true);
output = gnf.generateMaskedRow("");
assertEquals("", output); //$NON-NLS-1$
}
@Test
public void testGood() {
output = gnf.generateMaskedRow(null);
assertEquals("610201206301240556", output); //$NON-NLS-1$
}
@Test
public void testCheckFirstDigit() {
// First digit should not be a '9' in a Chinese SSN
gnf.setRandom(new Random());
boolean res = true;
for (int i = 0; i < 10; ++i) {
String tmp = gnf.generateMaskedRow(null);
res = !(tmp.charAt(0) == '9');
assertEquals("wrong number : " + tmp, res, true); //$NON-NLS-1$
}
}
@Test
public void testCheckYear() {
// Year should be between 1900 and 2100
gnf.setRandom(new Random());
boolean res = true;
for (int i = 0; i < 10; ++i) {
String tmp = gnf.generateMaskedRow(null);
int yyyy = Integer.valueOf(tmp.substring(6, 10));
res = (yyyy >= 1900 && yyyy < 2100);
assertEquals("wrong year : " + yyyy, res, true); //$NON-NLS-1$
}
}
@Test
public void testNull() {
gnf.keepNull = true;
output = gnf.generateMaskedRow(null);
assertEquals(null, output);
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.semantic.index;
import java.io.IOException;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
/**
* Created by sizhaoliu on 03/04/15.
*/
public class LuceneIndex implements Index {
private static final Logger LOG = Logger.getLogger(LuceneIndex.class);
private final DictionarySearcher searcher;
public LuceneIndex(URI indexPath, DictionarySearchMode searchMode) {
this(new DictionarySearcher(indexPath), searchMode);
}
public LuceneIndex(Directory directory, DictionarySearchMode searchMode) {
this(new DictionarySearcher(directory), searchMode);
}
private LuceneIndex(DictionarySearcher searcher, DictionarySearchMode searchMode) {
this.searcher = searcher;
searcher.setTopDocLimit(20);
searcher.setSearchMode(searchMode);
}
@Override
public void initIndex() {
searcher.maybeRefreshIndex();
}
@Override
public void closeIndex() {
searcher.close();
}
@Override
public Set<String> findCategories(String data) {
Set<String> foundCategorySet = new HashSet<String>();
try {
TopDocs docs = searcher.searchDocumentBySynonym(data);
for (ScoreDoc scoreDoc : docs.scoreDocs) {
Document document = searcher.getDocument(scoreDoc.doc);
foundCategorySet.add(document.getValues(DictionarySearcher.F_WORD)[0]);
}
} catch (IOException e) {
LOG.error(e, e);
}
return foundCategorySet;
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.semantic.index;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.junit.Before;
import org.junit.Test;
public class ConcurrentDictionaryAccessTest {
private static final Logger log = Logger.getLogger(ConcurrentDictionaryAccessTest.class);
private AtomicBoolean errorOccurred = new AtomicBoolean();
@Before
public void setUp() throws Exception {
errorOccurred.set(false);
}
private DictionarySearcher newSemanticDictionarySearcher() {
try {
final URI ddPath = this.getClass().getResource("/index/dictionary").toURI();
final DictionarySearcher searcher = new DictionarySearcher(ddPath);
searcher.setTopDocLimit(20);
searcher.setSearchMode(DictionarySearchMode.MATCH_SEMANTIC_DICTIONARY);
return searcher;
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private class SearcherRunnable implements Runnable {
@Override
public void run() {
final DictionarySearcher searcher = newSemanticDictionarySearcher();
doConcurrentAccess(searcher, true);
}
};
@Test
public void testThreadUnsafeConcurrentAccess() throws Exception {
try {
List<Thread> workers = new ArrayList<>();
for (int i = 0; i < 200; i++) {
final Runnable r = new SearcherRunnable();
workers.add(new Thread(r));
}
for (Thread worker : workers) {
worker.start();
}
for (Thread worker : workers) {
worker.join();
}
assertEquals("ConcurrentAccess failed", false, errorOccurred.get());
} catch (Exception e) {
fail(e.getMessage());
}
}
private static final Map<String, List<String>> EXPECTED_CATEGORY = new HashMap<String, List<String>>() {
private static final long serialVersionUID = 3771932655942133797L;
{
put("Paris", Arrays.asList(new String[] { "CITY", "FIRST_NAME", "LAST_NAME", "FR_COMMUNE", "FR_DEPARTEMENT" }));
put("Talend", Arrays.asList(new String[] { "COMPANY" }));
put("CDG", Arrays.asList(new String[] { "AIRPORT_CODE" }));
put("French", Arrays.asList(new String[] { "LANGUAGE", "LAST_NAME" }));
}
};
private void doConcurrentAccess(DictionarySearcher searcher, boolean isLogEnabled) {
int datasetID = (int) Math.floor(Math.random() * 4);
String input = "";
switch (datasetID) {
case 0:
input = "Paris";
break;
case 1:
input = "Talend";
break;
case 2:
input = "CDG";
break;
case 3:
input = "French";
break;
default:
break;
}
try {
final TopDocs docs = searcher.searchDocumentBySynonym(input);
ScoreDoc[] scoreDocs = docs.scoreDocs;
for (ScoreDoc sd : scoreDocs) {
final Document doc = searcher.getDocument(sd.doc);
final String cat = doc.getField("word").stringValue();
if (!EXPECTED_CATEGORY.get(input).contains(cat)) {
errorOccurred.set(true);
if (isLogEnabled) {
log.error(input + " is expected to be a " + cat + " but actually not");
}
}
}
searcher.close();
} catch (Exception e) {
errorOccurred.set(true);
if (isLogEnabled) {
log.error(e.getMessage(), e);
}
}
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2015 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.semantic.index.utils;
class CsvConstants {
static final char COMMA = ',';
static final char SEMICOLON = ';';
static final char TAB = '\t';
static final char PIPE = '|';
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import static org.junit.Assert.assertEquals;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Random;
import org.junit.Assert;
import org.junit.Test;
/**
* created by jgonzalez on 29 juin 2015 Detailled comment
*
*/
public class NumericVarianceIntegerTest {
private String output;
private Integer input = 123;
private NumericVarianceInteger nvi = new NumericVarianceInteger();
@Test
public void testGood() {
nvi.parse("10", false, new Random(42));
output = nvi.generateMaskedRow(input).toString();
assertEquals(-7, nvi.rate);
assertEquals(output, String.valueOf(115));
}
@Test
public void testNullParameter() {
nvi.parse(null, false, new Random(8766));
output = nvi.generateMaskedRow(input).toString();
assertEquals(9, nvi.rate);
assertEquals(output, String.valueOf(134));
}
@Test
public void testDummy() {
nvi.parse("-10", false, new Random(42));
output = nvi.generateMaskedRow(input).toString();
assertEquals(-7, nvi.rate);
assertEquals(String.valueOf(115), output);
}
/**
*
* {@link org.talend.dataquality.datamasking.functions.NumericVarianceInteger#doGenerateMaskedField(Integer)}
*/
@Test
public void testOverFlowCase() {
// Before OverFlow Case 99999999+20*99999999/100=119999998
nvi.parse("30", false, new Random(42));
output = nvi.generateMaskedRow(99999999).toString();
assertEquals(20, nvi.rate);
assertEquals(String.valueOf(119999998), output);
// over flow case for -237*99999999
nvi.parse("3000", false, new Random(42));
output = nvi.generateMaskedRow(99999999).toString();
assertEquals(-1870, nvi.rate);
assertEquals(String.valueOf(79000000), output);
// over flow case for 1248*99999999
nvi.parse("30000", false, new Random(42));
output = nvi.generateMaskedRow(99999999).toString();
assertEquals(1130, nvi.rate);
assertEquals(String.valueOf(120999998), output);
// over flow case for 18884*-99999999
nvi.parse("30000", false, new Random(42));
output = nvi.generateMaskedRow(-99999999).toString();
assertEquals(1130, nvi.rate);
assertEquals(String.valueOf(-120999998), output);
// over flow case for -2030*-99999999
nvi.parse("-4000", false, new Random(42));
output = nvi.generateMaskedRow(-99999999).toString();
assertEquals(1130, nvi.rate);
assertEquals(String.valueOf(-120999998), output);
}
/**
*
* {@link org.talend.dataquality.datamasking.functions.NumericVarianceInteger#getNonOverAddResult(int,int)}
*
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*
* case1 Integer.MAX_VALUE+Integer.MIN_VALUE=-1
*/
@Test
public void testGetNonOverAddResultCase1() throws InstantiationException, IllegalAccessException, NoSuchMethodException,
SecurityException, IllegalArgumentException, InvocationTargetException {
Class<NumericVarianceInteger> reflectNVIClass = NumericVarianceInteger.class;
Method getNonOverAddResultMethod = reflectNVIClass.getDeclaredMethod("getNonOverAddResult", //$NON-NLS-1$
new Class[] { int.class, int.class });
getNonOverAddResultMethod.setAccessible(true);
Object invoke = getNonOverAddResultMethod.invoke(new NumericVarianceInteger(),
new Object[] { Integer.MAX_VALUE, Integer.MIN_VALUE });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be -1 but it is " + invoke.toString(), -1, invoke); //$NON-NLS-1$
}
/**
*
* {@link org.talend.dataquality.datamasking.functions.NumericVarianceInteger#getNonOverAddResult(int,int)}
*
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*
* case2 Integer.MAX_VALUE+Integer.MAX_VALUE==Integer.MAX_VALUE-Integer.MAX_VALUE==0
*/
@Test
public void testGetNonOverAddResultCase2() throws InstantiationException, IllegalAccessException, NoSuchMethodException,
SecurityException, IllegalArgumentException, InvocationTargetException {
Class<NumericVarianceInteger> reflectNVIClass = NumericVarianceInteger.class;
Method getNonOverAddResultMethod = reflectNVIClass.getDeclaredMethod("getNonOverAddResult", //$NON-NLS-1$
new Class[] { int.class, int.class });
getNonOverAddResultMethod.setAccessible(true);
Object invoke = getNonOverAddResultMethod.invoke(new NumericVarianceInteger(),
new Object[] { Integer.MAX_VALUE, Integer.MAX_VALUE });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be 0 but it is " + invoke.toString(), 0, invoke); //$NON-NLS-1$
}
/**
*
* {@link org.talend.dataquality.datamasking.functions.NumericVarianceInteger#getNonOverAddResult(int,int)}
*
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*
* case3 Integer.MAX_VALUE+0==Integer.MAX_VALUE
*/
@Test
public void testGetNonOverAddResultCase3() throws InstantiationException, IllegalAccessException, NoSuchMethodException,
SecurityException, IllegalArgumentException, InvocationTargetException {
Class<NumericVarianceInteger> reflectNVIClass = NumericVarianceInteger.class;
Method getNonOverAddResultMethod = reflectNVIClass.getDeclaredMethod("getNonOverAddResult", //$NON-NLS-1$
new Class[] { int.class, int.class });
getNonOverAddResultMethod.setAccessible(true);
Object invoke = getNonOverAddResultMethod.invoke(new NumericVarianceInteger(), new Object[] { Integer.MAX_VALUE, 0 });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be Integer.MAX_VALUE but it is " + invoke.toString(), Integer.MAX_VALUE, //$NON-NLS-1$
invoke);
}
/**
*
* {@link org.talend.dataquality.datamasking.functions.NumericVarianceInteger#getNonOverAddResult(int,int)}
*
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*
* case4 Integer.MAX_VALUE+1==Integer.MAX_VALUE-1=2147483646
*/
@Test
public void testGetNonOverAddResultCase4() throws InstantiationException, IllegalAccessException, NoSuchMethodException,
SecurityException, IllegalArgumentException, InvocationTargetException {
Class<NumericVarianceInteger> reflectNVIClass = NumericVarianceInteger.class;
Method getNonOverAddResultMethod = reflectNVIClass.getDeclaredMethod("getNonOverAddResult", //$NON-NLS-1$
new Class[] { int.class, int.class });
getNonOverAddResultMethod.setAccessible(true);
Object invoke = getNonOverAddResultMethod.invoke(new NumericVarianceInteger(), new Object[] { Integer.MAX_VALUE, 1 });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be 2147483646 but it is " + invoke.toString(), 2147483646, invoke); //$NON-NLS-1$
}
/**
*
* {@link org.talend.dataquality.datamasking.functions.NumericVarianceInteger#getNonOverAddResult(int,int)}
*
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*
* case5 Integer.MIN_VALUE+Integer.MIN_VALUE==Integer.MIN_VALUE-Integer.MIN_VALUE=0
*/
@Test
public void testGetNonOverAddResultCase5() throws InstantiationException, IllegalAccessException, NoSuchMethodException,
SecurityException, IllegalArgumentException, InvocationTargetException {
Class<NumericVarianceInteger> reflectNVIClass = NumericVarianceInteger.class;
Method getNonOverAddResultMethod = reflectNVIClass.getDeclaredMethod("getNonOverAddResult", //$NON-NLS-1$
new Class[] { int.class, int.class });
getNonOverAddResultMethod.setAccessible(true);
Object invoke = getNonOverAddResultMethod.invoke(new NumericVarianceInteger(),
new Object[] { Integer.MIN_VALUE, Integer.MIN_VALUE });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be 0 but it is " + invoke.toString(), 0, invoke); //$NON-NLS-1$
}
/**
*
* {@link org.talend.dataquality.datamasking.functions.NumericVarianceInteger#getNonOverAddResult(int,int)}
*
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*
* case6 Integer.MIN_VALUE+-1==Integer.MIN_VALUE+1=-2147483647
*/
@Test
public void testGetNonOverAddResultCase6() throws InstantiationException, IllegalAccessException, NoSuchMethodException,
SecurityException, IllegalArgumentException, InvocationTargetException {
Class<NumericVarianceInteger> reflectNVIClass = NumericVarianceInteger.class;
Method getNonOverAddResultMethod = reflectNVIClass.getDeclaredMethod("getNonOverAddResult", //$NON-NLS-1$
new Class[] { int.class, int.class });
getNonOverAddResultMethod.setAccessible(true);
Object invoke = getNonOverAddResultMethod.invoke(new NumericVarianceInteger(), new Object[] { Integer.MIN_VALUE, -1 });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be -2147483647 but it is " + invoke.toString(), -2147483647, invoke); //$NON-NLS-1$
}
/**
*
* {@link org.talend.dataquality.datamasking.functions.NumericVarianceInteger#getNonOverAddResult(int,int)}
*
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*
* case7 Integer.MIN_VALUE+0==Integer.MIN_VALUE
*/
@Test
public void testGetNonOverAddResultCase7() throws InstantiationException, IllegalAccessException, NoSuchMethodException,
SecurityException, IllegalArgumentException, InvocationTargetException {
Class<NumericVarianceInteger> reflectNVIClass = NumericVarianceInteger.class;
Method getNonOverAddResultMethod = reflectNVIClass.getDeclaredMethod("getNonOverAddResult", //$NON-NLS-1$
new Class[] { int.class, int.class });
getNonOverAddResultMethod.setAccessible(true);
Object invoke = getNonOverAddResultMethod.invoke(new NumericVarianceInteger(), new Object[] { Integer.MIN_VALUE, 0 });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be Integer.MIN_VALUE but it is " + invoke.toString(), -2147483648, invoke); //$NON-NLS-1$
}
/**
*
* {@link org.talend.dataquality.datamasking.functions.NumericVarianceInteger#getNonOverMultiResult(int,int)}
*
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*
* case1 0*any==any*0==0
*/
@Test
public void testGetNonOverMultiResultCase1() throws InstantiationException, IllegalAccessException, NoSuchMethodException,
SecurityException, IllegalArgumentException, InvocationTargetException {
Class<NumericVarianceInteger> reflectNVIClass = NumericVarianceInteger.class;
Method getNonOverMultiResultMethod = reflectNVIClass.getDeclaredMethod("getNonOverMultiResult", //$NON-NLS-1$
new Class[] { int.class, int.class });
getNonOverMultiResultMethod.setAccessible(true);
// Integer.MIN_VALUE*0
Object invoke = getNonOverMultiResultMethod.invoke(new NumericVarianceInteger(), new Object[] { Integer.MIN_VALUE, 0 });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be 0 but it is " + invoke.toString(), 0, invoke); //$NON-NLS-1$
// 0*Integer.MAX_VALUE
invoke = getNonOverMultiResultMethod.invoke(new NumericVarianceInteger(), new Object[] { 0, Integer.MAX_VALUE });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be 0 but it is " + invoke.toString(), 0, invoke); //$NON-NLS-1$
// 0*0
invoke = getNonOverMultiResultMethod.invoke(new NumericVarianceInteger(), new Object[] { 0, 0 });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be 0 but it is " + invoke.toString(), 0, invoke); //$NON-NLS-1$
}
/**
*
* {@link org.talend.dataquality.datamasking.functions.NumericVarianceInteger#getNonOverMultiResult(int,int)}
*
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*
* case2 Integer.MIN_VALUE*Integer.MAX_VALUE==Integer.MIN_VALUE=-2147483648
*/
@Test
public void testGetNonOverMultiResultCase2() throws InstantiationException, IllegalAccessException, NoSuchMethodException,
SecurityException, IllegalArgumentException, InvocationTargetException {
Class<NumericVarianceInteger> reflectNVIClass = NumericVarianceInteger.class;
Method getNonOverMultiResultMethod = reflectNVIClass.getDeclaredMethod("getNonOverMultiResult", //$NON-NLS-1$
new Class[] { int.class, int.class });
getNonOverMultiResultMethod.setAccessible(true);
Object invoke = getNonOverMultiResultMethod.invoke(new NumericVarianceInteger(),
new Object[] { Integer.MIN_VALUE, Integer.MAX_VALUE });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be Integer.MIN_VALUE but it is " + invoke.toString(), -2147483648, invoke); //$NON-NLS-1$
}
/**
*
* {@link org.talend.dataquality.datamasking.functions.NumericVarianceInteger#getNonOverMultiResult(int,int)}
*
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*
* case3 Integer.MIN_VALUE*Integer.MIN_VALUE==Integer.MAX_VALUE=2147483647
*/
@Test
public void testGetNonOverMultiResultCase3() throws InstantiationException, IllegalAccessException, NoSuchMethodException,
SecurityException, IllegalArgumentException, InvocationTargetException {
Class<NumericVarianceInteger> reflectNVIClass = NumericVarianceInteger.class;
Method getNonOverMultiResultMethod = reflectNVIClass.getDeclaredMethod("getNonOverMultiResult", //$NON-NLS-1$
new Class[] { int.class, int.class });
getNonOverMultiResultMethod.setAccessible(true);
Object invoke = getNonOverMultiResultMethod.invoke(new NumericVarianceInteger(),
new Object[] { Integer.MIN_VALUE, Integer.MIN_VALUE });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be Integer.MAX_VALUE but it is " + invoke.toString(), 2147483647, invoke); //$NON-NLS-1$
}
/**
*
* {@link org.talend.dataquality.datamasking.functions.NumericVarianceInteger#getNonOverMultiResult(int,int)}
*
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*
* case4 Integer.MAX_VALUE*Integer.MAX_VALUE==Integer.MAX_VALUE=2147483647
*/
@Test
public void testGetNonOverMultiResultCase4() throws InstantiationException, IllegalAccessException, NoSuchMethodException,
SecurityException, IllegalArgumentException, InvocationTargetException {
Class<NumericVarianceInteger> reflectNVIClass = NumericVarianceInteger.class;
Method getNonOverMultiResultMethod = reflectNVIClass.getDeclaredMethod("getNonOverMultiResult", //$NON-NLS-1$
new Class[] { int.class, int.class });
getNonOverMultiResultMethod.setAccessible(true);
Object invoke = getNonOverMultiResultMethod.invoke(new NumericVarianceInteger(),
new Object[] { Integer.MAX_VALUE, Integer.MAX_VALUE });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be Integer.MAX_VALUE but it is " + invoke.toString(), 2147483647, invoke); //$NON-NLS-1$
}
/**
*
* {@link org.talend.dataquality.datamasking.functions.NumericVarianceInteger#getNonOverMultiResult(int,int)}
*
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*
* case5 Integer.MIN_VALUE*-2==Integer.MAX_VALUE=2147483647
*/
@Test
public void testGetNonOverMultiResultCase5() throws InstantiationException, IllegalAccessException, NoSuchMethodException,
SecurityException, IllegalArgumentException, InvocationTargetException {
Class<NumericVarianceInteger> reflectNVIClass = NumericVarianceInteger.class;
Method getNonOverMultiResultMethod = reflectNVIClass.getDeclaredMethod("getNonOverMultiResult", //$NON-NLS-1$
new Class[] { int.class, int.class });
getNonOverMultiResultMethod.setAccessible(true);
Object invoke = getNonOverMultiResultMethod.invoke(new NumericVarianceInteger(), new Object[] { Integer.MIN_VALUE, -2 });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be Integer.MAX_VALUE but it is " + invoke.toString(), 2147483647, invoke); //$NON-NLS-1$
// when -2*Integer.MIN_VALUE we should ge same result
invoke = getNonOverMultiResultMethod.invoke(new NumericVarianceInteger(), new Object[] { -2, Integer.MIN_VALUE });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be Integer.MAX_VALUE but it is " + invoke.toString(), 2147483647, invoke); //$NON-NLS-1$
}
/**
*
* {@link org.talend.dataquality.datamasking.functions.NumericVarianceInteger#getNonOverMultiResult(int,int)}
*
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*
* case6 99999999*100==100*99999999 99999999*-100==-100*99999999
*/
@Test
public void testGetNonOverMultiResultCase6() throws InstantiationException, IllegalAccessException, NoSuchMethodException,
SecurityException, IllegalArgumentException, InvocationTargetException {
Class<NumericVarianceInteger> reflectNVIClass = NumericVarianceInteger.class;
Method getNonOverMultiResultMethod = reflectNVIClass.getDeclaredMethod("getNonOverMultiResult", //$NON-NLS-1$
new Class[] { int.class, int.class });
getNonOverMultiResultMethod.setAccessible(true);
// 99999999*100
Object invoke = getNonOverMultiResultMethod.invoke(new NumericVarianceInteger(), new Object[] { 99999999, 100 });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be Integer.MAX_VALUE but it is " + invoke.toString(), 2099999979, invoke); //$NON-NLS-1$
// 100*99999999
invoke = getNonOverMultiResultMethod.invoke(new NumericVarianceInteger(), new Object[] { 100, 99999999 });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be Integer.MAX_VALUE but it is " + invoke.toString(), 2099999979, invoke); //$NON-NLS-1$
// -100*99999999
invoke = getNonOverMultiResultMethod.invoke(new NumericVarianceInteger(), new Object[] { -100, 99999999 });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be Integer.MAX_VALUE but it is " + invoke.toString(), -2099999979, invoke); //$NON-NLS-1$
// 99999999*-100
invoke = getNonOverMultiResultMethod.invoke(new NumericVarianceInteger(), new Object[] { -100, 99999999 });
Assert.assertNotNull("Current result should be null", invoke); //$NON-NLS-1$
Assert.assertTrue("Current type of result should be Integer but it is " + invoke.getClass().getSimpleName(), invoke //$NON-NLS-1$
.getClass().getSimpleName().equals("Integer")); //$NON-NLS-1$
Assert.assertEquals("Current result should be Integer.MAX_VALUE but it is " + invoke.toString(), -2099999979, invoke); //$NON-NLS-1$
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
/**
* DOC qzhao class global comment. Detailled comment<br>
*
* This class provides a random replacement of the top-level email address from a list of common domains<br>
*
* If a specified domain is provided, see the class {@link MaskSpecifiedEmailDomain}
*
* <b>See also:</b> {@link MaskEmail}
*/
public class MaskTopEmailDomainRandomly extends MaskEmailRandomly {
private static final long serialVersionUID = 4725759790417755993L;
@Override
protected String maskEmail(String address) {
int splitAddress = address.indexOf('@');
int splitDomain = address.lastIndexOf('.');
return address.substring(0, splitAddress + 1)
+ parameters[chooseAppropriateDomainIndex(address.substring(splitAddress + 1, splitDomain))]
+ address.substring(splitDomain);
}
}
<file_sep>package org.talend.dataquality.semantic.api;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import org.talend.dataquality.semantic.classifier.SemanticCategoryEnum;
import org.talend.dataquality.semantic.model.DQCategory;
public class LocalDictionaryCacheTest {
Map<String, String[]> EXPECTED_SUGGESTIONS = new LinkedHashMap<String, String[]>() {
private static final long serialVersionUID = -1799392161895210253L;
{
put("c", new String[] {});
put(" chalette", new String[] { "Chalette-sur-Voire", "Châlette-sur-Loing" });
put("Chalette", new String[] { "Chalette-sur-Voire", "Châlette-sur-Loing" });
put("châlette", new String[] { "Chalette-sur-Voire", "Châlette-sur-Loing", });
put("loi",
new String[] { "Loigny-la-Bataille", //
"Loigné-sur-Mayenne", //
"Loire-les-Marais", //
"Loire-sur-Rhône", //
"Loiron", //
"Loiré", //
"Loiré-sur-Nie", //
"Loisail", //
"Loisey", //
"Loisia", //
"Loisieux", //
"Loisin", //
"Loison", //
"Loison-sous-Lens", //
"Loison-sur-Créquoise", //
"Loisy", //
"Loisy-en-Brie", //
"Loisy-sur-Marne", //
"Loivre", //
"Loix", //
});
put("loin",
new String[] { "Bagneaux-sur-Loing", //
"Châlette-sur-Loing", //
"Conflans-sur-Loing", //
"Corgoloin", //
"Dammarie-sur-Loing", //
"Floing", //
"Fontenay-sur-Loing", //
"Gauchin-Verloingt", //
"Grez-sur-Loing", //
"La Madeleine-sur-Loing", //
"Montigny-sur-Loing", //
"Sainte-Colombe-sur-Loing", //
"Souppes-sur-Loing", //
"Villeloin-Coulangé", //
});
put("loing",
new String[] { "Bagneaux-sur-Loing", //
"Châlette-sur-Loing", //
"Conflans-sur-Loing", //
"Dammarie-sur-Loing", //
"Floing", //
"Fontenay-sur-Loing", //
"Gauchin-Verloingt", //
"Grez-sur-Loing", //
"La Madeleine-sur-Loing", //
"Montigny-sur-Loing", //
"Sainte-Colombe-sur-Loing", //
"Souppes-sur-Loing", //
});
put("ur loin",
new String[] { "Bagneaux-sur-Loing", //
"Châlette-sur-Loing", //
"Conflans-sur-Loing", //
"Dammarie-sur-Loing", //
"Fontenay-sur-Loing", //
"Grez-sur-Loing", //
"La Madeleine-sur-Loing", //
"Montigny-sur-Loing", //
"Sainte-Colombe-sur-Loing", //
"Souppes-sur-Loing", //
});
put("ur-loin",
new String[] { "Bagneaux-sur-Loing", //
"Châlette-sur-Loing", //
"Conflans-sur-Loing", //
"Dammarie-sur-Loing", //
"Fontenay-sur-Loing", //
"Grez-sur-Loing", //
"La Madeleine-sur-Loing", //
"Montigny-sur-Loing", //
"Sainte-Colombe-sur-Loing", //
"Souppes-sur-Loing", //
});
}
};
@Test
public void testSuggestValues() {
LocalDictionaryCache dict = CategoryRegistryManager.getInstance().getDictionaryCache();
for (String input : EXPECTED_SUGGESTIONS.keySet()) {
Set<String> found = dict.suggestValues(SemanticCategoryEnum.FR_COMMUNE.name(), input);
assertEquals("Unexpected result size for input: " + input, EXPECTED_SUGGESTIONS.get(input).length, found.size());
for (String expected : EXPECTED_SUGGESTIONS.get(input)) {
assertTrue("Expected result not found: " + expected, found.contains(expected));
}
}
}
public static void main(String[] args) {
CategoryRegistryManager.setLocalRegistryPath(System.getProperty("java.io.tmpdir") + "/org.talend.dataquality.semantic/");
for (DQCategory cat : CategoryRegistryManager.getInstance().listCategories()) {
System.out.println(cat);
}
LocalDictionaryCache dict = CategoryRegistryManager.getInstance().getDictionaryCache();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Choose category: ");
String categoryName = br.readLine();
while (true) {
System.out.print("Show suggestions for: ");
String input = br.readLine();
if ("q".equals(input)) {
System.out.println("Exit!");
System.exit(0);
}
long begin = System.currentTimeMillis();
Set<String> lookupResultList = dict.suggestValues(categoryName, input, Integer.MAX_VALUE);
long end = System.currentTimeMillis();
for (String res : lookupResultList) {
System.out.println(res);
}
System.out.println("Found " + lookupResultList.size() + " results in " + (end - begin) + " ms.");
System.out.println("-----------\n");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
/**
* The class generates the American ssn number randomly.<br>
* The first two characters has 72 different combinations. The the following characters, whether is 00, whether is 06,
* whether is an integer from 0 to 8, so it has 11 permutations. The following character has 9 combinations. The
* following character has 9 combinations too. The end four characters, it can generate at least 5832 combinations. <br>
* In totoal, it has 374 134 464 results.<br>
*/
public class GenerateSsnUs extends Function<String> {
private static final long serialVersionUID = -7651076296534530622L;
@Override
protected String doGenerateMaskedField(String str) {
StringBuilder result = new StringBuilder(EMPTY_STRING);
result.append(rnd.nextInt(8));
result.append(rnd.nextInt(9));
if (result.charAt(0) == '0' && result.charAt(1) == '0' || result.charAt(0) == '6' && result.charAt(1) == '6') {
int tmp = 0;
do {
tmp = rnd.nextInt(9);
} while ((char) tmp == result.charAt(0));
result.append(tmp);
} else {
result.append(rnd.nextInt(9));
}
result.append("-"); //$NON-NLS-1$
result.append(rnd.nextInt(9));
if (result.charAt(4) == '0') {
result.append(rnd.nextInt(8) + 1);
} else {
result.append(rnd.nextInt(9));
}
result.append("-"); //$NON-NLS-1$
for (int i = 0; i < 3; ++i) {
result.append(rnd.nextInt(9));
}
if (result.charAt(7) == '0' && result.charAt(8) == '0' && result.charAt(9) == '0') {
result.append(rnd.nextInt(8) + 1);
} else {
result.append(rnd.nextInt(9));
}
return result.toString();
}
}
<file_sep>package org.talend.dataquality.datamasking.shuffling;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class ShuffleColumnTest {
private String file5000 = "Shuffling_test_data_5000.csv";
private String file50000 = "Shuffling_test_data_50000.csv";
private String file1000Compared = "Shuffling_test_data_1000 _result.csv";
private static List<Integer> data = new ArrayList<Integer>();
private static GenerateData generation = new GenerateData();
private static List<List<String>> columns = new ArrayList<List<String>>();
private static List<String> allColumns = Arrays
.asList(new String[] { "id", "first_name", "last_name", "email", "gender", "birth", "city", "zip_code", "country" });
@BeforeClass
public static void generateData() {
for (int i = 0; i < 14; i++) {
data.add(i);
}
List<String> column1 = Arrays.asList(new String[] { "id", "first_name" });
List<String> column2 = Arrays.asList(new String[] { "email" });
List<String> column3 = Arrays.asList(new String[] { "city", "zip_code" });
columns.add(column1);
columns.add(column2);
columns.add(column3);
}
@Test
public void testBufferDemo() {
String file = "demo_test.csv";
String fileCompared = "demo_test _result.csv";
List<List<String>> columns = new ArrayList<List<String>>();
List<String> column1 = Arrays.asList(new String[] { "id" });
List<String> column2 = Arrays.asList(new String[] { "fn", "ln" });
columns.add(column1);
columns.add(column2);
List<String> allColumns = Arrays.asList(new String[] { "id", "fn", "ln", "City", "Addr", "Country" });
Queue<List<List<Object>>> result = new ConcurrentLinkedQueue<List<List<Object>>>();
ShufflingService service = new ShufflingService(columns, allColumns);
ShufflingHandler handler = new ShufflingHandler(service, result);
service.setShufflingHandler(handler);
service.setSeperationSize(10);
service.setRandomSeed(77);
List<List<Object>> fileData = generation.getTableValue(file);
long time1 = System.currentTimeMillis();
service.setRows(fileData);
long time2 = System.currentTimeMillis();
service.setHasFinished(true);
List<List<Object>> fileDataCompared = generation.getTableValue(fileCompared);
for (int i = 0; i < 2; i++) {
List<List<Object>> rows = result.peek();
for (int j = 0; j < rows.size(); j++) {
List<Object> shuffled = rows.get(j);
List<Object> compared = fileDataCompared.get(i * 10 + j);
for (int k = 0; k < 3; k++) {
assertEquals(shuffled.get(k).toString(), compared.get(k).toString().trim());
}
}
}
}
@Test
public void testReplacementBigInteger() {
int size = 23000000;
int prime = 198491329;
// System.out.println((long) Integer.MAX_VALUE * Integer.MAX_VALUE);
for (long i = 0; i < size; i++) {
int result = (int) (((i + 1) * prime) % size);
if (result == i || (result < 0)) {
System.out.println(i + " => " + result);
fail("result is identical");
}
}
}
@Test
public void testOneColumnBigInteger() {
int partition = 10000;
int size = 1000000;
List<List<String>> id = new ArrayList<List<String>>();
List<String> idc = new ArrayList<String>();
idc.add("id");
id.add(idc);
Queue<List<List<Object>>> result = new ConcurrentLinkedQueue<List<List<Object>>>();
ShufflingService service = new ShufflingService(id, idc);
ShufflingHandler handler = new ShufflingHandler(service, result);
service.setShufflingHandler(handler);
service.setSeperationSize(partition);
for (int i = 0; i < size; i++) {
List<Object> row = Arrays.asList((Object) (i + ""));
service.addOneRow(row);
}
service.setHasFinished(true);
Assert.assertEquals(size / partition, result.size());
for (int i = 0; i < result.size(); i++) {
List<List<Object>> rows = result.poll();
for (int position = 0; position < rows.size(); position++) {
int item = Integer.parseInt(rows.get(position).get(0).toString());
// the partition is good
Assert.assertTrue(item < partition * (i + 1));
Assert.assertTrue(item >= partition * i);
// the position changes
Assert.assertTrue(item != position);
}
}
}
@Test
@Ignore
public void testOneColumnBigIntegerHasModulo() {
int partition = 100000;
int size = 10000999;
List<List<String>> id = new ArrayList<List<String>>();
List<String> idc = new ArrayList<String>();
idc.add("id");
id.add(idc);
Queue<List<List<Object>>> result = new ConcurrentLinkedQueue<List<List<Object>>>();
ShufflingService service = new ShufflingService(id, idc);
ShufflingHandler handler = new ShufflingHandler(service, result);
service.setShufflingHandler(handler);
service.setSeperationSize(partition);
service.setSeperationSize(partition);
for (int i = 0; i < size; i++) {
List<Object> row = Arrays.asList((Object) (i + ""));
service.addOneRow(row);
}
service.setHasFinished(true);
Assert.assertEquals(size / partition, result.size() - 1);
for (int i = 0; i < size / partition; i++) {
List<List<Object>> rows = result.poll();
for (int position = 0; position < rows.size(); position++) {
int item = Integer.parseInt(rows.get(position).get(0).toString());
// the partition is good
Assert.assertTrue(item < partition * (i + 1));
Assert.assertTrue(item >= partition * i);
// the position changes
Assert.assertTrue(item != position);
}
}
// test last rows
List<List<Object>> rows = result.poll();
for (int position = 0; position < rows.size(); position++) {
int item = Integer.parseInt(rows.get(position).get(0).toString());
// the partition is good
Assert.assertTrue(item < size);
Assert.assertTrue(item >= partition * (size / partition));
// the position changes
Assert.assertTrue(item != position);
}
}
@Test
public void testshuffleColumnsData1000() throws InterruptedException {
Queue<List<List<Object>>> result = new ConcurrentLinkedQueue<List<List<Object>>>();
ShufflingService service = new ShufflingService(columns, allColumns);
service.setRandomSeed(77);
ShufflingHandler handler = new ShufflingHandler(service, result);
service.setShufflingHandler(handler);
service.setSeperationSize(100000);
List<List<Object>> fileData = generation.getTableValue(GenerateData.SHUFFLING_DATA_PATH);
List<List<Object>> fileDataCompared = generation.getTableValue(file1000Compared);
long time1 = System.currentTimeMillis();
service.setRows(fileData);
long time2 = System.currentTimeMillis();
service.setHasFinished(true);
System.out.println("1000 line generation time " + (time2 - time1));
Assert.assertEquals(1, result.size());
List<Object> idColumnSL = new ArrayList<Object>();
List<Object> firstNameColumnSL = new ArrayList<Object>();
List<Object> emailSL = new ArrayList<Object>();
List<Object> citySL = new ArrayList<Object>();
List<Object> zipSL = new ArrayList<Object>();
List<Object> idColumnL = new ArrayList<Object>();
List<Object> firstNameColumnL = new ArrayList<Object>();
List<Object> emailL = new ArrayList<Object>();
List<Object> cityL = new ArrayList<Object>();
List<Object> zipL = new ArrayList<Object>();
// Initialize the shuffled data
for (int group = 0; group < result.size(); group++) {
List<List<Object>> rows = result.poll();
// Compare the shuffling results' positions
for (int i = 0; i < rows.size(); i++) {
List<Object> shuffled = rows.get(i);
List<Object> compared = fileDataCompared.get(i);
for (int j = 0; j < 4; j++) {
assertEquals(shuffled.get(j).toString(), compared.get(j).toString().trim());
}
}
for (List<Object> row : rows) {
Object idS = row.get(0);
Object firstNameS = row.get(1);
Object emailS = row.get(3);
Object cityS = row.get(6);
Object zipS = row.get(7);
idColumnSL.add(idS);
firstNameColumnSL.add(firstNameS);
emailSL.add(emailS);
citySL.add(cityS);
zipSL.add(zipS);
}
}
// Initialize the original data set
for (int i = 0; i < fileData.size(); i++) {
Object id = fileData.get(i).get(0);
Object firstName = fileData.get(i).get(1);
Object email = fileData.get(i).get(3);
Object city = fileData.get(i).get(6);
Object zip = fileData.get(i).get(7);
idColumnL.add(id);
firstNameColumnL.add(firstName);
emailL.add(email);
cityL.add(city);
zipL.add(zip);
}
for (int i = 0; i < fileData.size(); i++) {
// test whether all email address retain
Assert.assertTrue(emailSL.contains(emailL.get(i)));
// test whether all name retain
Assert.assertTrue(firstNameColumnSL.contains(firstNameColumnSL.get(i)));
Object oid = idColumnL.get(i);
Object nid = idColumnSL.get(i);
Object oemail = emailL.get(i);
Object nemail = emailSL.get(i);
Object oName = firstNameColumnL.get(i);
// test whether email and id information have all changed
Assert.assertTrue(!oid.equals(nid) || !oemail.equals(nemail));
// test whether the id and first name's relation retains
int sIdIndex = idColumnSL.indexOf(oid);
Object sFirstName = firstNameColumnSL.get(sIdIndex);
Assert.assertTrue(oName.equals(sFirstName));
}
}
@Test
public void testshuffleColumnsData5000() throws InterruptedException {
Queue<List<List<Object>>> result = new ConcurrentLinkedQueue<List<List<Object>>>();
ShufflingService service = new ShufflingService(columns, allColumns);
ShufflingHandler handler = new ShufflingHandler(service, result);
service.setShufflingHandler(handler);
service.setSeperationSize(100000);
List<List<Object>> fileData = generation.getTableValue(file5000);
long time1 = System.currentTimeMillis();
service.setRows(fileData);
long time2 = System.currentTimeMillis();
service.setHasFinished(true);
Thread.sleep(100);
System.out.println("5000 line generation time " + (time2 - time1));
Assert.assertEquals(1, result.size());
List<Object> idColumnSL = new ArrayList<Object>();
List<Object> firstNameColumnSL = new ArrayList<Object>();
List<Object> emailSL = new ArrayList<Object>();
List<Object> citySL = new ArrayList<Object>();
List<Object> zipSL = new ArrayList<Object>();
List<Object> idColumnL = new ArrayList<Object>();
List<Object> firstNameColumnL = new ArrayList<Object>();
List<Object> emailL = new ArrayList<Object>();
List<Object> cityL = new ArrayList<Object>();
List<Object> zipL = new ArrayList<Object>();
// Initialize the shuffled data
for (int group = 0; group < result.size(); group++) {
List<List<Object>> rows = result.poll();
for (List<Object> row : rows) {
Object idS = row.get(0);
Object firstNameS = row.get(1);
Object emailS = row.get(3);
Object cityS = row.get(6);
Object zipS = row.get(7);
idColumnSL.add(idS);
firstNameColumnSL.add(firstNameS);
emailSL.add(emailS);
citySL.add(cityS);
zipSL.add(zipS);
}
}
// Initialize the original data set
for (int i = 0; i < fileData.size(); i++) {
Object id = fileData.get(i).get(0);
Object firstName = fileData.get(i).get(1);
Object email = fileData.get(i).get(3);
Object city = fileData.get(i).get(6);
Object zip = fileData.get(i).get(7);
idColumnL.add(id);
firstNameColumnL.add(firstName);
emailL.add(email);
cityL.add(city);
zipL.add(zip);
}
for (int i = 0; i < fileData.size(); i++) {
// test whether all email address retain
Assert.assertTrue(emailSL.contains(emailL.get(i)));
// test whether all name retain
Assert.assertTrue(firstNameColumnSL.contains(firstNameColumnSL.get(i)));
Object oid = idColumnL.get(i);
Object nid = idColumnSL.get(i);
Object oemail = emailL.get(i);
Object nemail = emailSL.get(i);
Object oName = firstNameColumnL.get(i);
// test whether email and id information have all changed
Assert.assertTrue(!oid.equals(nid) || !oemail.equals(nemail));
// test whether the id and first name's relation retains
int sIdIndex = idColumnSL.indexOf(oid);
Object sFirstName = firstNameColumnSL.get(sIdIndex);
Assert.assertTrue(oName.equals(sFirstName));
}
}
@Test
@Ignore
public void testshuffleColumnsData50000() {
Queue<List<List<Object>>> result = new ConcurrentLinkedQueue<List<List<Object>>>();
ShufflingService service = new ShufflingService(columns, allColumns);
ShufflingHandler handler = new ShufflingHandler(service, result);
service.setShufflingHandler(handler);
service.setSeperationSize(100000);
List<List<Object>> fileData = generation.getTableValue(file50000);
long time1 = System.currentTimeMillis();
service.setRows(fileData);
long time2 = System.currentTimeMillis();
service.setHasFinished(true);
System.out.println("50000 line generation time " + (time2 - time1));
Assert.assertEquals(1, result.size());
System.out.println("result size " + result.size());
long time3 = System.currentTimeMillis();
List<Object> idColumnSL = new ArrayList<Object>();
List<Object> firstNameColumnSL = new ArrayList<Object>();
List<Object> emailSL = new ArrayList<Object>();
List<Object> citySL = new ArrayList<Object>();
List<Object> zipSL = new ArrayList<Object>();
List<Object> idColumnL = new ArrayList<Object>();
List<Object> firstNameColumnL = new ArrayList<Object>();
List<Object> emailL = new ArrayList<Object>();
List<Object> cityL = new ArrayList<Object>();
List<Object> zipL = new ArrayList<Object>();
// Initialize the shuffled data
for (int group = 0; group < result.size(); group++) {
List<List<Object>> rows = result.poll();
for (List<Object> row : rows) {
Object idS = row.get(0);
Object firstNameS = row.get(1);
Object emailS = row.get(3);
Object cityS = row.get(6);
Object zipS = row.get(7);
idColumnSL.add(idS);
firstNameColumnSL.add(firstNameS);
emailSL.add(emailS);
citySL.add(cityS);
zipSL.add(zipS);
}
}
// Initialize the original data set
for (int i = 0; i < fileData.size(); i++) {
Object id = fileData.get(i).get(0);
Object firstName = fileData.get(i).get(1);
Object email = fileData.get(i).get(3);
Object city = fileData.get(i).get(6);
Object zip = fileData.get(i).get(7);
idColumnL.add(id);
firstNameColumnL.add(firstName);
emailL.add(email);
cityL.add(city);
zipL.add(zip);
}
for (int i = 0; i < fileData.size(); i++) {
// test whether all email address retain
Assert.assertTrue(emailSL.contains(emailL.get(i)));
// test whether all name retain
Assert.assertTrue(firstNameColumnSL.contains(firstNameColumnSL.get(i)));
Object oid = idColumnL.get(i);
Object nid = idColumnSL.get(i);
Object oemail = emailL.get(i);
Object nemail = emailSL.get(i);
Object oName = firstNameColumnL.get(i);
// test whether email and id information have all changed
Assert.assertTrue(!oid.equals(nid) || !oemail.equals(nemail));
// test whether the id and first name's relation retains
int sIdIndex = idColumnSL.indexOf(oid);
Object sFirstName = firstNameColumnSL.get(sIdIndex);
Assert.assertTrue(oName.equals(sFirstName));
}
long time4 = System.currentTimeMillis();
System.out.println("50000 line generation time " + (time4 - time3));
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2015 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.semantic.index.utils.optimizer;
import java.util.HashSet;
import java.util.Set;
public class AirportOptimizer implements CategoryOptimizer {
@Override
public Set<String> optimize(String[] inputValues) {
Set<String> synAirportNames = new HashSet<String>();
for (String input : inputValues) {
if (input == null || input.trim().length() == 0) {
continue;
}
synAirportNames.add(input);
// 1. create syn without the word in parenthesis
if (input.contains("(")) {
String subStrWithOutParenthesis = input.substring(0, input.indexOf("(")).trim()
+ input.substring(input.indexOf(")") + 1);
synAirportNames.add(subStrWithOutParenthesis);
}
// 2. create syn for the items with the keyword words, e.g. "Airport", "Heliport", "Field"
if (input.contains(" Airport")) {// 2.1 create syn for the items with the word "Airport"
if (input.contains("International Airport")) {
synAirportNames.add(input.replaceAll("(?i)" + java.util.regex.Pattern.quote(" International Airport"), ""));
} else if (input.contains("Municipal Airport")) {
synAirportNames.add(input.replaceAll("(?i)" + java.util.regex.Pattern.quote(" Municipal Airport"), ""));
} else if (input.contains("Regional Airport")) {
synAirportNames.add(input.replaceAll("(?i)" + java.util.regex.Pattern.quote(" Regional Airport"), ""));
} else if (input.contains("County Airport")) {
synAirportNames.add(input.replaceAll("(?i)" + java.util.regex.Pattern.quote(" County Airport"), ""));
}
synAirportNames.add(input.replaceAll("(?i)" + java.util.regex.Pattern.quote(" Airport"), ""));
}
if (input.contains(" Heliport")) {// 2.2 create syn for the items with the word "Heliport"
synAirportNames.add(input.replaceAll("(?i)" + java.util.regex.Pattern.quote(" Heliport"), ""));
}
if (input.contains(" Field")) {// 2.3 create syn for the items with the word "Field"
synAirportNames.add(input.replaceAll("(?i)" + java.util.regex.Pattern.quote(" Field"), ""));
}
}
return synAirportNames;
}
}
<file_sep>package org.talend.dataquality.datamasking.functions;
import static org.junit.Assert.assertEquals;
import java.util.Locale;
import java.util.Random;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
/**
* Created by jdenantes on 21/09/16.
*/
public class GenerateUniquePhoneNumberUsTest {
private String output;
private AbstractGenerateUniquePhoneNumber gnu = new GenerateUniquePhoneNumberUs();
private GeneratePhoneNumberUS gpn = new GeneratePhoneNumberUS();
private static PhoneNumberUtil GOOGLE_PHONE_UTIL = PhoneNumberUtil.getInstance();
@Before
public void setUp() throws Exception {
gnu.setRandom(new Random(42));
gnu.setKeepFormat(true);
}
@Test
public void testKeepInvalidPatternTrue() {
gnu.setKeepInvalidPattern(true);
output = gnu.generateMaskedRow(null);
assertEquals(null, output);
output = gnu.generateMaskedRow("");
assertEquals("", output);
output = gnu.generateMaskedRow("AHDBNSKD");
assertEquals("AHDBNSKD", output);
}
@Test
public void testKeepInvalidPatternFalse() {
gnu.setKeepInvalidPattern(false);
output = gnu.generateMaskedRow(null);
assertEquals(null, output);
output = gnu.generateMaskedRow("");
assertEquals("", output);
output = gnu.generateMaskedRow("AHDBNSKD");
assertEquals("AHDBNSKD", output);
}
@Test
public void testGood1() {
output = gnu.generateMaskedRow("35-6/42-5/9 865");
assertEquals("35-6/41-6/5 815", output);
}
@Test
public void testGood2() {
gnu.setKeepFormat(false);
// with spaces
output = gnu.generateMaskedRow("356-425-9865");
assertEquals("3564165815", output);
}
@Test
public void testWrongSsnFieldNumber() {
gnu.setKeepInvalidPattern(false);
// with two 1 at the fifth and the sixth position
output = gnu.generateMaskedRow("465 311 9856");
assertEquals("308 075 2722", output);
}
@Test
public void testValidAfterMasking() {
gnu.setKeepFormat(false);
String input;
String output;
for (int i = 0; i < 100; i++) {
gpn.setRandom(new Random());
input = gpn.doGenerateMaskedField(null);
if (isValidPhoneNumber(input) && !(input.charAt(5) == '1' && input.charAt(6) == '1')) {
for (int j = 0; j < 1000; j++) {
long rgenseed = System.nanoTime();
gnu.setRandom(new Random(rgenseed));
output = gnu.generateMaskedRow(input);
Assert.assertTrue("Don't worry, report this line to Data Quality team: with a seed = " + rgenseed + ", "
+ input + " is valid, but after the masking " + output + " is not valid", isValidPhoneNumber(output));
}
}
}
}
/**
*
* whether a phone number is valid for a certain region.
*
* @param data the data that we want to validate
* @return a boolean that indicates whether the number is of a valid pattern
*/
public static boolean isValidPhoneNumber(Object data) {
Phonenumber.PhoneNumber phonenumber = null;
try {
phonenumber = GOOGLE_PHONE_UTIL.parse(data.toString(), Locale.US.getCountry());
} catch (Exception e) {
return false;
}
return GOOGLE_PHONE_UTIL.isValidNumberForRegion(phonenumber, Locale.US.getCountry());
}
}
<file_sep>Regular expressions
-----------
| Name | Label | Description | Completeness |
|---------------|:-------------:|:-----------:|:-----------:|
|`WEB_DOMAIN`|Web Domain|Website domain|true|
|`US_SSN`|US Social Security Number|US social security number|true|
|`EMAIL`|Email|Email address|true|
|`BG_VAT_NUMBER`|BG VAT Number|Bulgaria VAT number|true|
|`URL`|URL|Website URL|true|
|`GEO_COORDINATE`|Geographic coordinate|Longitude or latitude coordinates with at least meter precision|true|
|`MAC_ADDRESS`|MAC Address|MAC Address.|true|
|`EN_WEEKDAY`|EN Weekday|Weekday or their abbreviation|true|
|`FR_POSTAL_CODE`|FR Postal Code|French postal code|true|
|`DE_PHONE`|DE Phone|German phone number|true|
|`VISA_CARD`|Visa Card|Visa card|true|
|`MASTERCARD`|MasterCard|MasterCard|true|
|`FR_SSN`|FR Social Security Number|French social security number|true|
|`ISBN_10`|ISBN-10|International Standard Book Number 10 digits. Such as ISBN 2-711-79141-6|true|
|`SE_SSN`|SE Social Security Number|The personal identity number (Swedish: personnummer) is the Swedish national identification number.|true|
|`ISBN_13`|ISBN-13|International Standard Book Number 13 digits.|true|
|`UK_SSN`|UK Social Security Number|National Insurance number, generally called an NI Number (NINO)|true|
|`EN_MONEY_AMOUNT`|Money Amount (EN)|Amount of money in English format|true|
|`BANK_ROUTING_TRANSIT_NUMBER`|Bank Routing Transit Number|Bank routing transit number|true|
|`AMEX_CARD`|Amex Card|American Express card|true|
|`UK_POSTAL_CODE`|UK Postal Code|UK postal code|true|
|`EN_MONTH`|EN Month|Month in English|true|
|`IPv6_ADDRESS`|IPv6 Address|IPv6 address|true|
|`MAILTO_URL`|MailTo URL|MAIL TO URL|true|
|`US_PHONE`|US Phone|American phone number|true|
|`FR_CODE_COMMUNE_INSEE`|FR Insee Code|French Insee code of cities with Corsica and colonies|true|
|`IBAN`|IBAN|IBAN|true|
|`GEO_COORDINATES_DEG`|Geographic Coordinates (degree)|Latitude and longitude coordinates separated by a comma in the form: N 0:59:59.99,E 0:59:59.99|true|
|`DATA_URL`|Data URL|DATA URL|true|
|`IPv4_ADDRESS`|IPv4 Address|IPv4 address|true|
|`FR_MONEY_AMOUNT`|Money Amount (FR)|Amount of money in French format|true|
|`EN_MONTH_ABBREV`|EN Month Abbrev|Month English abbreviation|true|
|`FR_PHONE`|FR Phone|French phone number|true|
|`GEO_COORDINATES`|Geographic Coordinates|Google Maps style GPS Decimal format|true|
|`US_STATE`|US State|US states|true|
|`FILE_URL`|File URL|FILE URL|true|
|`US_STATE_CODE`|US State Code|US state code|true|
|`COLOR_HEX_CODE`|Color Hex Code|Color hexadecimal code|true|
|`FR_VAT_NUMBER`|FR VAT Number|French VAT number|true|
|`HDFS_URL`|HDFS URL|HDFS URL|true|
|`DE_POSTAL_CODE`|DE Postal Code|German postal code|true|
|`UK_PHONE`|UK Phone|UK phone number|true|
|`BE_POSTAL_CODE`|BE Postal Code|Belgium postal code|true|
|`AT_VAT_NUMBER`|AT VAT Number|Austria VAT number|true|
|`SEDOL`|SEDOL|Stock Exchange Daily Official List|true|
|`PASSPORT`|Passport|Passport number|true|
|`US_POSTAL_CODE`|US Postal Code|US postal code|true|
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* created by jgonzalez on 19 juin 2015. This function works like GenerateFromList, the difference is that the parameter
* is now a String holding the path to a file in the user’s computer.
*
*/
public abstract class GenerateFromFile<T> extends Function<T> {
private static final long serialVersionUID = 1556057898878709265L;
private static final Logger LOGGER = Logger.getLogger(GenerateFromFile.class);
protected List<T> genericTokens = new ArrayList<T>();
@Override
public void parse(String extraParameter, boolean keepNullValues, Random rand) {
super.parse(extraParameter, keepNullValues, rand);
for (int i = 0; i < parameters.length; ++i) {
try {
genericTokens.add(getOutput(parameters[i]));
} catch (NumberFormatException e) {
LOGGER.info("The parameter " + parameters[i] + " can't be parsed in the required type.");
}
}
}
protected abstract T getOutput(String string);
@Override
protected T doGenerateMaskedField(T t) {
if (!genericTokens.isEmpty()) {
return genericTokens.get(rnd.nextInt(genericTokens.size()));
} else {
return getDefaultOutput();
}
}
protected abstract T getDefaultOutput();
}
<file_sep>package org.talend.dataquality.datamasking.functions;
import static org.junit.Assert.assertEquals;
import java.util.Random;
import org.junit.Assert;
import org.junit.Test;
public class MaskEmailLocalPartByXTest {
private String output;
private String mail = "<EMAIL>";
private String spemail = "<EMAIL>";
private MaskEmailLocalPartByX maskEmailLocalPartByX = new MaskEmailLocalPartByX();
@Test
public void testEmpty() {
maskEmailLocalPartByX.setKeepEmpty(true);
output = maskEmailLocalPartByX.generateMaskedRow("");
assertEquals("", output); //$NON-NLS-1$
}
@Test
public void test1Good() {
maskEmailLocalPartByX.parse("", false, new Random());
output = maskEmailLocalPartByX.generateMaskedRow(mail);
Assert.assertEquals("<EMAIL>", output);
}
@Test
public void testNullParameter() {
maskEmailLocalPartByX.parse(null, false, new Random());
output = maskEmailLocalPartByX.generateMaskedRow(mail);
Assert.assertEquals("<EMAIL>", output);
}
@Test
public void testSpecialEmail() {
maskEmailLocalPartByX.parse("", true, new Random(Long.valueOf(12345678)));
output = maskEmailLocalPartByX.generateMaskedRow(spemail);
Assert.assertEquals("<EMAIL>", output);
}
@Test
public void test2WithInput() {
maskEmailLocalPartByX.parse("hehe", false, new Random());
output = maskEmailLocalPartByX.generateMaskedRow(mail);
Assert.assertEquals("<EMAIL>", output);
}
@Test
public void test2WithOneCharacter() {
maskEmailLocalPartByX.parse("A", false, new Random());
output = maskEmailLocalPartByX.generateMaskedRow(mail);
Assert.assertEquals("<EMAIL>", output);
}
@Test
public void test2WithOneDigit() {
maskEmailLocalPartByX.parse("1", false, new Random());
output = maskEmailLocalPartByX.generateMaskedRow(mail);
Assert.assertEquals("<EMAIL>", output);
}
@Test
public void test3NullEmail() {
maskEmailLocalPartByX.parse("", false, new Random());
output = maskEmailLocalPartByX.generateMaskedRow(null);
Assert.assertTrue(output.isEmpty());
}
@Test
public void test3KeepNullEmail() {
maskEmailLocalPartByX.parse("", true, new Random());
output = maskEmailLocalPartByX.generateMaskedRow(null);
Assert.assertTrue(output == null);
}
@Test
public void test4EmptyEmail() {
maskEmailLocalPartByX.parse("", false, new Random());
output = maskEmailLocalPartByX.generateMaskedRow("");
Assert.assertTrue(output.isEmpty());
}
@Test
public void test5WrongFormat() {
maskEmailLocalPartByX.parse("", false, new Random());
output = maskEmailLocalPartByX.generateMaskedRow("hehe");
Assert.assertEquals("XXXX", output);
}
}
<file_sep>package org.talend.dataquality.datamasking.functions;
import java.util.Random;
public class KeepLastDigitsAndReplaceOtherDigits extends Function<String> {
private int integerParam = 0;
@Override
public void parse(String extraParameter, boolean keepNullValues, Random rand) {
super.parse(extraParameter, keepNullValues, rand);
if (CharactersOperationUtils.validParameters1Number(parameters))
integerParam = Integer.parseInt(parameters[0]);
else
throw new IllegalArgumentException("The parameter is not a positive integer.");
}
@Override
protected String doGenerateMaskedField(String str) {
if (str != null && !EMPTY_STRING.equals(str) && integerParam >= 0) {
String s = str.trim();
StringBuilder sb = new StringBuilder(EMPTY_STRING);
if (integerParam > s.length()) {
return str;
}
if (integerParam < s.length()) {
StringBuilder end = new StringBuilder(EMPTY_STRING);
for (int i = s.length() - 1; i >= s.length() - integerParam; --i) {
if (i < 0) {
break;
}
end.append(s.charAt(i));
if (!Character.isDigit(s.charAt(i))) {
integerParam++;
}
}
for (int i = 0; i < s.length() - integerParam; ++i) {
if (i < 0) {
break;
}
if (Character.isDigit(s.charAt(i))) {
sb.append(rnd.nextInt(9));
} else {
sb.append(s.charAt(i));
}
}
sb.append(end.reverse());
return sb.toString();
}
}
return EMPTY_STRING;
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import static org.junit.Assert.assertEquals;
import java.util.Random;
import org.junit.Before;
import org.junit.Test;
/**
* @author dprot
*/
public class GenerateUniqueSsnChnTest {
private String output;
private AbstractGenerateUniqueSsn gnf = new GenerateUniqueSsnChn();
@Before
public void setUp() throws Exception {
gnf.setRandom(new Random(42));
gnf.setKeepFormat(true);
}
@Test
public void testEmpty() {
gnf.setKeepEmpty(true);
output = gnf.generateMaskedRow("");
assertEquals("", output); //$NON-NLS-1$
}
@Test
public void testKeepInvalidPatternTrue() {
gnf.setKeepInvalidPattern(true);
output = gnf.generateMaskedRow(null);
assertEquals(null, output);
output = gnf.generateMaskedRow("");
assertEquals("", output);
output = gnf.generateMaskedRow("AHDBNSKD");
assertEquals("AHDBNSKD", output);
}
@Test
public void testKeepInvalidPatternFalse() {
gnf.setKeepInvalidPattern(false);
output = gnf.generateMaskedRow(null);
assertEquals(null, output);
output = gnf.generateMaskedRow("");
assertEquals(null, output);
output = gnf.generateMaskedRow("AHDBNSKD");
assertEquals(null, output);
}
@Test
public void testGood() {
output = gnf.generateMaskedRow("64010119520414123X");
assertEquals("150923205211538130", output);
}
@Test
public void testGoodSpace() {
// with spaces
output = gnf.generateMaskedRow("231202 19510411 456 4");
assertEquals("410422 19840319 136 X", output);
}
@Test
public void testGoodLeapYear() {
// leap year for date of birth
output = gnf.generateMaskedRow("232723 19960229 459 4");
assertEquals("445322 19370707 229 X", output);
}
@Test
public void testWrongSsnFieldNumber() {
gnf.setKeepInvalidPattern(false);
// without a number
output = gnf.generateMaskedRow("6401011920414123X");
assertEquals(null, output);
}
@Test
public void testWrongSsnFieldLetter() {
gnf.setKeepInvalidPattern(false);
// with a wrong letter
output = gnf.generateMaskedRow("640101195204141C3X");
assertEquals(null, output);
}
@Test
public void testWrongSsnFieldRegion() {
gnf.setKeepInvalidPattern(false);
// With an invalid region code
output = gnf.generateMaskedRow("11000119520414123X");
assertEquals(null, output);
}
@Test
public void testWrongSsnFieldBirth() {
gnf.setKeepInvalidPattern(false);
// With an invalid date of birth (wrong year)
output = gnf.generateMaskedRow("64010118520414123X");
assertEquals(null, output);
}
@Test
public void testWrongSsnFieldBirth2() {
gnf.setKeepInvalidPattern(false);
// With an invalid date of birth (day not existing)
output = gnf.generateMaskedRow("64010119520434123X");
assertEquals(null, output);
}
@Test
public void testWrongSsnFieldBirth3() {
gnf.setKeepInvalidPattern(false);
// With an invalid date of birth (29th February in a non-leap year)
output = gnf.generateMaskedRow("64010119530229123X");
assertEquals(null, output);
}
}
<file_sep>package org.talend.dataquality.datamasking.shuffling;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.log4j.Logger;
/**
* This class is a handler of {@link ShuffleColumn} who has an internal class implemented runnable to call the shuffle
* method in the {@link ShuffleColumn} DOC qzhao class global comment.
*/
public class ShufflingHandler {
private static final Logger LOGGER = Logger.getLogger(ShufflingHandler.class);
protected ShufflingService shufflingService;
protected AsynchronizedOutputRunnable runnable = null;
protected Queue<List<List<Object>>> resultQueue;
protected Thread t = null;
/**
* Constructor
*
* @param shufflingService ShufflingService object
* @param resultQueue a queue with separated table
*/
public ShufflingHandler(ShufflingService shufflingService, Queue<List<List<Object>>> resultQueue) {
super();
this.shufflingService = shufflingService;
this.resultQueue = (resultQueue == null) ? new ConcurrentLinkedQueue<List<List<Object>>>() : resultQueue;
}
class AsynchronizedOutputRunnable implements Runnable {
@Override
public void run() {
try {
ConcurrentLinkedQueue<Future<List<List<Object>>>> queue = shufflingService.getConcurrentQueue();
while (!shufflingService.hasFinished() || !queue.isEmpty()) {
if (queue.isEmpty()) {
Thread.sleep(100);
continue;
}
Future<List<List<Object>>> future = queue.poll();
List<List<Object>> rows = future.get();
resultQueue.add(rows);
}
} catch (InterruptedException | ExecutionException | NullPointerException e) {
LOGGER.error(e.getMessage(), e);
shufflingService.shutDown();
}
}
}
public void start() {
if (runnable == null) {
runnable = new AsynchronizedOutputRunnable();
}
t = new Thread(runnable);
t.start();
}
public void join() {
try {
t.join();
} catch (InterruptedException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import static org.junit.Assert.assertEquals;
import java.util.Random;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
/**
* DOC qzhao class global comment. Detailled comment
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MaskFullEmailDomainByXTest {
private String output;
private String mail = "<EMAIL>";
private String spemail = "<EMAIL>";
private String spemails = "<EMAIL>";
private MaskFullEmailDomainByX maskEmailDomainByX = new MaskFullEmailDomainByX();
@Test
public void testEmpty() {
maskEmailDomainByX.setKeepEmpty(true);
output = maskEmailDomainByX.generateMaskedRow("");
assertEquals("", output); //$NON-NLS-1$
}
@Test
public void test1Good() {
maskEmailDomainByX.parse("", false, new Random());
output = maskEmailDomainByX.generateMaskedRow(mail);
Assert.assertEquals("hehe.hehe@XXXXX.XXX.XX", output);
}
@Test
public void testReal() {
maskEmailDomainByX.parse("", true, new Random(Long.valueOf(12345678)));
output = maskEmailDomainByX.generateMaskedRow("<EMAIL>");
Assert.assertEquals("dewitt.julio@XXXXXXX.XXX", output);
}
@Test
public void testSpecialEmail() {
maskEmailDomainByX.parse("", true, new Random(Long.valueOf(12345678)));
output = maskEmailDomainByX.generateMaskedRow(spemail);
Assert.assertEquals("hehe@XXXXXXXXXXXXXXXX.XX", output);
}
@Test
public void testSpecialEmails() {
maskEmailDomainByX.parse("", true, new Random(Long.valueOf(12345678)));
output = maskEmailDomainByX.generateMaskedRow(spemails);
Assert.assertEquals("hehe@XXXXXXXXXXXXXXXXX.XXXXXXX.XX", output);
}
@Test
public void test2WithInput() {
maskEmailDomainByX.parse("hehe", false, new Random());
output = maskEmailDomainByX.generateMaskedRow(mail);
Assert.assertEquals("hehe.hehe@XXXXX.XXX.XX", output);
}
@Test
public void test2WithOneCharacter() {
maskEmailDomainByX.parse("A", false, new Random());
output = maskEmailDomainByX.generateMaskedRow(mail);
Assert.assertEquals("hehe.hehe@AAAAA.AAA.AA", output);
}
@Test
public void test2WithOneDigit() {
maskEmailDomainByX.parse("1", false, new Random());
output = maskEmailDomainByX.generateMaskedRow(mail);
Assert.assertEquals("hehe.hehe@XXXXX.XXX.XX", output);
}
@Test
public void test3NullEmail() {
maskEmailDomainByX.parse("", false, new Random());
output = maskEmailDomainByX.generateMaskedRow(null);
Assert.assertTrue(output.isEmpty());
}
@Test
public void test3KeepNullEmail() {
maskEmailDomainByX.parse("", true, new Random());
output = maskEmailDomainByX.generateMaskedRow(null);
Assert.assertTrue(output == null);
}
@Test
public void test4EmptyEmail() {
maskEmailDomainByX.parse("", false, new Random());
output = maskEmailDomainByX.generateMaskedRow("");
Assert.assertTrue(output.isEmpty());
}
@Test
public void test5WrongFormat() {
maskEmailDomainByX.parse("", false, new Random());
output = maskEmailDomainByX.generateMaskedRow("hehe");
Assert.assertEquals("XXXX", output);
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import static org.junit.Assert.assertEquals;
import java.util.Random;
import org.junit.Test;
/**
* created by jgonzalez on 29 juin 2015 Detailled comment
*
*/
public class KeepFirstCharsStringTest {
private String output;
private String input = "a1b2c3d456"; //$NON-NLS-1$
private KeepFirstCharsString kfag = new KeepFirstCharsString();
@Test
public void testEmpty() {
kfag.setKeepEmpty(true);
output = kfag.generateMaskedRow("");
assertEquals("", output); //$NON-NLS-1$
}
@Test
public void testGood() {
kfag.parse("3", false, new Random(42));
output = kfag.generateMaskedRow(input);
assertEquals("a1b8h0m075", output); //$NON-NLS-1$
}
@Test
public void testDummyGood() {
kfag.parse("15", false, new Random(542));
output = kfag.generateMaskedRow(input);
assertEquals(input, output);
}
@Test
public void testParameters() {
kfag.parse("5,8", false, new Random(542));
output = kfag.generateMaskedRow(input);
assertEquals("a1b2c88888", output);
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
/**
* created by jgonzalez on 18 juin 2015. This class is an abstract class that
* all other functions extends. All the methods and fiels that all functions
* share are stored here.
*
*/
public abstract class Function<T> implements Serializable {
private static final long serialVersionUID = 6333987486134315822L;
private static final Logger LOGGER = Logger.getLogger(Function.class);
protected static final String EMPTY_STRING = ""; //$NON-NLS-1$
public static final String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //$NON-NLS-1$
public static final String LOWER = "abcdefghijklmnopqrstuvwxyz"; //$NON-NLS-1$
protected Random rnd = new Random();
protected String[] parameters;
protected boolean keepNull = false;
protected boolean keepInvalidPattern = false;
protected boolean keeEmpty = false;
protected boolean keepFormat = false;
protected static final Pattern patternSpace = Pattern.compile("\\s+");
protected static final Pattern nonDigits = Pattern.compile("\\D+");
/**
* setter for random
*
* @param rand
* The RandomWrapper.
* @deprecated use {@link setRandom()} instead
*/
public void setRandomWrapper(Random rand) {
setRandom(rand);
}
/**
* setter for random
*
* @param rand
* The java.util.Random instance.
*/
public void setRandom(Random rand) {
if (rand == null) {
rnd = new Random();
} else {
rnd = rand;
}
}
/**
* getter for random
*
* @return the random object
*/
public Random getRandom() {
return rnd;
}
/**
* DOC jgonzalez Comment method "setKeepNull". This function sets a boolean
* used to keep null values.
*
* @param keep
* The value of the boolean.
*/
public void setKeepNull(boolean keep) {
this.keepNull = keep;
}
public void setKeepFormat(boolean keep) {
this.keepFormat = keep;
}
public void setKeepEmpty(boolean empty) {
this.keeEmpty = empty;
}
public void setKeepInvalidPattern(boolean keepInvalidPattern) {
this.keepInvalidPattern = keepInvalidPattern;
}
/**
* DOC jgonzalez Comment method "parse". This function is called at the
* beginning of the job and parses the parameter. Moreover, it will call
* methods setKeepNull and setRandomWrapper
*
* @param extraParameter
* The parameter we try to parse.
* @param keepNullValues
* The parameter used for setKeepNull.
* @param rand
* The parameter used for setRandomMWrapper.
*/
public void parse(String extraParameter, boolean keepNullValues, Random rand) {
if (extraParameter != null) {
parameters = clean(extraParameter).split(","); //$NON-NLS-1$
if (parameters.length == 1) { // check if it's a path to a readable
// file
try {
List<String> aux = KeysLoader.loadKeys(parameters[0].trim());
parameters = new String[aux.size()];
int i = 0;
for (String str : aux)
parameters[i++] = str.trim();
} catch (IOException | NullPointerException e2) { // otherwise,
// we just
// get the
// parameter
LOGGER.debug("The parameter is not a path to a file.");
LOGGER.debug(e2);
parameters[0] = parameters[0].trim();
}
} else {
for (int i = 0; i < parameters.length; i++)
parameters[i] = parameters[i].trim();
}
}
setKeepNull(keepNullValues);
if (rand != null) {
setRandom(rand);
}
}
private String clean(String extraParameter) {
StringBuilder res = new StringBuilder(extraParameter.trim());
while (res.length() > 0 && res.charAt(0) == ',')
res.deleteCharAt(0);
while (res.length() > 0 && res.charAt(res.length() - 1) == ',')
res.deleteCharAt(res.length() - 1);
return res.toString();
}
public T generateMaskedRow(T t) {
if (t == null && keepNull) {
return null;
}
if (t != null && keeEmpty) {
if (String.valueOf(t).trim().isEmpty())
return t;
}
return doGenerateMaskedField(t);
}
/**
* @param strWithSpaces,
* resWithoutSpaces
* @return the res with spaces
*/
protected String insertFormatInString(String strWithSpaces, StringBuilder resWithoutSpaces) {
if (strWithSpaces == null || resWithoutSpaces == null)
return strWithSpaces;
for (int i = 0; i < strWithSpaces.length(); i++)
if (strWithSpaces.charAt(i) == ' ' || strWithSpaces.charAt(i) == '/' || strWithSpaces.charAt(i) == '-'
|| strWithSpaces.charAt(i) == '.')
resWithoutSpaces.insert(i, strWithSpaces.charAt(i));
return resWithoutSpaces.toString();
}
/**
* Remove all the spaces in the input string
*
* @param input
* @return
*/
protected String removeFormatInString(String input) {
return StringUtils.replaceEach(input, new String[] { " ", ".", "-", "/" }, new String[] { "", "", "", "" });
}
/**
* DOC jgonzalez Comment method "generateMaskedRow". This method applies a
* function on a field and returns the its new value.
*
* @param t
* The input value.
* @return A new value after applying the function.
*/
protected abstract T doGenerateMaskedField(T t);
}
<file_sep>package org.talend.dataquality.datamasking.shuffling;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
/**
* This class offers a shuffling service to manipulates the {@link ShuffleColumn} action and the
* {@link ShufflingHandler} action together.
*/
public class ShufflingService {
private static final Logger LOGGER = Logger.getLogger(ShufflingService.class);
protected ConcurrentLinkedQueue<Future<List<List<Object>>>> concurrentQueue = new ConcurrentLinkedQueue<Future<List<List<Object>>>>();
protected ShufflingHandler shufflingHandler;
protected List<List<String>> shuffledColumns;
protected List<String> allInputColumns;
protected List<String> partitionColumns;
protected ExecutorService executor;
protected long seed;
protected boolean hasSeed;
private List<List<Object>> rows = new ArrayList<List<Object>>();
private int seperationSize = Integer.MAX_VALUE;
private boolean hasLaunched = false;
private boolean hasFinished = false;
private boolean hasSubmitted = false;
/**
* Constructor without the partition choice
*
* @param shuffledColumns the 2D list of shuffled columns
* @param allInputColumns the list of all input columns name
* @throws IllegalArgumentException when the some columns in the shuffledColumns do not exist in the allInputColumns
*/
public ShufflingService(List<List<String>> shuffledColumns, List<String> allInputColumns) {
this(shuffledColumns, allInputColumns, null);
}
public ShufflingService(List<List<String>> shuffledColumns, List<String> allInputColumns, List<String> partitionColumns) {
this.shuffledColumns = shuffledColumns;
this.allInputColumns = allInputColumns;
this.partitionColumns = partitionColumns;
}
public void setShufflingHandler(ShufflingHandler shufflingHandler) {
this.shufflingHandler = shufflingHandler;
}
/**
* Executes a row list value.<br>
*
* The row is not executed immediately but is submitted to the {@link java.util.concurrent.ExecutorService}.<br>
* The results will be retrieved from the {@link java.util.concurrent.Future} objects which are appended to a
* {@link java.util.concurrent.ConcurrentLinkedQueue}<br>
*
* If the variable hasFinished equals true, it means this service has been closed. Tests whether the rows is empty
* or not. If the rows have still the values, submits those values to a callable process.<br>
*
* If the variable hasFinished equals false, adds the new value into the rows. Tests whether the rows' size equals
* the partition demand. When the size equals the partition size, submits those values to a callable process.<br>
*
* @param row
*/
protected synchronized void execute(List<Object> row) {
launcheHandler();
if (hasSubmitted) {
if (!rows.isEmpty()) {
executeFutureCall();
}
} else {
if (!row.isEmpty()) {
rows.add(row);
if (rows.size() == seperationSize) {
executeFutureCall();
}
}
}
}
/**
* Deep copies the rows value to another 2D list. Submits the rows' value to a callable process. Then submits the
* process to the executor.
*/
private void executeFutureCall() {
List<List<Object>> copyRow = deepCopyListTo(rows);
ShuffleColumn shuffle = new ShuffleColumn(shuffledColumns, allInputColumns, partitionColumns);
if (hasSeed) {
shuffle.setRandomSeed(seed);
}
Future<List<List<Object>>> future = executor.submit(new RowDataCallable<List<List<Object>>>(shuffle, copyRow));
concurrentQueue.add(future);
}
private void launcheHandler() {
if (!hasLaunched) {
shufflingHandler.start();
hasLaunched = true;
}
if (executor == null) {
executor = Executors.newCachedThreadPool();
} else {
if (executor.isShutdown()) {
throw new IllegalArgumentException("executor shutdown");
}
}
}
private synchronized List<List<Object>> deepCopyListTo(List<List<Object>> rows) {
List<List<Object>> copyRows = new ArrayList<List<Object>>(rows.size());
for (List<Object> row : rows) {
List<Object> copyRow = new ArrayList<Object>(row.size());
for (Object o : row) {
copyRow.add(o);
}
copyRows.add(copyRow);
}
rows.clear();
return copyRows;
}
public void setSeperationSize(int seperationSize2) {
this.seperationSize = seperationSize2;
}
/**
* Adds a new row in the waiting list and check the size of waiting list. When the waiting list fulfills the
* partition size then launches the shuffle algorithm.
*
* @param row a list of row data
*/
public void addOneRow(List<Object> row) {
execute(row);
}
public ConcurrentLinkedQueue<Future<List<List<Object>>>> getConcurrentQueue() {
return concurrentQueue;
}
/**
* Gets the hasFinished.
*
* @return hasFinished
*/
public boolean hasFinished() {
return hasFinished;
}
/**
* <ul>
* <li>First sets the hasSubmitted variable to be true and launches the execute() method with the global variable
* hasSubmitted equals true. This allows the resting rows to be submitted to a callable process.
* <li>To avoid the handler stopping scanning the result, lets the thread sleep 100 miliseconds. This allows the
* last callable job to stand by</li>
* <li>Sets the hasFinished variable true to announce the handler to finish the scan</li>
* </ul>
*
* @param hasFinished
*/
public void setHasFinished(boolean hasFinished) {
this.hasSubmitted = hasFinished;
execute(new ArrayList<Object>());
this.hasFinished = hasFinished;
shufflingHandler.join();
}
/**
* Sets the a table value directly by giving a 2D list.
*
* @param rows list of list of object
*/
public void setRows(List<List<Object>> rows) {
for (List<Object> row : rows) {
execute(row);
}
}
/**
* Shuts down the shuffling execution
*/
public void shutDown() {
if (executor != null) {
try {
executor.shutdown();
while (!concurrentQueue.isEmpty()) {
Thread.sleep(200);
}
executor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
public void setRandomSeed(long seed) {
this.hasSeed = true;
this.seed = seed;
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import static org.junit.Assert.assertEquals;
import java.util.Random;
import org.junit.Before;
import org.junit.Test;
/**
* created by jgonzalez on 29 juin 2015 Detailled comment
*
*/
public class KeepLastCharsStringTest {
private String output;
private String input = "123456"; //$NON-NLS-1$
private KeepLastCharsString klads = new KeepLastCharsString();
@Before
public void setUp() throws Exception {
klads.setRandom(new Random(42));
}
@Test
public void testEmpty() {
klads.setKeepEmpty(true);
output = klads.generateMaskedRow("");
assertEquals("", output); //$NON-NLS-1$
}
@Test
public void testGood() {
klads.parse("3", false, new Random(42));
output = klads.generateMaskedRow(input);
assertEquals("830456", output); //$NON-NLS-1$
// add msjian test for bug TDQ-11339: fix a "String index out of range: -1" exception
String inputa[] = new String[] { "test1234", "pp456", "<EMAIL>" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
String outputa[] = new String[] { "ahwm0734", "nq756", "<EMAIL>" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
klads.parse("2", false, new Random(42));
for (int i = 0; i < inputa.length; i++) {
output = klads.generateMaskedRow(inputa[i]);
assertEquals(outputa[i], output);
}
// TDQ-11339~
}
@Test
public void testDummyGood() {
klads.parse("7", false, new Random(42));
output = klads.generateMaskedRow(input);
assertEquals(input, output);
}
@Test
public void testParameter() {
klads.parse("3,i", false, new Random(42));
output = klads.generateMaskedRow(input);
assertEquals("iii456", output);
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Random;
import org.junit.Test;
/**
* created by jgonzalez on 25 juin 2015 Detailled comment
*
*/
public class ReplaceNumericIntegerTest {
private int input = 123;
private int output;
private ReplaceNumericInteger rni = new ReplaceNumericInteger();
@Test
public void testGood() {
rni.parse("6", false, new Random(42));
output = rni.generateMaskedRow(input);
assertEquals(666, output);
}
@Test
public void testNullParameter() {
rni.parse(null, false, new Random(42));
output = rni.generateMaskedRow(input);
assertEquals(830, output);
}
@Test
public void testWrongParameter() {
try {
rni.parse("r", false, new Random(42));
fail("should get exception with input " + rni.parameters); //$NON-NLS-1$
} catch (Exception e) {
assertTrue("expect illegal argument exception ", e instanceof IllegalArgumentException); //$NON-NLS-1$
}
output = rni.generateMaskedRow(input);
assertEquals(0, output);
}
@Test
public void testBad() {
try {
rni.parse("10", false, new Random(42));
fail("should get exception with input " + rni.parameters); //$NON-NLS-1$
} catch (Exception e) {
assertTrue("expect illegal argument exception ", e instanceof IllegalArgumentException); //$NON-NLS-1$
}
output = rni.generateMaskedRow(input);
assertEquals(0, output);
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.semantic.recognizer;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.talend.dataquality.semantic.classifier.ISubCategory;
import org.talend.dataquality.semantic.classifier.SemanticCategoryEnum;
/**
* created by talend on 2015-07-28 Detailled comment.
*/
public class CategoryFrequency implements Comparable<CategoryFrequency>, Serializable {
private static final long serialVersionUID = -3859689633174391877L;
String categoryId;
String categoryName;
float frequency;
long count;
/**
* CategoryFrequency constructor from a category.
*
* @param cat the category
*
* @deprecated
*/
public CategoryFrequency(ISubCategory cat) {
// do not use cat.getId() for the moment because it represents the mongoId
this(cat.getName(), cat.getName());
}
/**
* CategoryFrequency constructor from a category.
*
* @param catId the category ID
* @param catName the category name
*/
public CategoryFrequency(String catId, String catName) {
this.categoryId = catId;
this.categoryName = catName;
}
/**
* CategoryFrequency constructor from a category.
*
* @param catId the category ID
* @param catName the category name
* @param count the occurrence
*/
public CategoryFrequency(String catId, String catName, long count) {
this.categoryId = catId;
this.categoryName = catName;
this.count = count;
}
public String getCategoryId() {
return categoryId;
}
public String getCategoryName() {
return categoryName != null ? categoryName : categoryId;
}
public float getFrequency() {
return frequency;
}
public long getCount() {
return count;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof CategoryFrequency))
return false;
CategoryFrequency that = (CategoryFrequency) o;
return !(this.getCategoryId() != null ? !this.getCategoryId().equals(that.getCategoryId())
: that.getCategoryId() != null);
}
@Override
public int hashCode() {
return getCategoryId() != null ? getCategoryId().hashCode() : 0;
}
@Override
public int compareTo(CategoryFrequency o) {
if (this.getCount() > o.getCount()) {
return 1;
} else if (this.getCount() < o.getCount()) {
return -1;
} else {
final SemanticCategoryEnum cat1 = SemanticCategoryEnum.getCategoryById(this.getCategoryId());
final SemanticCategoryEnum cat2 = SemanticCategoryEnum.getCategoryById(o.getCategoryId());
if (cat1 != null && cat2 != null) {
return cat2.ordinal() - cat1.ordinal();
} else if (cat1 == null && cat2 != null) {
return 1;
} else if (cat1 != null && cat2 == null) {
return -1;
} else {
return o.getCategoryId().compareTo(this.getCategoryId());
}
}
}
@Override
public String toString() {
return "[Category: " + categoryId + " Count: " + count + " Frequency: " + frequency + "]";
}
public static void main(String[] args) {
CategoryFrequency cf1 = new CategoryFrequency("", "");
CategoryFrequency cf2 = new CategoryFrequency("CITY", "CITY");
List<CategoryFrequency> list = new ArrayList<>();
list.add(cf1);
list.add(cf2);
System.out.println(list);
Collections.sort(list);
System.out.println(list);
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.semantic;
import java.io.IOException;
import java.util.Random;
import org.apache.log4j.Logger;
import org.talend.dataquality.datamasking.functions.GenerateFromFileString;
import org.talend.dataquality.datamasking.functions.KeysLoader;
public class GenerateFromFileStringProvided extends GenerateFromFileString {
private static final long serialVersionUID = 8936060786451303843L;
private final static Logger log = Logger.getLogger(GenerateFromFileStringProvided.class);
@Override
public void parse(String extraParameter, boolean keepNullValues, Random rand) {
super.parse(extraParameter, keepNullValues, rand);
try {
genericTokens = KeysLoader.loadKeys(getClass().getResourceAsStream(parameters[0]));
} catch (IOException | NullPointerException e) {
log.error(e.getMessage(), e);
}
}
@Override
public String generateMaskedRow(String t) {
if (t == null || EMPTY_STRING.equals(t.trim())) {
return t;
}
return doGenerateMaskedField(t);
}
@Override
protected String doGenerateMaskedField(String str) {
return super.doGenerateMaskedField(str);
}
}
<file_sep>#!/bin/bash
UNAME_STR=`uname`
CONTAINER_NAME="talend/tdq-es:0.1"
CONTAINER_IP="192.168.59.103"
if [[ "$UNAME_STR" == 'Linux' ]]; then
#export DOCKER_HOST="tcp://192.168.59.103:2376"
#export DOCKER_CERT_PATH="$HOME/.boot2docker/certs/boot2docker-vm"
#export DOCKER_TLS_VERIFY=1
echo "linuxers need to config docker first."
exit
elif [[ "$UNAME_STR" == 'Darwin' ]]; then
boot2docker up
CONTAINER_IP=`boot2docker ip`
$(boot2docker shellinit)
fi
docker build -t $CONTAINER_NAME .
docker run -d -p 9200:9200 -p 9300:9300 $CONTAINER_NAME /elasticsearch/bin/elasticsearch \
--node.name=tdq
#docker run -i -t $CONTAINER_NAME /usr/bin/curl http://192.168.59.103:9200
docker run --rm -i -t $CONTAINER_NAME /bin/bash
#shut down all nodes at the end
#curl -XPOST 'http://192.168.59.103:9200/_shutdown'
<file_sep>package org.talend.dataquality.semantic.statistics;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.junit.BeforeClass;
import org.junit.Test;
import org.talend.dataquality.common.inference.Analyzer;
import org.talend.dataquality.common.inference.Analyzers;
import org.talend.dataquality.common.inference.Analyzers.Result;
import org.talend.dataquality.common.inference.ValueQualityStatistics;
import org.talend.dataquality.semantic.classifier.SemanticCategoryEnum;
import org.talend.dataquality.semantic.recognizer.CategoryFrequency;
import org.talend.dataquality.semantic.recognizer.CategoryRecognizerBuilder;
public class SemanticQualityAnalyzerTest {
private static CategoryRecognizerBuilder builder;
private static final List<String[]> RECORDS_CRM_CUST = getRecords("crm_cust.csv");
private static final List<String[]> RECORDS_CREDIT_CARDS = getRecords("credit_card_number_samples.csv");
private final String[] EXPECTED_CATEGORIES_DICT = new String[] { //
"", //
"CIVILITY", //
"FIRST_NAME", //
"LAST_NAME", //
"COUNTRY_CODE_ISO3", //
"ADDRESS_LINE", //
"FR_POSTAL_CODE", //
"CITY", //
"", //
"EMAIL", //
"", //
"", //
};
private static final long[][] EXPECTED_VALIDITY_COUNT_DICT = new long[][] { //
new long[] { 1000, 0, 0 }, //
new long[] { 1000, 0, 0 }, //
new long[] { 1000, 0, 0 }, //
new long[] { 1000, 0, 0 }, //
new long[] { 990, 10, 0 }, //
new long[] { 1000, 0, 0 }, //
new long[] { 996, 4, 0 }, //
new long[] { 1000, 0, 0 }, //
new long[] { 518, 0, 482 }, //
new long[] { 996, 4, 0 }, //
new long[] { 1000, 0, 0 }, //
new long[] { 1000, 0, 0 }, //
};
private final String[] EXPECTED_CATEGORIES_REGEX = new String[] { //
"", //
"VISA_CARD", //
};
private static final long[][] EXPECTED_VALIDITY_COUNT_REGEX = new long[][] { //
new long[] { 30, 0, 0 }, //
new long[] { 20, 10, 0 }, //
};
@BeforeClass
public static void setupBuilder() throws URISyntaxException {
final URI ddPath = SemanticQualityAnalyzerTest.class.getResource(CategoryRecognizerBuilder.DEFAULT_DD_PATH).toURI();
final URI kwPath = SemanticQualityAnalyzerTest.class.getResource(CategoryRecognizerBuilder.DEFAULT_KW_PATH).toURI();
builder = CategoryRecognizerBuilder.newBuilder() //
.ddPath(ddPath) //
.kwPath(kwPath) //
.lucene();
}
@Test
public void testSemanticQualityAnalyzerWithDictionaryCategory() {
testAnalysis(RECORDS_CRM_CUST, EXPECTED_CATEGORIES_DICT, EXPECTED_VALIDITY_COUNT_DICT);
}
@Test
public void testSemanticQualityAnalyzerWithRegexCategory() {
testAnalysis(RECORDS_CREDIT_CARDS, EXPECTED_CATEGORIES_REGEX, EXPECTED_VALIDITY_COUNT_REGEX);
}
public void testAnalysis(List<String[]> records, String[] expectedCategories, long[][] expectedValidityCount) {
Analyzer<Result> analyzers = Analyzers.with(//
new SemanticAnalyzer(builder), //
new SemanticQualityAnalyzer(builder, expectedCategories)//
);
for (String[] record : records) {
analyzers.analyze(record);
}
final List<Analyzers.Result> result = analyzers.getResult();
assertEquals(expectedCategories.length, result.size());
// Composite result assertions (there should be a DataType and a SemanticType)
for (Analyzers.Result columnResult : result) {
assertNotNull(columnResult.get(SemanticType.class));
assertNotNull(columnResult.get(ValueQualityStatistics.class));
}
// Semantic types assertions
for (int i = 0; i < expectedCategories.length; i++) {
final SemanticType stats = result.get(i).get(SemanticType.class);
// System.out.println("\"" + stats.getSuggestedCategory() + "\", //");
assertEquals("Unexpected SemanticType on column " + i, expectedCategories[i],
result.get(i).get(SemanticType.class).getSuggestedCategory());
for (CategoryFrequency cf : stats.getCategoryToCount().keySet()) {
if (expectedCategories[i].equals(cf.getCategoryId())) {
SemanticCategoryEnum cat = SemanticCategoryEnum.getCategoryById(cf.getCategoryId());
if (cat.getCompleteness()) {
assertEquals("Unexpected SemanticType occurence on column " + i, expectedValidityCount[i][0],
cf.getCount());
}
}
}
}
// Semantic validation assertions
for (int i = 0; i < expectedCategories.length; i++) {
final ValueQualityStatistics stats = result.get(i).get(ValueQualityStatistics.class);
// System.out.println("new long[] {" + stats.getValidCount() + ", " + stats.getInvalidCount() + ", "
// + stats.getEmptyCount() + "}, //");
assertEquals("Unexpected valid count on column " + i, expectedValidityCount[i][0], stats.getValidCount());
assertEquals("Unexpected invalid count on column " + i, expectedValidityCount[i][1], stats.getInvalidCount());
assertEquals("Unexpected empty count on column " + i, expectedValidityCount[i][2], stats.getEmptyCount());
assertEquals("Unexpected unknown count on column " + i, 0, stats.getUnknownCount());
}
}
private static List<String[]> getRecords(String path) {
List<String[]> records = new ArrayList<String[]>();
try {
Reader reader = new FileReader(SemanticQualityAnalyzerTest.class.getResource(path).getPath());
CSVFormat csvFormat = CSVFormat.DEFAULT.withDelimiter(';').withFirstRecordAsHeader();
Iterable<CSVRecord> csvRecords = csvFormat.parse(reader);
for (CSVRecord csvRecord : csvRecords) {
String[] values = new String[csvRecord.size()];
for (int i = 0; i < csvRecord.size(); i++) {
values[i] = csvRecord.get(i);
}
records.add(values);
}
} catch (IOException e) {
e.printStackTrace();
}
return records;
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.semantic.validator.impl;
import java.util.Locale;
import org.talend.dataquality.semantic.validator.AbstractPhoneNumberValidator;
import org.talend.dataquality.semantic.validator.ISemanticValidator;
/**
* Created by vlesquere on 24/06/16.
*/
public class DEPhoneNumberValidator extends AbstractPhoneNumberValidator implements ISemanticValidator {
@Override
public boolean isValid(String phoneNumber) {
return isValidPhoneNumber(phoneNumber, Locale.GERMANY);
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2015 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.semantic.index.utils;
import org.talend.dataquality.semantic.index.utils.optimizer.AirportOptimizer;
import org.talend.dataquality.semantic.index.utils.optimizer.CategoryOptimizer;
import org.talend.dataquality.semantic.index.utils.optimizer.FrCommuneOptimizer;
import org.talend.dataquality.semantic.index.utils.optimizer.UsCountyOptimizer;
public enum DictionaryGenerationSpec {
/**
* the categories defined in Keyword index
*/
ADDRESS_LINE(GenerationType.KEYWORD, "street_type_cleaned.csv", new CsvReaderConfig(CsvConstants.SEMICOLON, true), new int[] { 0, 1, 2, 3, 4, 5 }),
FULL_NAME(
GenerationType.KEYWORD,
"civility_cleaned.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, true),
new int[] { 0, 1, 2, 3, 4, 5 }),
/**
* the categories defined in Data Dictionary index
*/
ANIMAL(GenerationType.DICTIONARY, "animal_cleaned.csv", new CsvReaderConfig(CsvConstants.SEMICOLON, true), new int[] { 0, 1, 2, 3, 4 }),
ANSWER(GenerationType.DICTIONARY, "answer.csv", new CsvReaderConfig(CsvConstants.SEMICOLON, false), new int[] { 0, 1 }),
AIRPORT(
GenerationType.DICTIONARY,
"airport-name-wiki.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, false),
new int[] { 0 },
new AirportOptimizer()),
AIRPORT_CODE(
GenerationType.DICTIONARY,
"airport-code-wiki.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, true),
new int[] { 0 }),
CITY(
GenerationType.DICTIONARY,
"city_cleaned_without_pinyin.csv",
new CsvReaderConfig(CsvConstants.COMMA, false),
new int[] {}),
// CITY_COMPLEMENTED("city_complemented.csv", new CsvReaderConfig(CsvConstants.SEMICOLON, false), new int[] { 2 }, null,
// "CITY"),
CIVILITY(
GenerationType.DICTIONARY,
"civility_cleaned.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, true),
new int[] { 0, 1, 2, 3, 4, 5 }),
CONTINENT(
GenerationType.DICTIONARY,
"continent_cleaned.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, false),
new int[] { 0, 1, 2, 3, 4, 5 }),
CONTINENT_CODE(
GenerationType.DICTIONARY,
"continent_cleaned.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, false),
new int[] { 6 }),
COUNTRY(GenerationType.DICTIONARY, "country-codes.csv", new CsvReaderConfig(CsvConstants.COMMA, true), new int[] { 0, 1 }),
COUNTRY_CODE_ISO2(
GenerationType.DICTIONARY,
"country-codes.csv",
new CsvReaderConfig(CsvConstants.COMMA, true),
new int[] { 2 }),
COUNTRY_CODE_ISO3(
GenerationType.DICTIONARY,
"country-codes.csv",
new CsvReaderConfig(CsvConstants.COMMA, true),
new int[] { 3 }),
CURRENCY_NAME(
GenerationType.DICTIONARY,
"country-codes.csv",
new CsvReaderConfig(CsvConstants.COMMA, true),
new int[] { 17 }),
CURRENCY_CODE(
GenerationType.DICTIONARY,
"country-codes.csv",
new CsvReaderConfig(CsvConstants.COMMA, true),
new int[] { 14 }),
HR_DEPARTMENT(
GenerationType.DICTIONARY,
"hr_department_cleaned.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, false),
new int[] { 0 }),
FIRST_NAME(
GenerationType.DICTIONARY,
"firstname_cleaned.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, true),
new int[] { 0 }),
LAST_NAME(GenerationType.DICTIONARY, "lastname12k.csv", new CsvReaderConfig(CsvConstants.COMMA, true), new int[] { 0 }),
GENDER(
GenerationType.DICTIONARY,
"gender_cleaned.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, true),
new int[] { 0, 1, 2, 3, 4, 5 }),
JOB_TITLE(
GenerationType.DICTIONARY,
"job_title_cleaned.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, false),
new int[] { 0 }),
MONTH(
GenerationType.DICTIONARY,
"months_cleaned.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, true),
new int[] { 0, 1, 2, 3, 4, 5 }),
STREET_TYPE(
GenerationType.DICTIONARY,
"street_type_cleaned.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, true),
new int[] { 0, 1, 2, 3, 4, 5 }),
WEEKDAY(
GenerationType.DICTIONARY,
"weekdays_cleaned.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, true),
new int[] { 0, 1, 2, 3, 4, 5 }),
MUSEUM(
GenerationType.DICTIONARY,
"wordnet_museums_yago2.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, false),
new int[] { 0 }),
US_COUNTY(
GenerationType.DICTIONARY,
"us_counties.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, false),
new int[] { 0 },
new UsCountyOptimizer()),
ORGANIZATION(
GenerationType.DICTIONARY,
"wordnet_organizations_yago2.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, false),
new int[] { 0 }),
COMPANY(
GenerationType.DICTIONARY,
"wordnet_companies_yago2_optimized.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, true),
new int[] { 0 }),
BEVERAGE(
GenerationType.DICTIONARY,
"wordnet_beverages_yago2.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, false),
new int[] { 0 }),
MEASURE_UNIT(
GenerationType.DICTIONARY,
"units_of_measurement_cleaned.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, false),
new int[] { 0 }),
INDUSTRY(
GenerationType.DICTIONARY,
"industry_GICS_simplified.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, false),
new int[] { 1 }),
INDUSTRY_GROUP(
GenerationType.DICTIONARY,
"industry_group_GICS_simplified.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, false),
new int[] { 1 }),
SECTOR(
GenerationType.DICTIONARY,
"industry_sector_GICS_simplified.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, false),
new int[] { 1 }),
FR_COMMUNE(
GenerationType.DICTIONARY,
"fr_comsimp2015.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, false),
new int[] { 10, 11 },
new FrCommuneOptimizer()),
FR_DEPARTEMENT(
GenerationType.DICTIONARY,
"fr_depts2015.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, false),
new int[] { 5 }),
FR_REGION(GenerationType.DICTIONARY, "fr_reg2016.txt", new CsvReaderConfig(CsvConstants.TAB, true), new int[] { 4 }),
FR_REGION_LEGACY(
GenerationType.DICTIONARY,
"fr_reg2015.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, false),
new int[] { 4 }),
LANGUAGE(
GenerationType.DICTIONARY,
"languages_code_name.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, true),
new int[] { 2, 3, 4, 5 }),
LANGUAGE_CODE_ISO2(
GenerationType.DICTIONARY,
"languages_code_name.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, true),
new int[] { 0 }),
LANGUAGE_CODE_ISO3(
GenerationType.DICTIONARY,
"languages_code_name.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, true),
new int[] { 1 }),
CA_PROVINCE_TERRITORY(
GenerationType.DICTIONARY,
"ca_province_territory.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, true),
new int[] { 0 }),
CA_PROVINCE_TERRITORY_CODE(
GenerationType.DICTIONARY,
"ca_province_territory.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, true),
new int[] { 2 }),
MX_ESTADO(GenerationType.DICTIONARY, "mx_estado.csv", new CsvReaderConfig(CsvConstants.SEMICOLON, true), new int[] { 0 }),
MX_ESTADO_CODE(
GenerationType.DICTIONARY,
"mx_estado.csv",
new CsvReaderConfig(CsvConstants.SEMICOLON, true),
new int[] { 2 });
private GenerationType generationType;
private String sourceFile;
private CsvReaderConfig csvConfig;
private int[] columnsToIndex;
private CategoryOptimizer optimizer;
private String categoryName;
private DictionaryGenerationSpec(GenerationType generationType, String sourceFile, CsvReaderConfig csvConfig,
int[] columnsToIndex) {
this(generationType, sourceFile, csvConfig, columnsToIndex, null, null);
}
private DictionaryGenerationSpec(GenerationType generationType, String sourceFile, CsvReaderConfig csvConfig,
int[] columnsToIndex, CategoryOptimizer optimizer) {
this(generationType, sourceFile, csvConfig, columnsToIndex, optimizer, null);
}
private DictionaryGenerationSpec(GenerationType generationType, String sourceFile, CsvReaderConfig csvConfig,
int[] columnsToIndex, CategoryOptimizer optimizer, String categoryName) {
this.generationType = generationType;
this.sourceFile = sourceFile;
this.csvConfig = csvConfig;
this.columnsToIndex = columnsToIndex;
this.optimizer = optimizer;
if (categoryName == null) {
this.categoryName = this.name();
} else {
this.categoryName = categoryName;
}
}
public GenerationType getGenerationType() {
return generationType;
}
public String getSourceFile() {
return sourceFile;
}
public CsvReaderConfig getCsvConfig() {
return csvConfig;
}
public int[] getColumnsToIndex() {
return columnsToIndex;
}
public void setColumnsToIndex(int[] columnsToIndex) {
this.columnsToIndex = columnsToIndex;
}
public CategoryOptimizer getOptimizer() {
return optimizer;
}
public String getCategoryName() {
return categoryName;
}
}
enum GenerationType {
DICTIONARY,
KEYWORD
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2015 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.semantic;
import java.io.Serializable;
import java.util.List;
import org.talend.dataquality.datamasking.functions.Function;
/**
* API of data masking action using semantic domain information.
*/
public class ValueDataMasker implements Serializable {
private static final long serialVersionUID = 7071792900542293289L;
private Function<String> function;
Function<String> getFunction() {
return function;
}
/**
* ValueDataMasker constructor.
*
* @param semanticCategory the semantic domain information
* @param dataType the data type information
*/
public ValueDataMasker(String semanticCategory, String dataType) {
this(semanticCategory, dataType, null);
}
/**
* ValueDataMasker constructor.
*
* @param semanticCategory the semantic domain information
* @param dataType the data type information
* @param params extra parameters such as date time pattern list
*/
public ValueDataMasker(String semanticCategory, String dataType, List<String> params) {
function = SemanticMaskerFunctionFactory.createMaskerFunctionForSemanticCategory(semanticCategory, dataType, params);
}
/**
* mask the input value.
*
* @param input
* @return the masked value
*/
public String maskValue(String input) {
return function.generateMaskedRow(input);
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.email;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import org.talend.dataquality.email.checkerImpl.CallbackMailServerCheckerImplTest;
import org.talend.dataquality.email.checkerImpl.ListDomainsCheckerImplTest;
import org.talend.dataquality.email.checkerImpl.LocalPartRegexCheckerImplTest;
import org.talend.dataquality.email.checkerImpl.RegularRegexCheckerImplTest;
import org.talend.dataquality.email.checkerImpl.TLDsCheckerImplTest;
/**
* created by qiongli on 2014年12月30日 Detailled comment
*
*/
@RunWith(Suite.class)
@SuiteClasses({ EmailVerifyTest.class, CallbackMailServerCheckerImplTest.class, ListDomainsCheckerImplTest.class,
LocalPartRegexCheckerImplTest.class, RegularRegexCheckerImplTest.class, TLDsCheckerImplTest.class })
public class AllEmailTests {
}
<file_sep>package org.talend.dataquality.datamasking.semantic;
import java.util.Random;
import org.apache.commons.lang.StringUtils;
import org.talend.dataquality.datamasking.functions.Function;
public class ReplaceCharacterHelper {
static String replaceCharacters(String input, Random rnd) {
if (StringUtils.isEmpty(input)) {
return input;
} else {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (Character.isUpperCase(ch)) {
sb.append(Function.UPPER.charAt(rnd.nextInt(26)));
} else if (Character.isLowerCase(ch)) {
sb.append(Function.LOWER.charAt(rnd.nextInt(26)));
} else if (Character.isDigit(ch)) {
sb.append(rnd.nextInt(10));
} else {
sb.append(ch);
}
}
return sb.toString();
}
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import static org.junit.Assert.assertEquals;
import java.util.Random;
import org.junit.Before;
import org.junit.Test;
/**
* @author jteuladedenantes
*/
public class GenerateUniqueSsnFrTest {
private String output;
private AbstractGenerateUniqueSsn gnf = new GenerateUniqueSsnFr();
@Before
public void setUp() throws Exception {
gnf.setRandom(new Random(42));
gnf.setKeepFormat(true);
}
@Test
public void testEmpty() {
gnf.setKeepEmpty(true);
output = gnf.generateMaskedRow("");
assertEquals("", output); //$NON-NLS-1$
}
@Test
public void testKeepInvalidPatternTrue() {
gnf.setKeepInvalidPattern(true);
output = gnf.generateMaskedRow(null);
assertEquals(null, output);
output = gnf.generateMaskedRow("");
assertEquals("", output);
output = gnf.generateMaskedRow("AHDBNSKD");
assertEquals("AHDBNSKD", output);
}
@Test
public void testKeepInvalidPatternFalse() {
gnf.setKeepInvalidPattern(false);
output = gnf.generateMaskedRow(null);
assertEquals(null, output);
output = gnf.generateMaskedRow("");
assertEquals(null, output);
output = gnf.generateMaskedRow("AHDBNSKD");
assertEquals(null, output);
}
@Test
public void testGood1() {
output = gnf.generateMaskedRow("1860348282074 19");
assertEquals("2000132446558 52", output);
}
@Test
public void testGood2() {
gnf.setKeepFormat(false);
// with spaces
output = gnf.generateMaskedRow("2 12 12 15 953 006 88");
assertEquals("117051129317622", output);
}
@Test
public void testGood3() {
// corse department
output = gnf.generateMaskedRow("10501 2B 532895 34");
assertEquals("12312 85 719322 48", output);
}
@Test
public void testGood4() {
gnf.setKeepFormat(false);
// with a control key less than 10
output = gnf.generateMaskedRow("1960159794247 60");
assertEquals("276115886661903", output);
}
@Test
public void testWrongSsnFieldNumber() {
gnf.setKeepInvalidPattern(false);
// without a number
output = gnf.generateMaskedRow("186034828207 19");
assertEquals(null, output);
}
@Test
public void testWrongSsnFieldLetter() {
gnf.setKeepInvalidPattern(false);
// with a wrong letter
output = gnf.generateMaskedRow("186034Y282079 19");
assertEquals(null, output);
}
@Test
public void testWrongSsnFieldPattern() {
gnf.setKeepInvalidPattern(false);
// with a letter instead of a number
output = gnf.generateMaskedRow("1860I48282079 19");
assertEquals(null, output);
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.semantic.index;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.SearcherManager;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
public class DictionarySearcher extends AbstractDictionarySearcher {
private static final Logger LOGGER = Logger.getLogger(DictionarySearcher.class);
private SearcherManager mgr;
/**
* SynonymIndexSearcher constructor creates this searcher and initializes the index.
*
* @param indexPath the path to the index.
*/
public DictionarySearcher(String indexPath) {
try {
FSDirectory indexDir = FSDirectory.open(new File(indexPath));
mgr = new SearcherManager(indexDir, null);
} catch (IOException e) {
LOGGER.error("Unable to open synonym index.", e);
}
}
/**
* SynonymIndexSearcher constructor creates this searcher and initializes the index.
*
* @param indexPath the path to the index.
*/
public DictionarySearcher(URI indexPathURI) {
try {
Directory indexDir = ClassPathDirectory.open(indexPathURI);
mgr = new SearcherManager(indexDir, null);
} catch (IOException e) {
LOGGER.error("Unable to open synonym index.", e);
}
}
public DictionarySearcher(Directory indexDir) {
try {
mgr = new SearcherManager(indexDir, null);
} catch (IOException e) {
LOGGER.error("Unable to open synonym index.", e);
}
}
/**
* search for documents by one of the synonym (which may be the word).
*
* @param stringToSearch
* @return
* @throws java.io.IOException
*/
@Override
public TopDocs searchDocumentBySynonym(String stringToSearch) throws IOException {
TopDocs topDocs = null;
Query query;
switch (searchMode) {
case MATCH_SEMANTIC_DICTIONARY:
query = createQueryForSemanticDictionaryMatch(stringToSearch);
break;
case MATCH_SEMANTIC_KEYWORD:
query = createQueryForSemanticKeywordMatch(stringToSearch);
break;
default: // do the same as MATCH_SEMANTIC_DICTIONARY mode
query = createQueryForSemanticDictionaryMatch(stringToSearch);
break;
}
final IndexSearcher searcher = mgr.acquire();
topDocs = searcher.search(query, topDocLimit);
mgr.release(searcher);
return topDocs;
}
/**
* Get a document from search result by its document number.
*
* @param docNum the doc number
* @return the document (can be null if any problem)
*/
@Override
public Document getDocument(int docNum) {
Document doc = null;
try {
final IndexSearcher searcher = mgr.acquire();
doc = searcher.doc(docNum);
mgr.release(searcher);
} catch (IOException e) {
LOGGER.error(e);
}
return doc;
}
/**
* Method "getWordByDocNumber".
*
* @param docNo the document number
* @return the document or null
*/
public String getWordByDocNumber(int docNo) {
Document document = getDocument(docNo);
return document != null ? document.getValues(F_WORD)[0] : null;
}
/**
* Method "getSynonymsByDocNumber".
*
* @param docNo the doc number
* @return the synonyms or null if no document is found
*/
public String[] getSynonymsByDocNumber(int docNo) {
Document document = getDocument(docNo);
return document != null ? document.getValues(F_SYN) : null;
}
/**
* Method "getNumDocs".
*
* @return the number of documents in the index
*/
public int getNumDocs() {
try {
final IndexSearcher searcher = mgr.acquire();
final int numDocs = searcher.getIndexReader().numDocs();
mgr.release(searcher);
return numDocs;
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
return -1;
}
public void close() {
try {
mgr.acquire().getIndexReader().close();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
public void maybeRefreshIndex() {
try {
mgr.maybeRefresh();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking;
import org.talend.dataquality.datamasking.functions.Function;
/**
* created by jgonzalez on 18 juin 2015 This class is the factory that will instanciate the correct function.
*
*/
public class FunctionFactory {
private Function<?> getFunction(Class<?> clazz) throws InstantiationException, IllegalAccessException {
return (Function<?>) clazz.newInstance();
}
private Function<?> getFunction3(FunctionType type, int javaType) throws InstantiationException, IllegalAccessException {
Function<?> res;
switch (type) {
case REPLACE_LAST_CHARS:
switch (javaType) {
case 0:
res = getFunction(FunctionType.REPLACE_LAST_CHARS_INT.getClazz());
break;
case 1:
res = getFunction(FunctionType.REPLACE_LAST_CHARS_LONG.getClazz());
break;
case 4:
res = getFunction(FunctionType.REPLACE_LAST_CHARS_STRING.getClazz());
break;
default:
res = null;
break;
}
break;
case REPLACE_NUMERIC:
switch (javaType) {
case 0:
res = getFunction(FunctionType.REPLACE_NUMERIC_INT.getClazz());
break;
case 1:
res = getFunction(FunctionType.REPLACE_NUMERIC_LONG.getClazz());
break;
case 2:
res = getFunction(FunctionType.REPLACE_NUMERIC_FLOAT.getClazz());
break;
case 3:
res = getFunction(FunctionType.REPLACE_NUMERIC_DOUBLE.getClazz());
break;
case 4:
res = getFunction(FunctionType.REPLACE_NUMERIC_STRING.getClazz());
break;
default:
res = null;
break;
}
break;
default:
res = getFunction(type.getClazz());
break;
}
return res;
}
private Function<?> getFunction2(FunctionType type, int javaType) throws InstantiationException, IllegalAccessException {
Function<?> res;
switch (type) {
case GENERATE_FROM_LIST_HASH:
switch (javaType) {
case 0:
res = getFunction(FunctionType.GENERATE_FROM_LIST_HASH_INT.getClazz());
break;
case 1:
res = getFunction(FunctionType.GENERATE_FROM_LIST_HASH_LONG.getClazz());
break;
case 4:
res = getFunction(FunctionType.GENERATE_FROM_LIST_HASH_STRING.getClazz());
break;
default:
res = null;
break;
}
break;
case GENERATE_FROM_FILE_HASH:
switch (javaType) {
case 0:
res = getFunction(FunctionType.GENERATE_FROM_FILE_HASH_INT.getClazz());
break;
case 1:
res = getFunction(FunctionType.GENERATE_FROM_FILE_HASH_LONG.getClazz());
break;
case 4:
res = getFunction(FunctionType.GENERATE_FROM_FILE_HASH_STRING.getClazz());
break;
default:
res = null;
break;
}
break;
case GENERATE_SEQUENCE:
switch (javaType) {
case 0:
res = getFunction(FunctionType.GENERATE_SEQUENCE_INT.getClazz());
break;
case 1:
res = getFunction(FunctionType.GENERATE_SEQUENCE_LONG.getClazz());
break;
case 2:
res = getFunction(FunctionType.GENERATE_SEQUENCE_FLOAT.getClazz());
break;
case 3:
res = getFunction(FunctionType.GENERATE_SEQUENCE_DOUBLE.getClazz());
break;
case 4:
res = getFunction(FunctionType.GENERATE_SEQUENCE_STRING.getClazz());
break;
default:
res = null;
break;
}
break;
case NUMERIC_VARIANCE:
switch (javaType) {
case 0:
res = getFunction(FunctionType.NUMERIC_VARIANCE_INT.getClazz());
break;
case 1:
res = getFunction(FunctionType.NUMERIC_VARIANCE_LONG.getClazz());
break;
case 2:
res = getFunction(FunctionType.NUMERIC_VARIANCE_FlOAT.getClazz());
break;
case 3:
res = getFunction(FunctionType.NUMERIC_VARIANCE_DOUBLE.getClazz());
break;
default:
res = null;
break;
}
break;
case REMOVE_FIRST_CHARS:
switch (javaType) {
case 0:
res = getFunction(FunctionType.REMOVE_FIRST_CHARS_INT.getClazz());
break;
case 1:
res = getFunction(FunctionType.REMOVE_FIRST_CHARS_LONG.getClazz());
break;
case 4:
res = getFunction(FunctionType.REMOVE_FIRST_CHARS_STRING.getClazz());
break;
default:
res = null;
break;
}
break;
case REMOVE_LAST_CHARS:
switch (javaType) {
case 0:
res = getFunction(FunctionType.REMOVE_LAST_CHARS_INT.getClazz());
break;
case 1:
res = getFunction(FunctionType.REMOVE_LAST_CHARS_LONG.getClazz());
break;
case 4:
res = getFunction(FunctionType.REMOVE_LAST_CHARS_STRING.getClazz());
break;
default:
res = null;
break;
}
break;
case REPLACE_FIRST_CHARS:
switch (javaType) {
case 0:
res = getFunction(FunctionType.REPLACE_FIRST_CHARS_INT.getClazz());
break;
case 1:
res = getFunction(FunctionType.REPLACE_FIRST_CHARS_LONG.getClazz());
break;
case 4:
res = getFunction(FunctionType.REPLACE_FIRST_CHARS_STRING.getClazz());
break;
default:
res = null;
break;
}
break;
default:
res = getFunction3(type, javaType);
break;
}
return res;
}
/**
* DOC jgonzalez Comment method "getFunction". This function is used to res = the correct function according to the
* user choice.
*
* @param type The function requested by the user.
* @param javaType Some functions work and several type, this parameter represents the wanted type.
* @res = A new function.
* @throws InstantiationException
* @throws IllegalAccessException
*/
public Function<?> getFunction(FunctionType type, int javaType) throws InstantiationException, IllegalAccessException {
Function<?> res;
switch (type) {
case KEEP_FIRST_AND_GENERATE:
switch (javaType) {
case 0:
res = getFunction(FunctionType.KEEP_FIRST_AND_GENERATE_INT.getClazz());
break;
case 1:
res = getFunction(FunctionType.KEEP_FIRST_AND_GENERATE_LONG.getClazz());
break;
case 4:
res = getFunction(FunctionType.KEEP_FIRST_AND_GENERATE_STRING.getClazz());
break;
default:
res = null;
break;
}
break;
case KEEP_LAST_AND_GENERATE:
switch (javaType) {
case 0:
res = getFunction(FunctionType.KEEP_LAST_AND_GENERATE_INT.getClazz());
break;
case 1:
res = getFunction(FunctionType.KEEP_LAST_AND_GENERATE_LONG.getClazz());
break;
case 4:
res = getFunction(FunctionType.KEEP_LAST_AND_GENERATE_STRING.getClazz());
break;
default:
res = null;
break;
}
break;
case GENERATE_BETWEEN:
switch (javaType) {
case 0:
res = getFunction(FunctionType.GENERATE_BETWEEN_INT.getClazz());
break;
case 1:
res = getFunction(FunctionType.GENERATE_BETWEEN_LONG.getClazz());
break;
case 2:
res = getFunction(FunctionType.GENERATE_BETWEEN_FLOAT.getClazz());
break;
case 3:
res = getFunction(FunctionType.GENERATE_BETWEEN_DOUBLE.getClazz());
break;
case 4:
res = getFunction(FunctionType.GENERATE_BETWEEN_STRING.getClazz());
break;
case 5:
res = getFunction(FunctionType.GENERATE_BETWEEN_DATE.getClazz());
break;
default:
res = null;
break;
}
break;
case GENERATE_CREDIT_CARD_FORMAT:
switch (javaType) {
case 1:
res = getFunction(FunctionType.GENERATE_CREDIT_CARD_FORMAT_LONG.getClazz());
break;
case 4:
res = getFunction(FunctionType.GENERATE_CREDIT_CARD_FORMAT_STRING.getClazz());
break;
default:
res = null;
break;
}
break;
case GENERATE_CREDIT_CARD:
switch (javaType) {
case 1:
res = getFunction(FunctionType.GENERATE_CREDIT_CARD_LONG.getClazz());
break;
case 4:
res = getFunction(FunctionType.GENERATE_CREDIT_CARD_STRING.getClazz());
break;
default:
res = null;
break;
}
break;
case GENERATE_FROM_FILE:
switch (javaType) {
case 0:
res = getFunction(FunctionType.GENERATE_FROM_FILE_INT.getClazz());
break;
case 1:
res = getFunction(FunctionType.GENERATE_FROM_FILE_LONG.getClazz());
break;
case 4:
res = getFunction(FunctionType.GENERATE_FROM_FILE_STRING.getClazz());
break;
default:
res = null;
break;
}
break;
case GENERATE_FROM_LIST:
switch (javaType) {
case 0:
res = getFunction(FunctionType.GENERATE_FROM_LIST_INT.getClazz());
break;
case 1:
res = getFunction(FunctionType.GENERATE_FROM_LIST_LONG.getClazz());
break;
case 4:
res = getFunction(FunctionType.GENERATE_FROM_LIST_STRING.getClazz());
break;
default:
res = null;
break;
}
break;
default:
res = getFunction2(type, javaType);
break;
}
return res;
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.statistics.type;
import java.io.Serializable;
import java.util.*;
/**
*
* Data type bean hold type to frequency and type to value maps.
*/
public class DataTypeOccurences implements Serializable {
private static final long serialVersionUID = -736825123668340428L;
private Map<DataTypeEnum, Long> typeOccurences = new EnumMap<>(DataTypeEnum.class);
public Map<DataTypeEnum, Long> getTypeFrequencies() {
return typeOccurences;
}
/**
* The default method for get suggested type. <tt>typeThreshold</tt> is set to 0.5 and <tt>typeInteger</tt> is also
* set to 0.5.
*
* @return type suggested by system automatically given frequencies.
*/
public DataTypeEnum getSuggestedType() {
return getSuggestedType(0.5, 0.5);
}
/**
* Suggests a type according to the specified integer threshold and a default <tt>typeThreshold</tt> set to 0.5.
*
* @param integerThreshold pecifies the minimum occurrence ratio (w.r.t. the number of occurrences of numerical
* values which exceeds the <tt>typeThreshold</tt>) before integer type is returned as suggested type
* @return the suggested type
*/
public DataTypeEnum getSuggestedType(double integerThreshold) {
return getSuggestedType(0.5, integerThreshold);
}
/**
* Suggests a type according to the so far listed types occurrences. This methods returns a type which is different
* with <tt>Empty type</tt>. <tt>String type</tt> is the default type which is suggested when another type can not
* be suggested. For instance, for following values, "", "", "", "", "1.2" DOUBLE type is returned.
* <p>
* </p>
* Before a non-numerical type (all types but integer and double) is returned its ratio (according to the non empty
* types) must be greater than <tt>typeThreshold</tt>. When the ratio (w.r.t. the number of occurrences of non empty
* types) of numerical types is greater than <tt>typeThreshold</tt> then, the integer ratio ( according to the
* number of occurrences of numerical types) must be greater than <tt>integerThreshold</tt>. If not the double type
* is returned. <br/>
* For instance, for following values "1.2","3.5","2","6","7" and with an <tt>integerThreshold</tt> of 0.55 the
* suggested type will be INTEGER, whereas with an <tt>integerThreshold</tt> of 0.6 DOUBLE type is returned.
*
* @param typeThreshold specifies the minimum occurrence ratio (w.r.t. the number of occurrences of non empty types)
* reached by the suggested type (except for String type which is the default type).
* @param integerThreshold specifies the minimum occurrence ratio (w.r.t. the number of occurrences of numerical
* values which exceeds the <tt>typeThreshold</tt>) before integer type is returned as suggested type
* @return the suggested type
*/
public DataTypeEnum getSuggestedType(double typeThreshold, double integerThreshold) {
final List<Map.Entry<DataTypeEnum, Long>> sortedTypeOccurrences = new ArrayList<>();
long count = 0;
// retrieve the occurrences non empty types,
for (Map.Entry<DataTypeEnum, Long> entry : typeOccurences.entrySet()) {
final DataTypeEnum type = entry.getKey();
if (!DataTypeEnum.EMPTY.equals(type)) {
count += entry.getValue();
sortedTypeOccurrences.add(entry);
}
}
Comparator<Map.Entry<DataTypeEnum, Long>> decreasingOccurrenceComparator = new Comparator<Map.Entry<DataTypeEnum, Long>>() {
@Override
public int compare(Map.Entry<DataTypeEnum, Long> o1, Map.Entry<DataTypeEnum, Long> o2) {
return Long.compare(o2.getValue(), o1.getValue());
}
};
// sort the non empty types by decreasing occurrences number
Collections.sort(sortedTypeOccurrences, decreasingOccurrenceComparator);
final double occurrenceThreshold = typeThreshold * count;
// if non empty types exist
if (count > 0) {
final long mostFrequentTypeOccurrence = sortedTypeOccurrences.get(0).getValue();
final long doubleOccurrences = typeOccurences.containsKey(DataTypeEnum.DOUBLE)
? typeOccurences.get(DataTypeEnum.DOUBLE) : 0;
final long integerOccurrences = typeOccurences.containsKey(DataTypeEnum.INTEGER)
? typeOccurences.get(DataTypeEnum.INTEGER) : 0;
final long numericalOccurrences = doubleOccurrences + integerOccurrences;
// The column is numeric (both double and integer types) and the numerical occurrences is dominant
if (numericalOccurrences > occurrenceThreshold && numericalOccurrences > mostFrequentTypeOccurrence) {
if (integerOccurrences > integerThreshold * numericalOccurrences) {
return DataTypeEnum.INTEGER;
} else {
return DataTypeEnum.DOUBLE;
}
} else { // otherwise
final long secondMostFrequentTypeOccurrence = sortedTypeOccurrences.size() > 1
? sortedTypeOccurrences.get(1).getValue() : 0;
// return the most frequent type if it reaches the threshold and has strictly more occurrences than the
// second most frequent types
if (mostFrequentTypeOccurrence >= occurrenceThreshold
&& mostFrequentTypeOccurrence != secondMostFrequentTypeOccurrence) {
return sortedTypeOccurrences.get(0).getKey();
}
}
}
// fallback to string as default choice
return DataTypeEnum.STRING;
}
public void increment(DataTypeEnum type) {
if (!typeOccurences.containsKey(type)) {
typeOccurences.put(type, 1l);
} else {
typeOccurences.put(type, typeOccurences.get(type) + 1);
}
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
/**
* DOC qzhao class global comment. Detailled comment<br>
*
* This class provides a random replacement of the email address from a list of common domains<br>
*
* If a specified domain is provided, see the class {@link MaskSpecifiedEmailDomain}
*
* <b>See also:</b> {@link MaskEmail}
*/
public class MaskFullEmailDomainRandomly extends MaskEmailRandomly {
private static final long serialVersionUID = -7030194827250476071L;
/**
*
* DOC qzhao Comment method "maskFullDomainRandomly".<br>
*
* Replace full email domain by the given replacement
*
* @param address
* @param replacement
* @param count
* @return
*/
@Override
protected String maskEmail(String address) {
int splitAddress = address.indexOf('@');
return address.substring(0, splitAddress + 1)
+ parameters[chooseAppropriateDomainIndex(address.substring(splitAddress + 1))];
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import java.util.List;
/**
* @author jteuladedenantes
*
* A FieldEnum is a list of specific values. We defined a FieldEnum by an exhaustive list of all possible values.
*/
public class FieldEnum extends AbstractField {
private static final long serialVersionUID = 4434958606928963578L;
/**
* The exhaustive list of values
*/
private List<String> enumValues;
public FieldEnum(List<String> enumValues, int length) {
this.length = length;
for (String value : enumValues)
if (value.length() != length) {
// TODO
// Error in the field constructor
return;
}
this.enumValues = enumValues;
}
@Override
public long getWidth() {
return enumValues.size();
}
@Override
public Long encode(String str) {
return (long) enumValues.indexOf(str);
}
@Override
public String decode(long number) {
if (number >= getWidth())
return "";
return enumValues.get((int) number);
}
}
<file_sep>package org.talend.dataquality.datamasking.shuffling;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class GenerateData {
public static final String SHUFFLING_DATA_PATH = "Shuffling_test_data_1000.csv";
protected List<List<Object>> getTableValue(String file) {
String pathString = "";
try {
pathString = GenerateData.class.getResource(file).toURI().getPath();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
List<List<Object>> result = new ArrayList<List<Object>>();
try {
br = new BufferedReader(new FileReader(pathString));
line = br.readLine(); // read the column title
while ((line = br.readLine()) != null) {
List<Object> row = new ArrayList<Object>();
Object[] items = line.split(cvsSplitBy);
for (Object item : items) {
row.add(item);
}
result.add(row);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
protected List<List<Object>> getTableValueBySimbol(String file) {
String pathString = "";
try {
pathString = GenerateData.class.getResource(file).toURI().getPath();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
List<List<Object>> result = new ArrayList<List<Object>>();
try {
br = new BufferedReader(new FileReader(pathString));
line = br.readLine(); // read the column title
while ((line = br.readLine()) != null) {
List<Object> row = new ArrayList<Object>();
Object[] items = line.split(cvsSplitBy);
for (Object item : items) {
row.add(item);
}
result.add(row);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
protected int getColumnIndex(String column) {
String pathString = "";
try {
pathString = GenerateData.class.getResource(SHUFFLING_DATA_PATH).toURI().getPath();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
int position = 0;
try {
br = new BufferedReader(new FileReader(pathString));
if ((line = br.readLine()) != null) {
List<String> attributes = Arrays.asList(line.split(cvsSplitBy));
position = attributes.indexOf(column);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return position;
}
protected List<String> getData(String file, String column) throws URISyntaxException {
String pathString = GenerateData.class.getResource(file).toURI().getPath();
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
int position = 0;
List<String> result = new LinkedList<String>();
try {
br = new BufferedReader(new FileReader(pathString));
if ((line = br.readLine()) != null) {
List<String> attributes = Arrays.asList(line.split(","));
position = attributes.indexOf(column);
}
while ((line = br.readLine()) != null) {
String[] items = line.split(cvsSplitBy);
result.add(items[position]);
}
return result;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
protected List<List<String>> getMultipleData(String file, String[] columns) throws URISyntaxException {
List<List<String>> result = new ArrayList<List<String>>();
for (String column : columns) {
result.add(getData(file, column));
}
return result;
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import static org.junit.Assert.assertEquals;
import java.util.Random;
import org.junit.Before;
import org.junit.Test;
/**
* @author dprot
*/
public class GenerateUniqueSsnIndiaTest {
private String output;
private AbstractGenerateUniqueSsn gnf = new GenerateUniqueSsnIndia();
@Before
public void setUp() throws Exception {
gnf.setRandom(new Random(42));
gnf.setKeepFormat(true);
}
@Test
public void testKeepInvalidPatternTrue() {
gnf.setKeepInvalidPattern(true);
output = gnf.generateMaskedRow(null);
assertEquals(null, output);
output = gnf.generateMaskedRow("");
assertEquals("", output);
output = gnf.generateMaskedRow("AHDBNSKD");
assertEquals("AHDBNSKD", output);
}
@Test
public void testKeepInvalidPatternFalse() {
gnf.setKeepInvalidPattern(false);
output = gnf.generateMaskedRow(null);
assertEquals(null, output);
output = gnf.generateMaskedRow("");
assertEquals(null, output);
output = gnf.generateMaskedRow("AHDBNSKD");
assertEquals(null, output);
}
@Test
public void testGood1() {
output = gnf.generateMaskedRow("186034828209");
assertEquals("578462130603", output);
}
@Test
public void testGood2() {
// with spaces
output = gnf.generateMaskedRow("21212159530 8");
assertEquals("48639384490 5", output);
}
@Test
public void testWrongSsnFieldNumber() {
gnf.setKeepInvalidPattern(false);
// without a number
output = gnf.generateMaskedRow("21860348282");
assertEquals(null, output);
}
@Test
public void testWrongSsnField1() {
gnf.setKeepInvalidPattern(false);
// Wrong first field
output = gnf.generateMaskedRow("086034828209");
assertEquals(null, output);
}
@Test
public void testWrongSsnFieldLetter() {
gnf.setKeepInvalidPattern(false);
// with a letter instead of a number
output = gnf.generateMaskedRow("186034Y20795");
assertEquals(null, output);
}
}
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.talend.dataquality</groupId>
<artifactId>dataquality-parent</artifactId>
<version>3</version>
<packaging>pom</packaging>
<name>dataquality-parent</name>
<inceptionYear>2015</inceptionYear>
<url>http://www.talend.com</url>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<issueManagement>
<system>jira</system>
<url>https://jira.talendforge.org/browse/TDQ</url>
</issueManagement>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.organization>Talend</project.organization>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<distributionManagement>
<snapshotRepository>
<id>talend_nexus_deployment</id>
<url>http://newbuild.talend.com:8081/nexus/content/repositories/TalendOpenSourceSnapshot/</url>
</snapshotRepository>
<repository>
<id>talend_nexus_deployment</id>
<url>http://newbuild.talend.com:8081/nexus/content/repositories/TalendOpenSourceRelease/</url>
</repository>
</distributionManagement>
<repositories>
<repository>
<id>TalendOpenSourceSnapshot</id>
<url>http://newbuild.talend.com:8081/nexus/content/repositories/TalendOpenSourceSnapshot</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>TalendOpenSourceRelease</id>
<url>http://newbuild.talend.com:8081/nexus/content/repositories/TalendOpenSourceRelease</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<modules>
<module>dataquality-libraries</module>
</modules>
</project>
<file_sep>package org.talend.dataquality.datamasking.functions;
import static org.junit.Assert.assertEquals;
import java.util.Locale;
import java.util.Random;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
/**
* Created by jteuladedenantes on 22/09/16.
*/
public class GenerateUniquePhoneNumberUkTest {
private String output;
private AbstractGenerateUniquePhoneNumber gnu = new GenerateUniquePhoneNumberUk();
private GeneratePhoneNumberUK gpn = new GeneratePhoneNumberUK();
private static PhoneNumberUtil GOOGLE_PHONE_UTIL = PhoneNumberUtil.getInstance();
@Before
public void setUp() throws Exception {
gnu.setRandom(new Random(56));
gnu.setKeepFormat(true);
}
@Test
public void testValidWithFormat() {
output = gnu.generateMaskedRow("07700 900343");
assertEquals("07707 375307", output);
}
@Test
public void testValidWithoutFormat() {
gnu.setKeepFormat(false);
output = gnu.generateMaskedRow("07700 900343");
assertEquals("07707375307", output);
}
@Test
public void testInvalid() {
// without a number
output = gnu.generateMaskedRow("35686");
assertEquals("42445", output);
gnu.setKeepInvalidPattern(true);
// with a letter
output = gnu.generateMaskedRow("35686");
assertEquals("35686", output);
}
@Test
public void testValidAfterMasking() {
gnu.setKeepFormat(false);
String input;
String output;
for (int i = 0; i < 100; i++) {
gpn.setRandom(new Random());
input = gpn.doGenerateMaskedField(null);
if (isValidPhoneNumber(input)) {
for (int j = 0; j < 1000; j++) {
long rgenseed = System.nanoTime();
gnu.setRandom(new Random(rgenseed));
output = gnu.generateMaskedRow(input);
Assert.assertTrue("Don't worry, report this line to Data Quality team: with a seed = " + rgenseed + ", "
+ input + " is valid, but after the masking " + output + " is not valid", isValidPhoneNumber(output));
}
}
}
}
/**
*
* whether a phone number is valid for a certain region.
*
* @param data the data that we want to validate
* @return a boolean that indicates whether the number is of a valid pattern
*/
public static boolean isValidPhoneNumber(Object data) {
Phonenumber.PhoneNumber phonenumber = null;
try {
phonenumber = GOOGLE_PHONE_UTIL.parse(data.toString(), Locale.UK.getCountry());
} catch (Exception e) {
return false;
}
return GOOGLE_PHONE_UTIL.isValidNumberForRegion(phonenumber, Locale.UK.getCountry());
}
}
<file_sep>Jul. 2015
------------
**Source 1**: [http://data.okfn.org](http://data.okfn.org/data/country-codes),
licensed by its maintainers under the [Public Domain Dedication and License](http://opendatacommons.org/licenses/pddl/1-0/).<br/>
**File**: *country-codes.csv*.
**Source 2**: <NAME>, PhD from University of Paris 13.<br/>
**16 Files**: *address_cleaned.csv*, *airport_cleaned.csv*, *animal_cleaned.csv*,<br/>
*city_cleaned.csv*, *civility_cleaned.csv*, *continent_cleaned.csv*,<br/>
*days_cleaned.csv*, *department_cleaned.csv*, *drug_cleaned.csv*,<br/>
*jobTitle_cleaned.csv*, *firstname_cleaned.csv*, *medical_tets_cleaned.csv*,<br/>
*months_cleaned.csv*, *gender_cleaned.csv*,*pharmacy_cleaned.csv*,<br/>
*speciality_field_cleaned.csv*.
Oct. 2015
-------------
#### Add 8 new files:
##### Source YAGO:
1. *wordnet_beverages_yago2.csv*,
2. *wordnet_companies_yago2.csv*,
3. *wordnet_organizations_yago2.csv*,
4. *wordnet_museums_yago2.csv*.
##### Source Wikipedia
1. *us_counties.csv*: [Index of U.S. counties](https://en.wikipedia.org/wiki/Index_of_U.S._counties)
2. *airport-code-wiki.csv*: [List of airports](https://en.wikipedia.org/wiki/List_of_airports)
3. *airport-name-wiki.csv*: [List of airports](https://en.wikipedia.org/wiki/List_of_airports)
##### Others:
1. *industry_GICS_simplified.csv*,
2. *unitOfMeasurement_cleaned.csv*.
For more details, please check jira issue: [TDQ-10903.](https://jira.talendforge.org/browse/TDQ-10903)
#### Remove 5 files:
1. *drug_cleaned.csv*,
2. *medical_tets_cleaned.csv*,
3. *pharmacy_cleaned.csv*,
4. *speciality_field_cleaned.csv*,
5. *airport_cleaned.csv*,
6. *airport-codes_simplified.csv*: [Airport Codes](http://data.okfn.org/data/core/airport-codes)
#### Review all data source files and correct errors:
1. convert all files to utf 8
2. replace all "\&" by "&"
3. optimize some source files by adding the synonims
Nov. 2015
-------------
#### Add 6 new files:
##### Source INSEE:
1. *comisimp2015.csv* for *FR_COMMUNE* index,
2. *depts2015.csv* for *FR_DEPARTEMENT* index,
3. *reg2015.csv* for *FR_REGION* index.
##### Source wikipedia:
*languages_code_name.csv* for indexes:
*LANGUAGE*, *LANGUAGE_CODE_ISO2*, *LANGUAGE_CODE_ISO3*
##### Source [statoids.com](http://www.statoids.com/)
1. *ca_province_territory.csv* for the indexes: *CA_PROVINCE_TERRITORY*, *CA_PROVINCE_TERRITORY_CODE*
2. *mx_estado.csv* for the indexes: *MX_ESTADO*, *MX_ESTADO_CODE*
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Random;
import org.junit.Test;
/**
* created by jgonzalez on 25 juin 2015 Detailled comment
*
*/
public class ReplaceNumericStringTest {
private String input = "abc123def"; //$NON-NLS-1$
private String output;
private ReplaceNumericString rns = new ReplaceNumericString();
@Test
public void testGood() {
rns.parse("0", false, new Random(42));
output = rns.generateMaskedRow(input);
assertEquals("abc000def", output); //$NON-NLS-1$
}
@Test
public void testEmpty() {
rns.setKeepEmpty(true);
output = rns.generateMaskedRow("");
assertEquals("", output); //$NON-NLS-1$
}
@Test
public void testEmptyParameter() {
rns.parse(" ", false, new Random(42));
output = rns.generateMaskedRow(input);
assertEquals("abc830def", output); //$NON-NLS-1$
}
@Test
public void testBad() {
try {
rns.parse("0X", false, new Random(42));
fail("should get exception with input " + rns.parameters); //$NON-NLS-1$
} catch (Exception e) {
assertTrue("expect illegal argument exception ", e instanceof IllegalArgumentException); //$NON-NLS-1$
}
}
}
<file_sep>package org.talend.dataquality.datamasking.functions;
public abstract class KeepLastChars<T> extends CharactersOperation<T> {
private static final long serialVersionUID = 4065232723157315230L;
@Override
protected void initAttributes() {
endNumberToKeep = Integer.parseInt(parameters[0]);
if (parameters.length == 2)
charToReplace = parameters[1].charAt(0);
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.record.linkage.grouping;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.talend.dataquality.matchmerge.Attribute;
import org.talend.dataquality.matchmerge.MatchMergeAlgorithm;
import org.talend.dataquality.matchmerge.Record;
import org.talend.dataquality.matchmerge.mfb.MatchResult;
import org.talend.dataquality.matchmerge.mfb.RecordGenerator;
import org.talend.dataquality.matchmerge.mfb.RecordIterator;
import org.talend.dataquality.matchmerge.mfb.RecordIterator.ValueGenerator;
import org.talend.dataquality.record.linkage.grouping.swoosh.DQAttribute;
import org.talend.dataquality.record.linkage.grouping.swoosh.DQMFB;
import org.talend.dataquality.record.linkage.grouping.swoosh.DQMFBRecordMerger;
import org.talend.dataquality.record.linkage.grouping.swoosh.DQRecordIterator;
import org.talend.dataquality.record.linkage.grouping.swoosh.RichRecord;
import org.talend.dataquality.record.linkage.grouping.swoosh.SurvivorShipAlgorithmParams;
import org.talend.dataquality.record.linkage.grouping.swoosh.SurvivorShipAlgorithmParams.SurvivorshipFunction;
import org.talend.dataquality.record.linkage.grouping.swoosh.SwooshConstants;
import org.talend.dataquality.record.linkage.record.CombinedRecordMatcher;
import org.talend.dataquality.record.linkage.record.IRecordMatcher;
import org.talend.dataquality.record.linkage.utils.BidiMultiMap;
import org.talend.dataquality.record.linkage.utils.SurvivorShipAlgorithmEnum;
/**
* Record grouping class with t-swoosh algorithm.
*
*/
public class TSwooshGrouping<TYPE> {
List<RecordGenerator> rcdsGenerators = new ArrayList<>();
int totalCount = 0;
AbstractRecordGrouping<TYPE> recordGrouping;
BidiMultiMap<String, String> oldGID2New = new BidiMultiMap<String, String>();
// Added TDQ-9320: to use the algorithm handle the record one by one
private DQMFB algorithm;
// Added TDQ-12057
private boolean hasPassedOriginal = false;
/**
* DOC zhao TSwooshGrouping constructor comment.
*/
public TSwooshGrouping(AbstractRecordGrouping<TYPE> recordGrouping) {
this.recordGrouping = recordGrouping;
}
/**
* Getter for oldGID2New.
*
* @return the oldGID2New
*/
public Map<String, String> getOldGID2New() {
return this.oldGID2New;
}
/**
* Recording matching with t-swoosh algorithm. Used for tmatchgroup only
*
* @param inputRow
* @param matchingRule
*/
public void addToList(final TYPE[] inputRow, List<List<Map<java.lang.String, java.lang.String>>> multiMatchRules) {
totalCount++;
java.lang.String attributeName = null;
Map<java.lang.String, ValueGenerator> rcdMap = new LinkedHashMap<String, RecordIterator.ValueGenerator>();
for (List<Map<java.lang.String, java.lang.String>> matchRule : multiMatchRules) {
for (final Map<java.lang.String, java.lang.String> recordMap : matchRule) {
attributeName = recordMap.get(IRecordGrouping.ATTRIBUTE_NAME);
if (attributeName == null) {
// Dummy matcher
continue;
}
rcdMap.put(attributeName, new ValueGenerator() {
@Override
public int getColumnIndex() {
return Integer.valueOf(recordMap.get(IRecordGrouping.COLUMN_IDX));
}
@Override
public java.lang.String newValue() {
TYPE value = inputRow[Integer.valueOf(recordMap.get(IRecordGrouping.COLUMN_IDX))];
return value == null ? null : value.toString();
}
// Added TDQ-12057 : return the current column's values from the last original
// values.(multipass+swoosh+passOriginal)
// the original is the last one.
@Override
public Object getAttribute() {
TYPE type = inputRow[inputRow.length - 1];
if (type instanceof List) {
List<Attribute> attris = ((List<Attribute>) inputRow[inputRow.length - 1]);
Integer colIndex = Integer.valueOf(recordMap.get(IRecordGrouping.COLUMN_IDX));
for (Attribute att : attris) {
if (att.getColumnIndex() == colIndex) {
return att.getValues();
}
}
}
return null;
}
});
}
}
RecordGenerator rcdGen = new RecordGenerator();
rcdGen.setMatchKeyMap(rcdMap);
List<DQAttribute<?>> rowList = new ArrayList<>();
int colIdx = 0;
for (TYPE attribute : inputRow) {
DQAttribute<TYPE> attri;
// Added TDQ-12057, when pass original & multipass, no need to pass it into OriginalRow.
if (attribute instanceof List) {
attri = new DQAttribute<TYPE>(SwooshConstants.ORIGINAL_RECORD, colIdx, null);
hasPassedOriginal = true;
} else {// ~
attri = new DQAttribute<TYPE>(StringUtils.EMPTY, colIdx, attribute);
}
rowList.add(attri);
colIdx++;
}
rcdGen.setOriginalRow(rowList);
rcdsGenerators.add(rcdGen);
}
public void swooshMatch(IRecordMatcher combinedRecordMatcher, SurvivorShipAlgorithmParams survParams) {
swooshMatch(combinedRecordMatcher, survParams, new GroupingCallBack());
}
/**
* Used by tmatchgroup only.
*
* @param combinedRecordMatcher
* @param survParams
*/
private void swooshMatch(IRecordMatcher combinedRecordMatcher, SurvivorShipAlgorithmParams survParams,
GroupingCallBack callBack) {
algorithm = (DQMFB) createTswooshAlgorithm(combinedRecordMatcher, survParams, callBack);
Iterator<Record> iterator = new DQRecordIterator(totalCount, rcdsGenerators);
((DQRecordIterator) iterator).setOriginalColumnCount(this.recordGrouping.getOriginalInputColumnSize());
while (iterator.hasNext()) {
algorithm.matchOneRecord(iterator.next());
}
}
/**
* DOC yyin Comment method "createTswooshAlgorithm".
*
* @param combinedRecordMatcher
* @param survParams
* @return
*/
private MatchMergeAlgorithm createTswooshAlgorithm(IRecordMatcher combinedRecordMatcher,
SurvivorShipAlgorithmParams survParams, MatchMergeAlgorithm.Callback callback) {
SurvivorShipAlgorithmEnum[] surviorShipAlgos = new SurvivorShipAlgorithmEnum[survParams.getSurviorShipAlgos().length];
String[] funcParams = new String[surviorShipAlgos.length];
int idx = 0;
for (SurvivorshipFunction func : survParams.getSurviorShipAlgos()) {
surviorShipAlgos[idx] = func.getSurvivorShipAlgoEnum();
funcParams[idx] = func.getParameter();
idx++;
}
return new DQMFB(combinedRecordMatcher, new DQMFBRecordMerger("MFB", funcParams, //$NON-NLS-1$
surviorShipAlgos, survParams), callback);
}
// init the algorithm before do matching.
public void initialMFBForOneRecord(IRecordMatcher combinedRecordMatcher, SurvivorShipAlgorithmParams survParams) {
algorithm = (DQMFB) createTswooshAlgorithm(combinedRecordMatcher, survParams, new GroupingCallBack());
}
// do match on one single record,used by analysis
public void oneRecordMatch(RichRecord printRcd) {
algorithm.matchOneRecord(printRcd);
}
// get and output all result after all records finished
// used by both analysis and component
public void afterAllRecordFinished() {
List<Record> result = algorithm.getResult();
outputResult(result);
}
/**
* Output the result Result after all finished.
*
* @param result
*/
private void outputResult(List<Record> result) {
for (Record rcd : result) {
RichRecord printRcd = (RichRecord) rcd;
output(printRcd);
}
totalCount = 0;
rcdsGenerators.clear();
}
class GroupingCallBack implements MatchMergeAlgorithm.Callback {
@Override
public void onBeginRecord(Record record) {
// Nothing todo
}
@Override
public void onMatch(Record record1, Record record2, MatchResult matchResult) {
// record1 and record2 must be RichRecord from DQ grouping implementation.
RichRecord richRecord1 = (RichRecord) record1;
RichRecord richRecord2 = (RichRecord) record2;
richRecord1.setConfidence(richRecord1.getScore());
richRecord2.setConfidence(richRecord2.getScore());
String grpId1 = richRecord1.getGroupId();
String grpId2 = richRecord2.getGroupId();
if (grpId1 == null && grpId2 == null) {
// Both records are original records.
String gid = UUID.randomUUID().toString(); // Generate a new GID.
richRecord1.setGroupId(gid);
richRecord2.setGroupId(gid);
// group size is 0 for none-master record
richRecord1.setGrpSize(0);
richRecord2.setGrpSize(0);
richRecord1.setMaster(false);
richRecord2.setMaster(false);
output(richRecord1);
output(richRecord2);
} else if (grpId1 != null && grpId2 != null) {
// Both records are merged records.
richRecord2.setGroupId(grpId1);
// Put into the map: <gid2,gid1>
oldGID2New.put(grpId2, grpId1);
// Update map where value equals to gid2
List<String> keysOfGID2 = oldGID2New.getKeys(grpId2);
if (keysOfGID2 != null) {
for (String key : keysOfGID2) {
oldGID2New.put(key, grpId1);
}
}
} else if (grpId1 == null) {
// richRecord1 is original record
// GID is the gid of record 2.
richRecord1.setGroupId(richRecord2.getGroupId());
// group size is 0 for none-master record
richRecord1.setGrpSize(0);
richRecord1.setMaster(false);
output(richRecord1);
} else {
// richRecord2 is original record.
// GID
richRecord2.setGroupId(richRecord1.getGroupId());
// group size is 0 for none-master record
richRecord2.setGrpSize(0);
richRecord2.setMaster(false);
output(richRecord2);
}
}
@Override
public void onNewMerge(Record record) {
// record must be RichRecord from DQ grouping implementation.
RichRecord richRecord = (RichRecord) record;
richRecord.setMaster(true);
richRecord.setScore(1.0);
if (record.getGroupId() != null) {
richRecord.setMerged(true);
richRecord.setGrpSize(richRecord.getRelatedIds().size());
if (Double.compare(richRecord.getGroupQuality(), 0.0d) == 0) {
// group quality will be the confidence (score) .
richRecord.setGroupQuality(record.getConfidence());
}
}
}
@Override
public void onRemoveMerge(Record record) {
// record must be RichRecord from DQ grouping implementation.
RichRecord richRecord = (RichRecord) record;
if (richRecord.isMerged()) {
richRecord.setOriginRow(null); // set null original row, won't be usefull anymore after another merge.
richRecord.setGroupQuality(0);
}
richRecord.setMerged(false);
richRecord.setMaster(false);
}
@Override
public void onDifferent(Record record1, Record record2, MatchResult matchResult) {
RichRecord currentRecord = (RichRecord) record2;
currentRecord.setMaster(true);
// The rest of group properties will be set in RichRecord$getOutputRow()
}
@Override
public void onEndRecord(Record record) {
// Nothing todo
}
@Override
public boolean isInterrupted() {
// Nothing todo
return false;
}
@Override
public void onBeginProcessing() {
// Nothing todo
}
@Override
public void onEndProcessing() {
// Nothing todo
}
}
private void output(RichRecord record) {
recordGrouping.outputRow(record);
}
/**
* Before match, move the record(not master) out, only use the master to match. (but need to remember the old GID)
*
* After match: if 1(1,2) combined with 3(3,4), and 3 is the new master,-> 3(1,3), and now we should merge the 2,
* and 4 which didnot attend the second tMatchgroup,--> 3(1,2,3,4), and the group size also need to be changed from
* 2 to 4.
*
* And: TDQ-12659: 1(1,2) and 3(3,4) should also be removed, because they are intermedia masters.
*
* @param indexGID
*/
Map<String, List<List<DQAttribute<?>>>> groupRows;
public void swooshMatchWithMultipass(CombinedRecordMatcher combinedRecordMatcher,
SurvivorShipAlgorithmParams survivorShipAlgorithmParams, int indexGID2) {
groupRows = new HashMap<String, List<List<DQAttribute<?>>>>();
// key:GID, value: list of rows in this group which are not master.
List<RecordGenerator> notMasterRecords = new ArrayList<>();
for (RecordGenerator record : rcdsGenerators) {
List<DQAttribute<?>> originalRow = record.getOriginalRow();
if (!StringUtils.equalsIgnoreCase("true", StringUtils.normalizeSpace(originalRow.get(indexGID2 + 2).getValue()))) {
List<List<DQAttribute<?>>> list = groupRows.get(originalRow.get(indexGID2).getValue());
if (list == null) {
list = new ArrayList<>();
list.add(originalRow);
groupRows.put(originalRow.get(indexGID2).getValue(), list);
} else {
list.add(originalRow);
}
notMasterRecords.add(record);
} else {
resetMasterData(indexGID2, originalRow);
}
}
// remove the not masters before match
rcdsGenerators.removeAll(notMasterRecords);
totalCount = totalCount - notMasterRecords.size();
// match the masters
MultiPassGroupingCallBack multiPassGroupingCallBack = new MultiPassGroupingCallBack();
multiPassGroupingCallBack.setGIDindex(indexGID2);
swooshMatch(combinedRecordMatcher, survivorShipAlgorithmParams, multiPassGroupingCallBack);
// add the not masters again
List<Record> result = algorithm.getResult();
if (result.isEmpty()) {//no masters in the current block, TDQ-12851
for (RecordGenerator record : notMasterRecords) {
List<DQAttribute<?>> originalRow = record.getOriginalRow();
RichRecord createRecord = createRecord(originalRow, originalRow.get(indexGID2).getValue());
output(createRecord);
}
} else {
for (Record master : result) {
String groupId = StringUtils.isBlank(master.getGroupId()) ? ((RichRecord) master).getGID().getValue()
: master.getGroupId();
List<List<DQAttribute<?>>> list = groupRows.get(groupId);
int groupSize = list == null ? 0 : list.size();
restoreMasterData((RichRecord) master, indexGID2, groupSize);
addMembersIntoNewMaster(master, list, groupId);
//remove the record already handled.
groupRows.remove(groupId);
// use the new GID to fetch some members of old GID-- which belong to a temp master in first pass, but
// not a master after 2nd tMatchgroup.
String tempGid = oldGID2New.get(master.getGroupId());
if (!StringUtils.equals(groupId, tempGid)) {
list = groupRows.get(tempGid);
addMembersIntoNewMaster(master, list, groupId);
//remove the record already handled.
groupRows.remove(tempGid);
}
}
//Added TDQ-12851, only handle the lost records, but not the group
if (!groupRows.isEmpty()) {
Iterator<String> iterator = groupRows.keySet().iterator();
while (iterator.hasNext()) {
List<List<DQAttribute<?>>> list = groupRows.get(iterator.next());
for (List<DQAttribute<?>> attri : list) {
RichRecord createRecord = createRecord(attri, attri.get(indexGID2).getValue());
output(createRecord);
}
}
}
}
}
/**
* zshen after resetMasterData method some data has been changed to not master case here do the restore operation
*
* @param indexGID
* @param groupSize
*/
private void restoreMasterData(RichRecord master, int indexGID, int groupSize) {
DQAttribute<?> isMasterAttribute = master.getMASTER();
if (Double.compare(master.getGroupQuality(), 0.0d) == 0 && isMasterAttribute.getValue().equals("false")) { //$NON-NLS-1$
isMasterAttribute.setValue("true"); //$NON-NLS-1$
Double valueDQ = Double.valueOf(master.getGRP_QUALITY().getValue());// getOriginRow().get(indexGID +
// 4).getValue());
master.setGroupQuality(valueDQ);
}
}
/**
* zshen reset master data make it become not master one
*
* @param indexGID
* @param originalRow
*/
private void resetMasterData(int indexGID, List<DQAttribute<?>> originalRow) {
DQAttribute<?> groupSize = originalRow.get(indexGID + 1);
groupSize.setValue("0"); //$NON-NLS-1$
DQAttribute<?> isMaster = originalRow.get(indexGID + 2);
isMaster.setValue("false"); //$NON-NLS-1$
}
/**
* DOC yyin Comment method "addMembersIntoNewMaster".
*
* @param master
* @param list
* @param groupId
*/
private void addMembersIntoNewMaster(Record master, List<List<DQAttribute<?>>> list, String groupId) {
if (list == null) {
return;
}
RichRecord record = (RichRecord) master;
// TDQ-12659 add "-1" for the removed intermediate masters.
// if(record.isMerged()){
// record.setGrpSize(record.getGrpSize() + list.size() - 2);
// }
if (StringUtils.isBlank(master.getGroupId())) {
record.setGroupId(groupId);
}
for (List<DQAttribute<?>> attri : list) {
RichRecord createRecord = createRecord(attri, master.getGroupId());
output(createRecord);
}
}
private RichRecord createRecord(List<DQAttribute<?>> originalRow, String groupID) {
List<Attribute> rowList = new ArrayList<>();
for (DQAttribute<?> attr : originalRow) {
rowList.add(attr);
}
RichRecord record = new RichRecord(rowList, originalRow.get(0).getValue(), 0, "MFB"); //$NON-NLS-1$
record.setGroupId(groupID);
record.setGrpSize(0);
record.setMaster(false);
record.setRecordSize(this.recordGrouping.getOriginalInputColumnSize());
record.setOriginRow(originalRow);
return record;
}
/**
* move the records from old GID to new GID. (for multipass)
*
* @param oldGID
* @param newGID
*/
private void updateNotMasteredRecords(String oldGID, String newGID) {
List<List<DQAttribute<?>>> recordsInFirstGroup = groupRows.get(oldGID);
List<List<DQAttribute<?>>> recordsInNewGroup = groupRows.get(newGID);
if (recordsInFirstGroup != null) {
if (recordsInNewGroup == null) {
groupRows.put(newGID, recordsInFirstGroup);
// grp-size +1
} else {
recordsInNewGroup.addAll(recordsInFirstGroup);
// grp-size = sum of two list size
}
// remove the oldgid's list in: groupRows
groupRows.remove(oldGID);
}
}
class MultiPassGroupingCallBack extends GroupingCallBack {
int indexGID = 0;
@Override
public void onDifferent(Record record1, Record record2, MatchResult matchResult) {
// TODO Auto-generated method stub
super.onDifferent(record1, record2, matchResult);
}
@Override
public void onEndRecord(Record record) {
// TODO Auto-generated method stub
super.onEndRecord(record);
}
public void setGIDindex(int index) {
indexGID = index;
}
/**
* Getter for index of group id.
*
* @return the index of group id
*/
public int getIndexGID() {
return this.indexGID;
}
/**
* Getter for index of group quality.
*
* @return the index of group quality
*/
public int getIndexGQ() {
return this.indexGID + 4;
}
@Override
public void onMatch(Record record1, Record record2, MatchResult matchResult) {
if (!matchResult.isMatch()) {
return;
}
// record1 and record2 must be RichRecord from DQ grouping implementation.
RichRecord richRecord1 = (RichRecord) record1;
RichRecord richRecord2 = (RichRecord) record2;
richRecord1.setConfidence(richRecord1.getScore());
richRecord2.setConfidence(richRecord2.getScore());
String grpId1 = richRecord1.getGroupId();
String grpId2 = richRecord2.getGroupId();
String oldgrpId1 = richRecord1.getGID() == null ? null : richRecord1.getGID().getValue(); // .getOriginRow().get(getIndexGID()).getValue();
String oldgrpId2 = richRecord2.getGID() == null ? null : richRecord2.getGID().getValue();// .getOriginRow().get(getIndexGID()).getValue();
uniqueOldGroupQuality(record1, record2);
if (grpId1 == null && grpId2 == null) {
// Both records are original records.
richRecord1.setGroupId(oldgrpId1);
richRecord2.setGroupId(oldgrpId1);
// group size is 0 for none-master record
richRecord1.setGrpSize(0);
richRecord2.setGrpSize(0);
richRecord1.setMaster(false);
richRecord2.setMaster(false);
// Put into the map: <gid2,gid1>, oldgrpId2 is not used any more, but can be found by oldgrpId1 which is
// used
oldGID2New.put(oldgrpId2, oldgrpId1);
updateNotMasteredRecords(oldgrpId2, oldgrpId1);
output(richRecord1);
output(richRecord2);
} else if (grpId1 != null && grpId2 != null) {
// Both records are merged records.
richRecord2.setGroupId(grpId1);
updateNotMasteredRecords(grpId2, grpId1);
// Put into the map: <gid2,gid1>
oldGID2New.put(grpId1, grpId2);
// Update map where value equals to gid2
List<String> keysOfGID2 = oldGID2New.getKeys(grpId2);
if (keysOfGID2 != null) {
for (String key : keysOfGID2) {
oldGID2New.put(key, grpId1);
}
}
} else if (grpId1 == null) {
// richRecord1 is original record
// GID is the gid of record 2.
richRecord1.setGroupId(grpId2);
// Put into the map: <gid2,gid1>
oldGID2New.put(grpId2, oldgrpId1);
updateNotMasteredRecords(oldgrpId1, grpId2);
// group size is 0 for none-master record
richRecord1.setGrpSize(0);
richRecord1.setMaster(false);
output(richRecord1);
} else {
// richRecord2 is original record.
// GID
richRecord2.setGroupId(richRecord1.getGroupId());
updateNotMasteredRecords(oldgrpId2, richRecord1.getGroupId());
oldGID2New.put(grpId2, oldgrpId1);
// group size is 0 for none-master record
richRecord2.setGrpSize(0);
richRecord2.setMaster(false);
output(richRecord2);
}
}
/**
* zshen Comment method "uniqueOldGroupQuality". unique group quality with min
*
* @param record1
* @param record2
*/
private void uniqueOldGroupQuality(Record record1, Record record2) {
RichRecord richRecord1 = (RichRecord) record1;
RichRecord richRecord2 = (RichRecord) record2;
Double oldGrpQualiry1 = getOldGrpQualiry(richRecord1);
Double oldGrpQualiry2 = getOldGrpQualiry(richRecord2);
if (oldGrpQualiry1 < oldGrpQualiry2) {
setOldGrpQualiry(richRecord2, oldGrpQualiry1);
} else if (oldGrpQualiry1 > oldGrpQualiry2) {
setOldGrpQualiry(richRecord2, oldGrpQualiry2);
}
// oldGrpQualiry1 < oldGrpQualiry2 case we don't need do anything
}
/**
* DOC zshen Comment method "setOldGrpQualiry".
*
* @param double1
*/
private void setOldGrpQualiry(RichRecord richRecord, Double value) {
if (richRecord.getGRP_QUALITY() == null) {
richRecord.setGRP_QUALITY(
new DQAttribute<>(SwooshConstants.GROUP_QUALITY, richRecord.getRecordSize(), StringUtils.EMPTY));
} else {
richRecord.getGRP_QUALITY().setValue(String.valueOf(value));
}
// richRecord.getOriginRow().get(getIndexGQ()).setValue(String.valueOf(value));
}
@Override
public void onRemoveMerge(Record record) {
// record must be RichRecord from DQ grouping implementation.
RichRecord richRecord = (RichRecord) record;
if (richRecord.isMerged()) {
// removeOldValues(richRecord);
richRecord.setGroupQuality(0);
}
richRecord.setMerged(false);
richRecord.setMaster(false);
}
/*
* (non-Javadoc)
*
* @see
* org.talend.dataquality.record.linkage.grouping.TSwooshGrouping.GroupingCallBack#onNewMerge(org.talend.dataquality
* .matchmerge.Record)
*/
@Override
public void onNewMerge(Record record) {
// record must be RichRecord from DQ grouping implementation.
RichRecord richRecord = (RichRecord) record;
richRecord.setMaster(true);
richRecord.setScore(1.0);
if (record.getGroupId() != null) {
richRecord.setMerged(true);
richRecord.setGrpSize(richRecord.getRelatedIds().size());
if (Double.compare(richRecord.getGroupQuality(), 0.0d) == 0) {
// group quality will be the confidence (score) or old group quality decide that by who is minimum.
Double oldGrpQuality = getOldGrpQualiry(richRecord);
richRecord.setGroupQuality(getMergeGQ(oldGrpQuality, record.getConfidence()));
}
}
}
/**
* DOC zshen Comment method "getOldGrpQualiry".
*
* @param richRecord
* @return
*/
private Double getOldGrpQualiry(RichRecord richRecord) {
// String value = richRecord.getOriginRow().get(getIndexGQ()).getValue();
String value = richRecord.getGRP_QUALITY() == null ? null : richRecord.getGRP_QUALITY().getValue();
return Double.valueOf(value == null ? "1.0" : value);
}
/**
* DOC zshen Comment method "getMergeGQ".
*
* @param oldGrpQuality
* @param confidence
* @return minimum one
*/
private double getMergeGQ(Double oldGrpQuality, double confidence) {
if (oldGrpQuality.compareTo(0.0d) == 0) {
return confidence;
}
// get minimum one
return confidence > oldGrpQuality ? oldGrpQuality : confidence;
}
}
public boolean isHasPassedOriginal() {
return hasPassedOriginal;
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
/**
* The Japanese ssn has 12 numbers. As we generate every number from 0 to 8 randomly, it can generate 282 429 536 481 (9
* power 12) ssn numbers.<br>
* However, every generation is independent, this class cannot guarantee the difference among all the execution.
*/
public class GenerateSsnJapan extends Function<String> {
private static final long serialVersionUID = -8621894245597689328L;
@Override
protected String doGenerateMaskedField(String str) {
StringBuilder result = new StringBuilder(EMPTY_STRING);
for (int i = 0; i < 12; ++i) {
result.append(rnd.nextInt(9));
}
return result.toString();
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import static org.junit.Assert.assertEquals;
import java.util.Random;
import org.junit.Before;
import org.junit.Test;
/**
* created by jgonzalez on 29 juin 2015 Detailled comment
*
*/
public class GenerateAccountNumberFormatTest {
private String output;
private GenerateAccountNumberFormat ganf = new GenerateAccountNumberFormat();
@Before
public void setUp() throws Exception {
ganf.setRandom(new Random(4245));
}
@Test
public void testGood() {
ganf.setKeepFormat(true);
output = ganf.generateMaskedRow("DK49 038 4 0 5 5 8 93 22 62"); //$NON-NLS-1$
assertEquals("DK82 765 7 2 0 9 5 51 85 63", output); //$NON-NLS-1$
}
@Test
public void testEmpty() {
ganf.setKeepFormat(true);
ganf.setKeepEmpty(true);
output = ganf.generateMaskedRow(""); //$NON-NLS-1$
assertEquals("", output); //$NON-NLS-1$
}
@Test
public void testGood2() {
output = ganf.generateMaskedRow("DK49 038 4 0 5 5 8 93 22 62"); //$NON-NLS-1$
assertEquals("DK82 7657 2095 5185 63", output); //$NON-NLS-1$
}
@Test
public void testAmericanNumber() {
output = ganf.generateMaskedRow("453 654 94 87 4684 687"); //$NON-NLS-1$
assertEquals("453654948 7657209551", output); //$NON-NLS-1$
}
@Test
public void testAmericanNumber2() {
ganf.setKeepFormat(true);
output = ganf.generateMaskedRow("453 654 94 87 58 425 6"); //$NON-NLS-1$
assertEquals("453 654 94 87 65 720 9551", output); //$NON-NLS-1$
}
@Test
public void testIsNotAmericanNumber() {
output = ganf.generateMaskedRow("454344678 4536"); //$NON-NLS-1$
assertEquals("FR33 7657 2095 51R3 4XZP 6F4O 058", output); //$NON-NLS-1$
}
@Test
public void testBad() {
output = ganf.generateMaskedRow("not an iban"); //$NON-NLS-1$
assertEquals("FR33 7657 2095 51R3 4XZP 6F4O 058", output); //$NON-NLS-1$
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.statistics.datetime;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class SampleTest {
private static List<String> DATE_SAMPLES;
private static List<String> TIME_SAMPLES;
private final Map<String, Set<String>> EXPECTED_FORMATS = new LinkedHashMap<String, Set<String>>() {
private static final long serialVersionUID = 1L;
{
put("3/22/99", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yy" })));
put("22/03/99", new HashSet<String>(Arrays.asList(new String[] //
{ "d/MM/yy", "dd/MM/yy" })));
put("22.03.99", new HashSet<String>(Arrays.asList(new String[] //
{ "dd.MM.yy", "d.MM.yy", "d.M.yy" })));
put("99-03-22", new HashSet<String>(Arrays.asList(new String[] //
{ "yy-MM-dd", "yy-M-d" })));
put("99/03/22", new HashSet<String>(Arrays.asList(new String[] //
{ "yy/MM/dd" })));
put("99-3-22", new HashSet<String>(Arrays.asList(new String[] //
{ "yy-M-d" })));
put("Mar 22, 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "MMMM d, yyyy", "MMM d, yyyy" })));
put("22 mars 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "d MMMM yyyy", "d MMM yyyy", "dd MMMM yyyy" })));
put("22.03.1999", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yyyy", "d.MM.yyyy", "dd.MM.yyyy" })));
put("22-Mar-1999", new HashSet<String>(Arrays.asList(new String[] //
{ "dd-MMM-yyyy", "d-MMM-yyyy" })));
put("22-mar-1999", new HashSet<String>(Arrays.asList(new String[] //
{ "dd-MMM-yyyy", "d-MMM-yyyy" })));
put("22-Mar-1999", new HashSet<String>(Arrays.asList(new String[] //
{ "dd-MMM-yyyy", "d-MMM-yyyy" })));
put("1999-03-22", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-MM-dd", "yyyy-M-d" })));
put("1999/03/22", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy/MM/dd" })));
put("1999-3-22", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-M-d" })));
put("March 22, 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "MMMM d, yyyy" })));
put("22 mars 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "d MMMM yyyy", "d MMM yyyy", "dd MMMM yyyy" })));
put("22. März 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "d. MMMM yyyy" })));
put("22 March 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "d MMMM yyyy", "dd MMMM yyyy" })));
put("22 marzo 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "d MMMM yyyy", "dd MMMM yyyy" })));
put("March 22, 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "MMMM d, yyyy" })));
put("22 mars 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "d MMMM yyyy", "d MMM yyyy", "dd MMMM yyyy" })));
put("1999年3月22日", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy'年'M'月'd'日'" })));
put("Monday, March 22, 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "EEEE, MMMM d, yyyy" })));
put("lundi 22 mars 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "EEEE d MMMM yyyy" })));
put("Montag, 22. März 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "EEEE, d. MMMM yyyy" })));
put("Monday, 22 March 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "EEEE, d MMMM yyyy" })));
put("lunedì 22 marzo 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "EEEE d MMMM yyyy" })));
put("Monday, March 22, 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "EEEE, MMMM d, yyyy" })));
put("lundi 22 mars 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "EEEE d MMMM yyyy" })));
put("1999年3月22日 星期一", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy'年'M'月'd'日' EEEE" })));
put("3/22/99 5:06 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yy h:mm a" })));
put("22/03/99 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "d/MM/yy H:mm", "dd/MM/yy HH:mm" })));
put("22.03.99 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yy H:mm", "d.M.yy HH:mm", "dd.MM.yy HH:mm", "dd.MM.yy H:mm", "d.MM.yy H:mm" })));
put("22/03/99 5.06", new HashSet<String>(Arrays.asList(new String[] //
{ "dd/MM/yy H.mm" })));
put("22/03/99 5:06 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "dd/MM/yy h:mm a" })));
put("99-03-22 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "yy-MM-dd HH:mm" })));
put("99/03/22 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "yy/MM/dd H:mm" })));
put("99-3-22 上午5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "yy-M-d ah:mm" })));
put("Mar 22, 1999 5:06:07 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "MMM d, yyyy h:mm:ss a" })));
put("22 mars 1999 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "d MMM yyyy HH:mm:ss" })));
put("22.03.1999 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "dd.MM.yyyy H:mm:ss", "d.M.yyyy HH:mm:ss", "d.M.yyyy H:mm:ss", "dd.MM.yyyy HH:mm:ss", "d.MM.yyyy H:mm:ss" })));
put("22-Mar-1999 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "dd-MMM-yyyy HH:mm:ss" })));
put("22-mar-1999 5.06.07", new HashSet<String>(Arrays.asList(new String[] //
{ "d-MMM-yyyy H.mm.ss" })));
put("22-Mar-1999 5:06:07 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "d-MMM-yyyy h:mm:ss a" })));
put("1999-03-22 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-MM-dd HH:mm:ss", "yyyy-M-d HH:mm:ss", "yyyy-M-d H:mm:ss" })));
put("1999/03/22 5:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy/MM/dd H:mm:ss" })));
put("1999-3-22 5:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-M-d H:mm:ss" })));
put("March 22, 1999 5:06:07 AM CET", new HashSet<String>(Arrays.asList(new String[] //
{ "MMMM d, yyyy h:mm:ss a z" })));
put("22 mars 1999 05:06:07 CET", new HashSet<String>(Arrays.asList(new String[] //
{ "dd MMMM yyyy HH:mm:ss z", "d MMMM yyyy HH:mm:ss z" })));
put("22. März 1999 05:06:07 MEZ", new HashSet<String>(Arrays.asList(new String[] //
{ "d. MMMM yyyy HH:mm:ss z" })));
put("22 March 1999 05:06:07 CET", new HashSet<String>(Arrays.asList(new String[] //
{ "dd MMMM yyyy HH:mm:ss z", "d MMMM yyyy HH:mm:ss z" })));
put("22 marzo 1999 5.06.07 CET", new HashSet<String>(Arrays.asList(new String[] //
{ "d MMMM yyyy H.mm.ss z" })));
put("March 22, 1999 5:06:07 CET AM", new HashSet<String>(Arrays.asList(new String[] //
{ "MMMM d, yyyy h:mm:ss z a" })));
put("22 mars 1999 05:06:07 CET", new HashSet<String>(Arrays.asList(new String[] //
{ "dd MMMM yyyy HH:mm:ss z", "d MMMM yyyy HH:mm:ss z" })));
put("1999/03/22 5:06:07 CET", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy/MM/dd H:mm:ss z" })));
put("1999年3月22日 上午05时06分07秒", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy'年'M'月'd'日' ahh'时'mm'分'ss'秒'" })));
put("Monday, March 22, 1999 5:06:07 AM CET", new HashSet<String>(Arrays.asList(new String[] //
{ "EEEE, MMMM d, yyyy h:mm:ss a z" })));
put("lundi 22 mars 1999 05 h 06 CET", new HashSet<String>(Arrays.asList(new String[] //
{ "EEEE d MMMM yyyy HH' h 'mm z", "EEEE d MMMM yyyy H' h 'mm z" })));
put("Montag, 22. März 1999 05:06 Uhr MEZ", new HashSet<String>(Arrays.asList(new String[] //
{ "EEEE, d. MMMM yyyy HH:mm' Uhr 'z" })));
put("Monday, 22 March 1999 05:06:07 o'clock CET", new HashSet<String>(Arrays.asList(new String[] //
{ "EEEE, d MMMM yyyy HH:mm:ss 'o''clock' z" })));
put("lunedì 22 marzo 1999 5.06.07 CET", new HashSet<String>(Arrays.asList(new String[] //
{ "EEEE d MMMM yyyy H.mm.ss z" })));
put("Monday, March 22, 1999 5:06:07 o'clock AM CET", new HashSet<String>(Arrays.asList(new String[] //
{ "EEEE, MMMM d, yyyy h:mm:ss 'o''clock' a z" })));
put("lundi 22 mars 1999 5 h 06 CET", new HashSet<String>(Arrays.asList(new String[] //
{ "EEEE d MMMM yyyy H' h 'mm z" })));
put("1999年3月22日 5時06分07秒 CET", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy'年'M'月'd'日' H'時'mm'分'ss'秒' z" })));
put("1999年3月22日 星期一 上午05时06分07秒 CET", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy'年'M'月'd'日' EEEE ahh'时'mm'分'ss'秒' z" })));
put("22/03/99 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "dd/MM/yy HH:mm:ss" })));
put("22.03.99 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "dd.MM.yy HH:mm:ss" })));
put("22.03.1999 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yyyy HH:mm", "dd.MM.yyyy HH:mm", "d.M.yyyy H:mm" })));
put("99/03/22 5:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "yy/MM/dd H:mm:ss" })));
put("1999/03/22 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy/MM/dd H:mm" })));
put("22/03/1999", new HashSet<String>(Arrays.asList(new String[] //
{ "d/M/yyyy", "dd/MM/yyyy" })));
put("22/03/1999 5:06 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "dd/MM/yyyy h:mm a", "d/M/yyyy h:mm a" })));
put("22/03/1999 5:06:07 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "d/M/yyyy h:mm:ss a", "dd/MM/yyyy h:mm:ss a" })));
put("22/03/1999 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "dd/MM/yyyy H:mm", "dd/MM/yyyy HH:mm", "d/M/yyyy HH:mm", "d/M/yyyy H:mm" })));
put("22/03/1999 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "d/M/yyyy H:mm:ss", "dd/MM/yyyy HH:mm:ss", "dd/MM/yyyy H:mm:ss", "d/M/yyyy HH:mm:ss" })));
put("22/03/1999 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "dd/MM/yyyy H:mm", "d/M/yyyy H:mm" })));
put("22/03/1999 5:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "d/M/yyyy H:mm:ss", "dd/MM/yyyy H:mm:ss" })));
put("22/3/1999", new HashSet<String>(Arrays.asList(new String[] //
{ "d/M/yyyy" })));
put("22/3/1999 5:06 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "d/M/yyyy h:mm a" })));
put("22/3/1999 5:06:07 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "d/M/yyyy h:mm:ss a" })));
put("22/3/1999 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "d/M/yyyy HH:mm", "d/M/yyyy H:mm" })));
put("22/3/1999 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "d/M/yyyy H:mm:ss", "d/M/yyyy HH:mm:ss" })));
put("22/3/1999 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "d/M/yyyy H:mm" })));
put("22/3/1999 5:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "d/M/yyyy H:mm:ss" })));
put("03/22/1999", new HashSet<String>(Arrays.asList(new String[] //
{ "MM/dd/yyyy", "M/d/yyyy" })));
put("03/22/1999 5:06 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yyyy h:mm a", "MM/dd/yyyy h:mm a" })));
put("03/22/1999 5:06:07 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yyyy h:mm:ss a", "MM/dd/yyyy h:mm:ss a" })));
put("03/22/1999 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yyyy HH:mm", "MM/dd/yyyy H:mm", "MM/dd/yyyy HH:mm", "M/d/yyyy H:mm" })));
put("03/22/1999 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "MM/dd/yyyy HH:mm:ss", "M/d/yyyy HH:mm:ss", "M/d/yyyy H:mm:ss", "MM/dd/yyyy H:mm:ss" })));
put("03/22/1999 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "MM/dd/yyyy H:mm", "M/d/yyyy H:mm" })));
put("03/22/1999 5:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yyyy H:mm:ss", "MM/dd/yyyy H:mm:ss" })));
put("3/22/1999", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yyyy" })));
put("3/22/1999 5:06 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yyyy h:mm a" })));
put("3/22/1999 5:06:07 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yyyy h:mm:ss a" })));
put("3/22/1999 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yyyy HH:mm", "M/d/yyyy H:mm" })));
put("3/22/1999 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yyyy HH:mm:ss", "M/d/yyyy H:mm:ss" })));
put("3/22/1999 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yyyy H:mm" })));
put("3/22/1999 5:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yyyy H:mm:ss" })));
put("3-22-99", new HashSet<String>(Arrays.asList(new String[] //
{ "M-d-yy" })));
put("3-22-99 5:06 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "M-d-yy h:mm a" })));
put("3-22-99 5:06:07 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "M-d-yy h:mm:ss a" })));
put("3-22-99 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "M-d-yy H:mm", "M-d-yy HH:mm" })));
put("3-22-99 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "M-d-yy HH:mm:ss", "M-d-yy H:mm:ss" })));
put("3-22-99 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "M-d-yy H:mm" })));
put("3-22-99 5:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "M-d-yy H:mm:ss" })));
put("3-22-1999", new HashSet<String>(Arrays.asList(new String[] //
{ "M-d-yyyy" })));
put("3-22-1999 5:06 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "M-d-yyyy h:mm a" })));
put("3-22-1999 5:06:07 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "M-d-yyyy h:mm:ss a" })));
put("3-22-1999 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "M-d-yyyy H:mm", "M-d-yyyy HH:mm" })));
put("3-22-1999 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "M-d-yyyy HH:mm:ss", "M-d-yyyy H:mm:ss" })));
put("3-22-1999 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "M-d-yyyy H:mm" })));
put("3-22-1999 5:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "M-d-yyyy H:mm:ss" })));
put("1999-3-22 5:06 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-M-d h:mm a" })));
put("1999-3-22 5:06:07 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-M-d h:mm:ss a" })));
put("1999-3-22 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-M-d HH:mm", "yyyy-M-d H:mm" })));
put("1999-3-22 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-M-d HH:mm:ss", "yyyy-M-d H:mm:ss" })));
put("1999-3-22 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-M-d H:mm" })));
put("3/22/99 5:06:07 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yy h:mm:ss a" })));
put("3/22/99 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yy HH:mm", "M/d/yy H:mm" })));
put("3/22/99 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yy HH:mm:ss", "M/d/yy H:mm:ss" })));
put("3/22/99 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yy H:mm" })));
put("3/22/99 5:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "M/d/yy H:mm:ss" })));
put("Mar 22 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "MMM d yyyy", "MMMM d yyyy" })));
put("Mar.22.1999", new HashSet<String>(Arrays.asList(new String[] //
{ "MMM.dd.yyyy" })));
put("March 22 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "MMMM d yyyy" })));
put("1999-03-22 05:06:07.0", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-MM-dd HH:mm:ss.S" })));
put("22/Mar/1999 5:06:07 +0100", new HashSet<String>(Arrays.asList(new String[] //
{ "d/MMM/yyyy H:mm:ss Z" })));
put("22-Mar-99 05.06.07.000000888 AM", new HashSet<String>(Arrays.asList(new String[] //
{ "dd-MMM-yy hh.mm.ss.nnnnnnnnn a" })));
put("Mon Mar 22 05:06:07 CET 1999", new HashSet<String>(Arrays.asList(new String[] //
{ "EEE MMM dd HH:mm:ss z yyyy" })));
put("19990322+0100", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyyMMddZ" })));
put("19990322", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyyMMdd" })));
put("1999-03-22+01:00", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-MM-ddXXX" })));
put("1999-03-22T05:06:07.000[Europe/Paris]", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-MM-dd'T'HH:mm:ss.SSS'['VV']'" })));
put("1999-03-22T05:06:07.000", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-MM-dd'T'HH:mm:ss.SSS" })));
put("1999-03-22T05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-MM-dd'T'HH:mm:ss" })));
put("1999-03-22T05:06:07.000Z", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" })));
put("1999-03-22T05:06:07.000+01:00", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" })));
put("1999-03-22T05:06:07+01:00", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-MM-dd'T'HH:mm:ssXXX" })));
put("1999-081+01:00", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-DDDXXX" })));
put("1999-W13-4+01:00", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-'W'w-WXXX" })));
put("1999-03-22T05:06:07.000+01:00[Europe/Paris]", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-MM-dd'T'HH:mm:ss.SSSXXX'['VV']'" })));
put("1999-03-22T05:06:07+01:00[Europe/Paris]", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-MM-dd'T'HH:mm:ssXXX'['VV']'" })));
put("Mon, 22 Mar 1999 05:06:07 +0100", new HashSet<String>(Arrays.asList(new String[] //
{ "EEE, d MMM yyyy HH:mm:ss Z" })));
put("22 Mar 1999 05:06:07 +0100", new HashSet<String>(Arrays.asList(new String[] //
{ "d MMM yyyy HH:mm:ss Z" })));
put("22.3.99", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yy" })));
put("22-03-99", new HashSet<String>(Arrays.asList(new String[] //
{ "d-M-yy", "dd-MM-yy" })));
put("22/03/99", new HashSet<String>(Arrays.asList(new String[] //
{ "d/MM/yy", "dd/MM/yy" })));
put("22.03.99", new HashSet<String>(Arrays.asList(new String[] //
{ "dd.MM.yy", "d.MM.yy", "d.M.yy" })));
put("22.3.1999", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yyyy" })));
put("1999.03.22", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy.MM.dd" })));
put("1999.03.22.", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy.MM.dd." })));
put("99. 3. 22", new HashSet<String>(Arrays.asList(new String[] //
{ "yy. M. d" })));
put("99.3.22", new HashSet<String>(Arrays.asList(new String[] //
{ "yy.M.d" })));
put("99.22.3", new HashSet<String>(Arrays.asList(new String[] //
{ "yy.d.M" })));
put("22-3-99", new HashSet<String>(Arrays.asList(new String[] //
{ "d-M-yy" })));
put("22-03-1999", new HashSet<String>(Arrays.asList(new String[] //
{ "dd-MM-yyyy" })));
put("22.3.99.", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yy." })));
put("22.03.1999", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yyyy", "d.MM.yyyy", "dd.MM.yyyy" })));
put("1999. 3. 22", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy. M. d" })));
put("1999.22.3", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy.d.M" })));
put("22.03.1999.", new HashSet<String>(Arrays.asList(new String[] //
{ "dd.MM.yyyy." })));
put("22.3.99 5.06", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yy H.mm" })));
put("22.3.99 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yy H:mm" })));
put("22-03-99 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "d-M-yy H:mm", "dd-MM-yy HH:mm" })));
put("22/03/99 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "d/MM/yy H:mm" })));
put("22.03.99 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yy H:mm", "dd.MM.yy H:mm", "d.MM.yy H:mm" })));
put("22.3.1999 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yyyy H:mm" })));
put("99/03/22 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "yy/MM/dd HH:mm", "yy/MM/dd H:mm" })));
put("05:06 22/03/99", new HashSet<String>(Arrays.asList(new String[] //
{ "HH:mm dd/MM/yy" })));
put("1999.03.22 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy.MM.dd HH:mm" })));
put("1999.03.22. 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy.MM.dd. H:mm" })));
put("22.3.1999 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yyyy HH:mm", "d.M.yyyy H:mm" })));
put("99.3.22 05.06", new HashSet<String>(Arrays.asList(new String[] //
{ "yy.M.d HH.mm" })));
put("99.22.3 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "yy.d.M HH:mm" })));
put("22.3.99 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yy H:mm", "d.M.yy HH:mm" })));
put("22-3-99 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "d-M-yy H:mm" })));
put("22-03-1999 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "dd-MM-yyyy H:mm" })));
put("22.03.99 5:06", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yy H:mm", "dd.MM.yy H:mm", "d.MM.yy H:mm" })));
put("99-03-22 5.06.PD", new HashSet<String>(Arrays.asList(new String[] //
{ "yy-MM-dd h.mm.a" })));
put("22.3.99. 05.06", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yy. HH.mm" })));
put("1999-03-22 05:06", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-M-d HH:mm", "yyyy-MM-dd HH:mm", "yyyy-M-d H:mm" })));
put("05:06 22/03/1999", new HashSet<String>(Arrays.asList(new String[] //
{ "HH:mm dd/MM/yyyy" })));
put("22.3.1999 5.06.07", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yyyy H.mm.ss" })));
put("22.3.1999 5:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yyyy H:mm:ss" })));
put("22-03-1999 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "dd-MM-yyyy HH:mm:ss" })));
put("22.03.1999 5:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "dd.MM.yyyy H:mm:ss", "d.M.yyyy H:mm:ss", "d.MM.yyyy H:mm:ss" })));
put("05:06:07 22/03/1999", new HashSet<String>(Arrays.asList(new String[] //
{ "HH:mm:ss dd/MM/yyyy" })));
put("1999.03.22 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy.MM.dd HH:mm:ss" })));
put("1999.03.22. 5:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy.MM.dd. H:mm:ss" })));
put("22.3.1999 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yyyy HH:mm:ss", "d.M.yyyy H:mm:ss" })));
put("1999-03-22 05.06.07", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-MM-dd HH.mm.ss" })));
put("1999.22.3 05:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy.d.M HH:mm:ss" })));
put("22.3.1999 05:06:", new HashSet<String>(Arrays.asList(new String[] //
{ "d.M.yyyy HH:mm:" })));
put("22.03.1999 5:06:07", new HashSet<String>(Arrays.asList(new String[] //
{ "dd.MM.yyyy H:mm:ss", "d.M.yyyy H:mm:ss", "d.MM.yyyy H:mm:ss" })));
put("1999-03-22 5:06:07.PD", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-MM-dd h:mm:ss.a" })));
put("22.03.1999. 05.06.07", new HashSet<String>(Arrays.asList(new String[] //
{ "dd.MM.yyyy. HH.mm.ss" })));
put("05:06:07 22-03-1999", new HashSet<String>(Arrays.asList(new String[] //
{ "HH:mm:ss dd-MM-yyyy" })));
put("1999-03-22 5.06.07.PD CET", new HashSet<String>(Arrays.asList(new String[] //
{ "yyyy-MM-dd h.mm.ss.a z" })));
put("22.03.1999. 05.06.07 CET", new HashSet<String>(Arrays.asList(new String[] //
{ "dd.MM.yyyy. HH.mm.ss z" })));
}
};
@BeforeClass
public static void loadTestData() throws IOException {
InputStream dateInputStream = SystemDateTimePatternManager.class.getResourceAsStream("DateSampleTable.txt");
DATE_SAMPLES = IOUtils.readLines(dateInputStream, "UTF-8");
InputStream timeInputStream = SystemDateTimePatternManager.class.getResourceAsStream("TimeSampleTable.txt");
TIME_SAMPLES = IOUtils.readLines(timeInputStream, "UTF-8");
}
@Test
public void testDatesWithMultipleFormats() throws IOException {
for (String sample : EXPECTED_FORMATS.keySet()) {
Set<String> patternSet = SystemDateTimePatternManager.datePatternReplace(sample);
assertEquals("Unexpected Format Set on sample <" + sample + ">", EXPECTED_FORMATS.get(sample), patternSet);
}
}
@Test
@Ignore
public void prepareDatesWithMultipleFormats() throws IOException {
Set<String> datesWithMultipleFormats = new HashSet<String>();
StringBuilder sb = new StringBuilder();
for (int i = 1; i < DATE_SAMPLES.size(); i++) {
String line = DATE_SAMPLES.get(i);
if (!"".equals(line.trim())) {
String[] sampleLine = line.trim().split("\t");
String sample = sampleLine[0];
Set<String> patternSet = SystemDateTimePatternManager.datePatternReplace(sample);
if (patternSet.size() > 0) {
sb.append("put(\"").append(sample).append("\", new HashSet<String>(Arrays.asList(new String[] //\n\t{ ");
datesWithMultipleFormats.add(sample);
for (String p : patternSet) {
sb.append("\"").append(p).append("\",");
}
sb.deleteCharAt(sb.length() - 1);
sb.append(" })));\n");
}
}
}
System.out.println(sb.toString());
}
@Test
public void testAllSupportedDatesWithRegexes() throws IOException {
for (int i = 1; i < DATE_SAMPLES.size(); i++) {
String line = DATE_SAMPLES.get(i);
if (!"".equals(line.trim())) {
String[] sampleLine = line.trim().split("\t");
String sample = sampleLine[0];
// String expectedPattern = sampleLine[1];
// String locale = sampleLine[2];
// System.out.println(SystemDateTimePatternManager.isDate(sample) + "\t" + locale + "\t" + sample + "\t"
// + expectedPattern);
// System.out.println(SystemDateTimePatternManager.datePatternReplace(sample));
assertTrue(sample + " is expected to be a valid date but actually not.",
SystemDateTimePatternManager.isDate(sample));
}
}
}
@Test
public void testAllSupportedTimesWithRegexes() throws IOException {
for (int i = 1; i < TIME_SAMPLES.size(); i++) {
String line = TIME_SAMPLES.get(i);
if (!"".equals(line.trim())) {
String[] sampleLine = line.trim().split("\t");
String sample = sampleLine[0];
// String expectedPattern = sampleLine[1];
// String locale = sampleLine[2];
// System.out.println(SystemDateTimePatternManager.isTime(sample) + "\t" + locale + "\t" + sample + "\t"
// + expectedPattern);
assertTrue(sample + " is expected to be a valid time but actually not.",
SystemDateTimePatternManager.isTime(sample));
}
}
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.semantic.statistics;
import static org.junit.Assert.assertEquals;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.talend.dataquality.common.inference.Analyzer;
import org.talend.dataquality.common.inference.Analyzers;
import org.talend.dataquality.common.inference.Analyzers.Result;
import org.talend.dataquality.semantic.classifier.SemanticCategoryEnum;
import org.talend.dataquality.semantic.recognizer.CategoryRecognizerBuilder;
public class SemanticAnalyzerTest {
private CategoryRecognizerBuilder builder;
final List<String[]> TEST_RECORDS = new ArrayList<String[]>() {
private static final long serialVersionUID = 1L;
{
add(new String[] { "CHAT" });
add(new String[] { "United States" });
add(new String[] { "France" });
}
};
final List<String[]> TEST_RECORDS_TAGADA = new ArrayList<String[]>() {
private static final long serialVersionUID = 1L;
{
add(new String[] { "1", "Lennon", "John", "40", "10/09/1940", "false" });
add(new String[] { "2", "Bowie", "David", "67", "01/08/1947", "true" });
}
};
final List<String> EXPECTED_CATEGORY_TAGADA = Arrays
.asList(new String[] { "", SemanticCategoryEnum.LAST_NAME.name(), SemanticCategoryEnum.FIRST_NAME.name(), "", "" });
@Before
public void setUp() throws Exception {
final URI ddPath = this.getClass().getResource(CategoryRecognizerBuilder.DEFAULT_DD_PATH).toURI();
final URI kwPath = this.getClass().getResource(CategoryRecognizerBuilder.DEFAULT_KW_PATH).toURI();
builder = CategoryRecognizerBuilder.newBuilder() //
.ddPath(ddPath) //
.kwPath(kwPath) //
.lucene();
}
@Test
public void testTagada() {
SemanticAnalyzer semanticAnalyzer = new SemanticAnalyzer(builder);
Analyzer<Result> analyzer = Analyzers.with(semanticAnalyzer);
analyzer.init();
for (String[] record : TEST_RECORDS_TAGADA) {
analyzer.analyze(record);
}
analyzer.end();
for (int i = 0; i < EXPECTED_CATEGORY_TAGADA.size(); i++) {
Result result = analyzer.getResult().get(i);
if (result.exist(SemanticType.class)) {
final SemanticType semanticType = result.get(SemanticType.class);
final String suggestedCategory = semanticType.getSuggestedCategory();
assertEquals("Unexpected Category.", EXPECTED_CATEGORY_TAGADA.get(i), suggestedCategory);
}
}
}
@Test
public void testSetLimit() {
SemanticAnalyzer semanticAnalyzer = new SemanticAnalyzer(builder);
semanticAnalyzer.setLimit(0);
assertEquals("Unexpected Category.", SemanticCategoryEnum.COUNTRY.getId(), getSuggestedCategorys(semanticAnalyzer));
semanticAnalyzer.setLimit(1);
assertEquals("Unexpected Category.", SemanticCategoryEnum.ANIMAL.getId(), getSuggestedCategorys(semanticAnalyzer));
semanticAnalyzer.setLimit(3);
assertEquals("Unexpected Category.", SemanticCategoryEnum.COUNTRY.getId(), getSuggestedCategorys(semanticAnalyzer));
}
private String getSuggestedCategorys(SemanticAnalyzer semanticAnalyzer) {
Analyzer<Result> analyzer = Analyzers.with(semanticAnalyzer);
analyzer.init();
for (String[] record : TEST_RECORDS) {
analyzer.analyze(record);
}
analyzer.end();
Result result = analyzer.getResult().get(0);
if (result.exist(SemanticType.class)) {
final SemanticType semanticType = result.get(SemanticType.class);
final String suggestedCategory = semanticType.getSuggestedCategory();
return suggestedCategory;
}
return null;
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Random;
import org.junit.Test;
/**
* created by jgonzalez on 1 juil. 2015 Detailled comment
*
*/
public class ReplaceLastCharsLongTest {
private long output;
private Long input = 123456L;
private ReplaceLastCharsLong rlcl = new ReplaceLastCharsLong();
@Test
public void testGood() {
rlcl.parse("3", false, new Random(42));
output = rlcl.generateMaskedRow(input);
assertEquals(123830L, output); // $NON-NLS-1$
}
@Test
public void testDummyGood() {
rlcl.parse("7", false, new Random(42));
output = rlcl.generateMaskedRow(input);
assertEquals(830807L, output); // $NON-NLS-1$
}
@Test
public void testParameters() {
rlcl.parse("4,9", false, new Random(42));
output = rlcl.generateMaskedRow(input);
assertEquals(129999, output); // $NON-NLS-1$
}
@Test
public void testWrongParameters() {
try {
rlcl.parse("0,x", false, new Random(42));
fail("should get exception with input " + rlcl.parameters); //$NON-NLS-1$
} catch (Exception e) {
assertTrue("expect illegal argument exception ", e instanceof IllegalArgumentException); //$NON-NLS-1$
}
assertEquals(0L, output); // $NON-NLS-1$
}
}
<file_sep>package org.talend.dataquality.datamasking.functions;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
public final class CharactersOperationUtils {
private CharactersOperationUtils() {
}
protected static final Pattern patternNumber = Pattern.compile("[0-9]+");
protected static final Pattern patternCharacter = Pattern.compile(".");
protected static final Pattern patternDigit = Pattern.compile("[0-9]");
private static final boolean factorise(String[] parameters, int length, Pattern pattern) {
return parameters.length == length && pattern.matcher(parameters[length - 1]).matches();
}
private static final boolean factorise2Indexes(String[] parameters) {
return patternNumber.matcher(parameters[0]).matches() && patternNumber.matcher(parameters[1]).matches();
}
public static final boolean validParameters2Indexes(String[] parameters) {
return parameters != null && parameters.length == 2 && factorise2Indexes(parameters);
}
public static final boolean validParameters2Indexes1CharReplace(String[] parameters) {
return parameters != null && (parameters.length == 2 || factorise(parameters, 3, patternCharacter))
&& factorise2Indexes(parameters);
}
public static final boolean validParameters1Number1DigitReplace(String[] parameters) {
return parameters != null && (parameters.length == 1 || factorise(parameters, 2, patternDigit))
&& patternNumber.matcher(parameters[0]).matches();
}
public static final boolean validParameters1Number1CharReplace(String[] parameters) {
return parameters != null && (parameters.length == 1 || factorise(parameters, 2, patternCharacter))
&& patternNumber.matcher(parameters[0]).matches();
}
public static final boolean validParameters1Number(String[] parameters) {
return parameters != null && factorise(parameters, 1, patternNumber);
}
public static final boolean validParameters1DigitReplace(String[] parameters) {
return parameters == null || (parameters.length == 1
&& (StringUtils.isEmpty(parameters[0]) || patternDigit.matcher(parameters[0]).matches()));
}
public static final boolean validParameters1CharReplace(String[] parameters) {
return parameters == null || (parameters.length == 1
&& (StringUtils.isEmpty(parameters[0]) || patternCharacter.matcher(parameters[0]).matches()));
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import org.apache.commons.lang.StringUtils;
/**
* created by jgonzalez on 19 juin 2015. This function produces a correct account number and tries to keep the country
* where it's from.
*
*/
public class GenerateAccountNumberFormat extends GenerateAccountNumber {
private static final long serialVersionUID = 116648954835024228L;
@Override
protected String doGenerateMaskedField(String str) {
String accountNumber = removeFormatInString(str); // $NON-NLS-1$ //$NON-NLS-2$
StringBuilder accountNumberFormat = new StringBuilder();
boolean isAmerican = false;
if (!StringUtils.isEmpty(accountNumber) && accountNumber.length() > 9) {
try {
if (Character.isDigit(accountNumber.charAt(0)) && isAmericanAccount(accountNumber)) {
accountNumberFormat = generateAmericanAccountNumber(accountNumber);
isAmerican = true;
} else {
accountNumberFormat = generateIban(accountNumber);
}
if (keepFormat)
return insertFormatInString(str, accountNumberFormat);
} catch (NumberFormatException e) {
accountNumberFormat = generateIban();
}
} else {
accountNumberFormat = generateIban();
}
if (isAmerican) {
accountNumberFormat.insert(9, ' ');
} else {
for (int i = 4; i < accountNumberFormat.length(); i += 5) {
accountNumberFormat.insert(i, ' ');
}
}
return accountNumberFormat.toString();
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
/**
*
* @author dprot
* This class proposes a pure-random Chinese SSN number
* The Chinese SSN has 4 fields : the first one, on 6 digits, stands for the birth place; the second one, with format
* YYYYMMDD for the date of birth; the third one, with 3 digits; the last one, on one digit, is a checksum key
*/
public class GenerateSsnChn extends Function<String> {
private static final long serialVersionUID = 8845031997964609626L;
private static final Logger LOGGER = Logger.getLogger(GenerateSsnChn.class);
public static final List<Integer> monthSize = Collections
.unmodifiableList(Arrays.asList(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31));
private static final List<Integer> keyWeight = Collections
.unmodifiableList(Arrays.asList(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2));
private static final int KeyMod = 11; // $NON-NLS-1$
private static final List<String> keyString = Collections
.unmodifiableList(Arrays.asList("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"));
private String computeChineseKey(String ssnNumber) {
int key = 0;
for (int i = 0; i < 17; i++) {
key += Character.getNumericValue(ssnNumber.charAt(i)) * keyWeight.get(i);
}
key = key % KeyMod;
return keyString.get(key);
}
@Override
protected String doGenerateMaskedField(String str) {
StringBuilder result = new StringBuilder(EMPTY_STRING);
// Region code
InputStream is = GenerateUniqueSsnChn.class.getResourceAsStream("RegionListChina.txt");
List<String> places = null;
try {
places = IOUtils.readLines(is, "UTF-8");
} catch (IOException e) {
LOGGER.error("The file of chinese regions is not correctly loaded " + e.getMessage(), e);
}
result.append(places.get(rnd.nextInt(places.size())));
// Year
int yyyy = rnd.nextInt(200) + 1900;
result.append(yyyy);
// Month
int mm = rnd.nextInt(12) + 1;
if (mm < 10) {
result.append("0"); //$NON-NLS-1$
}
result.append(mm);
// Day
int dd = 1 + rnd.nextInt(monthSize.get(mm - 1));
if (dd < 10) {
result.append("0"); //$NON-NLS-1$
}
// Birth rank
result.append(dd);
for (int i = 0; i < 3; ++i) {
result.append(rnd.nextInt(10));
}
// Checksum
String controlKey = computeChineseKey(result.toString());
result.append(controlKey);
return result.toString();
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.sampling.parallel;
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SQLContext;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.talend.dataquality.duplicating.AllDataqualitySamplingTests;
public class SparkSamplingUtilTest implements Serializable {
private static final int SAMPLE_SIZE = 10;
private static final int ORIGINAL_COUNT = 100;
private ReservoirSamplerWithBinaryHeap<TestRowStruct> sampler;
private TestRowStruct[] testers;
private static final Integer[] EXPECTED_SAMPLES_LIST = { 31, 79, 93, 32, 45, 90, 15, 59, 91, 89 };
private static JavaSparkContext sc;
@BeforeClass
public static void beforeClass() {
sc = new JavaSparkContext(new SparkConf().setAppName("Simple Application").setMaster("local[1]"));
}
@Before
public void init() {
testers = new TestRowStruct[ORIGINAL_COUNT];
for (int j = 0; j < ORIGINAL_COUNT; j++) {
TestRowStruct struct = new TestRowStruct();
struct.id = j + 1;
struct.city = "city" + (j + 1);
testers[j] = struct;
}
}
@Test
public void testSamplePairList() {
JavaRDD<TestRowStruct> rdd = sc.parallelize(Arrays.asList(testers));
SparkSamplingUtil<TestRowStruct> sampler = new SparkSamplingUtil<>(AllDataqualitySamplingTests.RANDOM_SEED);
List<ImmutablePair<Double, TestRowStruct>> topPairs = sampler.getSamplePairList(rdd, SAMPLE_SIZE);
for (int i = 0; i < topPairs.size(); i++) {
assertTrue("The ID " + topPairs.get(i).getRight().getId() + " is expected",
Arrays.asList(EXPECTED_SAMPLES_LIST).contains(topPairs.get(i).getRight().getId()));
}
}
@Test
public void getSamplePairListForDataFrame() {
SQLContext sqlContext = new org.apache.spark.sql.SQLContext(sc);
JavaRDD<TestRowStruct> rdd = sc.parallelize(Arrays.asList(testers));
DataFrame df = sqlContext.createDataFrame(rdd, TestRowStruct.class);
SparkSamplingUtil<TestRowStruct> sampler = new SparkSamplingUtil<>(AllDataqualitySamplingTests.RANDOM_SEED);
List<ImmutablePair<Double, Row>> sampleList = sampler.getSamplePairList(df, 5);
for (int i = 0; i < sampleList.size(); i++) {
assertTrue("The ID " + sampleList.get(i).getRight().getInt(1) + " is expected",
Arrays.asList(EXPECTED_SAMPLES_LIST).contains(sampleList.get(i).getRight().getInt(1)));
}
}
@Test
public void testGetSampleList() {
JavaRDD<TestRowStruct> rdd = sc.parallelize(Arrays.asList(testers));
SparkSamplingUtil<TestRowStruct> sampler = new SparkSamplingUtil<>(AllDataqualitySamplingTests.RANDOM_SEED);
List<TestRowStruct> sampleList = sampler.getSampleList(rdd, SAMPLE_SIZE);
for (int i = 0; i < sampleList.size(); i++) {
assertTrue("The ID " + sampleList.get(i).getId() + " is expected",
Arrays.asList(EXPECTED_SAMPLES_LIST).contains(sampleList.get(i).getId()));
}
}
public class TestRowStruct implements Serializable {
private Integer id;
private String city;
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return id + " -> " + city; //$NON-NLS-1$
}
}
}
<file_sep>package org.talend.dataquality.datamasking.shuffling;
import java.util.List;
import java.util.concurrent.Callable;
/**
* This class implements the Callable interface which returns a shuffled table.
*/
public class RowDataCallable<V> implements Callable<List<List<Object>>> {
protected List<List<Object>> rows;
protected ShuffleColumn shuffleColumn;
/**
* Constructor
*
* @param shuffleColumn ShuffleColumn object
* @param rows a table
*/
public RowDataCallable(ShuffleColumn shuffleColumn, List<List<Object>> rows) {
super();
this.shuffleColumn = shuffleColumn;
this.rows = rows;
}
@Override
public List<List<Object>> call() throws Exception {
shuffleColumn.shuffle(rows);
return rows;
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.standardization.phone;
import java.util.List;
import java.util.Locale;
/**
* As per {@link #PhoneNumberHandlerBase} ,but use the default region code and default Local language in this class.
*/
public class PhoneNumberHandler {
private String defaultRegion = Locale.getDefault().getCountry();
private Locale defaultLocale = Locale.getDefault();
/**
*
* As per {@link #isValidPhoneNumber(Object, String)} but explicitly the region code is default.
*
* @param data the data that we want to validate
* @return
*/
public boolean isValidPhoneNumber(Object data) {
return PhoneNumberHandlerBase.isValidPhoneNumber(data, defaultRegion);
}
/**
*
* As per {@link #isPossiblePhoneNumber(Object, String)} but explicitly the region code is default.
*
* @param data the data that we want to validate
* @return
*/
public boolean isPossiblePhoneNumber(Object data) {
return PhoneNumberHandlerBase.isPossiblePhoneNumber(data, defaultRegion);
}
/**
*
* As per {@link #formatE164(Object, String)} but explicitly the region code is default.
*
* @param data
* @return
*/
public String formatE164(Object data) {
return PhoneNumberHandlerBase.formatE164(data, defaultRegion);
}
/**
*
* As per {@link #formatInternational(Object, String)} but explicitly the region code is default.
*
* @param data
* @return return a formated number like as "+1 242-365-1234".
*/
public String formatInternational(Object data) {
return PhoneNumberHandlerBase.formatInternational(data, defaultRegion);
}
/**
*
* As per {@link #formatNational(Object, String)} but explicitly the region code is default.
*
* @param data
* @return the formatted phone number like as "(242) 365-1234"
*/
public String formatNational(Object data) {
return PhoneNumberHandlerBase.formatNational(data, defaultRegion);
}
/**
*
* As per {@link #formatRFC396(Object, String)} but explicitly the region code is default.
*
* @param data
* @return the formatted phone number like as "tel:+1-242-365-1234"
*/
public String formatRFC396(Object data) {
return PhoneNumberHandlerBase.formatRFC396(data, defaultRegion);
}
/**
*
* As per {@link #getPhoneNumberType(Object, String)} but explicitly the region code is default.
*
* @param data
* @return
*/
public PhoneNumberTypeEnum getPhoneNumberType(Object data) {
return PhoneNumberHandlerBase.getPhoneNumberType(data, defaultRegion);
}
/**
*
* As per {@link #getTimeZonesForNumber(Object, String)} but explicitly the region code is default.
*
* @param data
* @return
*/
public List<String> getTimeZonesForNumber(Object data) {
return PhoneNumberHandlerBase.getTimeZonesForNumber(data, defaultRegion);
}
/**
*
* As per {@link #getGeocoderDescriptionForNumber(Object, Locale)} but explicitly the Locale is default.
*
* @param data
* @return
*/
public String getGeocoderDescriptionForNumber(Object data) {
return PhoneNumberHandlerBase.getGeocoderDescriptionForNumber(data, defaultRegion, defaultLocale);
}
/**
*
* As per {@link #getCarrierNameForNumber(Object, String)} but explicitly the region code is default.
*
* @param data
* @return
*/
public String getCarrierNameForNumber(Object data) {
return PhoneNumberHandlerBase.getCarrierNameForNumber(data, defaultRegion, defaultLocale);
}
public Locale getDefaultLocale() {
return defaultLocale;
}
public void setDefaultLocale(Locale defaultLocale) {
this.defaultLocale = defaultLocale;
}
public String getDefaultRegion() {
return defaultRegion;
}
public void setDefaultRegion(String defaultRegion) {
this.defaultRegion = defaultRegion;
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.semantic;
import org.talend.dataquality.datamasking.functions.Function;
/**
* created by jgonzalez on 22 juin 2015. This function will replace every letter by the parameter.
*
*/
public class ReplaceCharactersWithGeneration extends Function<String> {
private static final long serialVersionUID = 368348491822287354L;
@Override
protected String doGenerateMaskedField(String input) {
return ReplaceCharacterHelper.replaceCharacters(input, rnd);
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.semantic.classifier.impl;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import org.talend.dataquality.semantic.classifier.ISubCategoryClassifier;
import org.talend.dataquality.semantic.index.Index;
/**
* Created by sizhaoliu on 27/03/15.
*/
public class DataDictFieldClassifier implements ISubCategoryClassifier {
private Index dictionary;
private Index keyword;
public DataDictFieldClassifier(Index dictionary, Index keyword) {
this.dictionary = dictionary;
this.keyword = keyword;
}
@Override
public Set<String> classify(String data) {
StringTokenizer t = new StringTokenizer(data, " ");
final int tokenCount = t.countTokens();
HashSet<String> result = new HashSet<String>();
// if it's a valid syntactic data --> search in DD
if (tokenCount < 3) {
result.addAll(dictionary.findCategories(data));
} else {
result.addAll(dictionary.findCategories(data));
result.addAll(keyword.findCategories(data));
}
return result;
}
public void closeIndex() {
dictionary.closeIndex();
keyword.closeIndex();
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.semantic;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.junit.Test;
import org.talend.dataquality.datamasking.functions.DateVariance;
import org.talend.dataquality.duplicating.AllDataqualitySamplingTests;
public class DateFunctionAdapterTest {
@Test
public void testGenerateMaskedRow() {
final DateVariance dv = new DateVariance();
dv.parse("61", true, new Random(AllDataqualitySamplingTests.RANDOM_SEED));
final List<String> patternList = Arrays
.asList(new String[] { "yyyy/MM/dd", "yyyy-MM-dd", "yyyy/MM/dd H:mm:ss", "AA9999" });
final DateFunctionAdapter function = new DateFunctionAdapter(dv, patternList);
assertEquals(null, function.generateMaskedRow(null)); // return null when input is null
assertEquals("", function.generateMaskedRow("")); // return empty when input is empty
assertEquals(" \t", function.generateMaskedRow(" \t")); // return original value when input contains only whitespaces
assertEquals("2015-12-09", function.generateMaskedRow("2015-11-15")); // should mask
assertEquals("2016/01/03", function.generateMaskedRow("2015/11/15")); // should mask
assertEquals("2015/05/23 22:25:11", function.generateMaskedRow("2015/6/15 10:00:00"));
assertEquals("14.2.1999", function.generateMaskedRow("22.3.1999"));
assertEquals("5000*24*70", function.generateMaskedRow("2015*11*15")); // replace chars when no date pattern is applicable
assertEquals("Vbrs-Kqc-260", function.generateMaskedRow("Vkfz-Zps-550"));
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Random;
import org.junit.Test;
/**
* created by jgonzalez on 25 juin 2015 Detailled comment
*
*/
public class BetweenIndexesKeepTest {
private BetweenIndexesKeep bik = new BetweenIndexesKeep();
private String input = "Steve"; //$NON-NLS-1$
private String output;
@Test
public void testGood() {
bik.parse("2, 4", false, new Random(42));
output = bik.generateMaskedRow(input);
assertEquals("tev", output); //$NON-NLS-1$
}
@Test
public void testGood2() {
bik.parse("1, 2", false, new Random(42));
output = bik.generateMaskedRow(input);
assertEquals("St", output); //$NON-NLS-1$
}
@Test
public void testEmpty() {
bik.parse("2, 4", false, new Random(42));
output = bik.generateMaskedRow("");
assertEquals("", output); //$NON-NLS-1$
}
@Test
public void testWrongParameter() {
try {
bik.parse("0, 8", false, new Random(42));
fail("should get exception with input " + bik.parameters); //$NON-NLS-1$
} catch (Exception e) {
assertTrue("expect illegal argument exception ", e instanceof IllegalArgumentException); //$NON-NLS-1$
}
output = bik.generateMaskedRow(input);
assertEquals("", output); //$NON-NLS-1$
}
@Test
public void testBad() {
try {
bik.parse("1", false, new Random(42));
fail("should get exception with input " + bik.parameters); //$NON-NLS-1$
} catch (Exception e) {
assertTrue("expect illegal argument exception ", e instanceof IllegalArgumentException); //$NON-NLS-1$
}
output = bik.generateMaskedRow(input);
assertEquals("", output); //$NON-NLS-1$
}
@Test
public void testBad2() {
try {
bik.parse("lk, df", false, new Random(42));
fail("should get exception with input " + bik.parameters); //$NON-NLS-1$
} catch (Exception e) {
assertTrue("expect illegal argument exception ", e instanceof IllegalArgumentException); //$NON-NLS-1$
}
output = bik.generateMaskedRow(input);
assertEquals("", output); //$NON-NLS-1$
}
@Test
public void testDummyParameters() {
bik.parse("423,452", false, new Random(42));
output = bik.generateMaskedRow(input);
assertEquals("", output);
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import org.talend.dataquality.datamasking.functions.BetweenIndexesKeepTest;
import org.talend.dataquality.datamasking.functions.BetweenIndexesRemoveTest;
import org.talend.dataquality.datamasking.functions.BetweenIndexesReplaceTest;
import org.talend.dataquality.datamasking.functions.DateVarianceTest;
import org.talend.dataquality.datamasking.functions.GenerateAccountNumberFormatTest;
import org.talend.dataquality.datamasking.functions.GenerateAccountNumberSimpleTest;
import org.talend.dataquality.datamasking.functions.GenerateBetweenDateTest;
import org.talend.dataquality.datamasking.functions.GenerateBetweenIntegerTest;
import org.talend.dataquality.datamasking.functions.GenerateBetweenLongTest;
import org.talend.dataquality.datamasking.functions.GenerateBetweenStringTest;
import org.talend.dataquality.datamasking.functions.GenerateCreditCardFormatLongTest;
import org.talend.dataquality.datamasking.functions.GenerateCreditCardFormatStringTest;
import org.talend.dataquality.datamasking.functions.GenerateCreditCardLongTest;
import org.talend.dataquality.datamasking.functions.GenerateCreditCardStringTest;
import org.talend.dataquality.datamasking.functions.GenerateFromFileHashIntegerTest;
import org.talend.dataquality.datamasking.functions.GenerateFromFileHashLongTest;
import org.talend.dataquality.datamasking.functions.GenerateFromFileHashStringTest;
import org.talend.dataquality.datamasking.functions.GenerateFromFileIntegerTest;
import org.talend.dataquality.datamasking.functions.GenerateFromFileLongTest;
import org.talend.dataquality.datamasking.functions.GenerateFromFileStringTest;
import org.talend.dataquality.datamasking.functions.GenerateFromPatternTest;
import org.talend.dataquality.datamasking.functions.GeneratePhoneNumberFrenchTest;
import org.talend.dataquality.datamasking.functions.GeneratePhoneNumberGermanyTest;
import org.talend.dataquality.datamasking.functions.GeneratePhoneNumberJapanTest;
import org.talend.dataquality.datamasking.functions.GeneratePhoneNumberUkTest;
import org.talend.dataquality.datamasking.functions.GeneratePhoneNumberUsTest;
import org.talend.dataquality.datamasking.functions.GenerateSsnFrenchTest;
import org.talend.dataquality.datamasking.functions.GenerateSsnGermanyTest;
import org.talend.dataquality.datamasking.functions.GenerateSsnJapanTest;
import org.talend.dataquality.datamasking.functions.GenerateSsnUkTest;
import org.talend.dataquality.datamasking.functions.GenerateSsnUsTest;
import org.talend.dataquality.datamasking.functions.KeepFirstCharsIntegerTest;
import org.talend.dataquality.datamasking.functions.KeepFirstCharsLongTest;
import org.talend.dataquality.datamasking.functions.KeepFirstCharsStringTest;
import org.talend.dataquality.datamasking.functions.KeepLastCharsIntegerTest;
import org.talend.dataquality.datamasking.functions.KeepLastCharsLongTest;
import org.talend.dataquality.datamasking.functions.KeepLastCharsStringTest;
import org.talend.dataquality.datamasking.functions.KeepYearTest;
import org.talend.dataquality.datamasking.functions.MaskAddressTest;
import org.talend.dataquality.datamasking.functions.MaskEmailLocalPartByXTest;
import org.talend.dataquality.datamasking.functions.MaskEmailLocalPartRandomlyTest;
import org.talend.dataquality.datamasking.functions.MaskFullEmailDomainByXTest;
import org.talend.dataquality.datamasking.functions.MaskFullEmailDomainRandomlyTest;
import org.talend.dataquality.datamasking.functions.MaskTopEmailDomainByXTest;
import org.talend.dataquality.datamasking.functions.MaskTopEmailDomainRandomlyTest;
import org.talend.dataquality.datamasking.functions.NumericVarianceIntegerTest;
import org.talend.dataquality.datamasking.functions.NumericVarianceLongTest;
import org.talend.dataquality.datamasking.functions.RemoveFirstCharsIntegerTest;
import org.talend.dataquality.datamasking.functions.RemoveFirstCharsLongTest;
import org.talend.dataquality.datamasking.functions.RemoveFirstCharsStringTest;
import org.talend.dataquality.datamasking.functions.RemoveLastCharsIntegerTest;
import org.talend.dataquality.datamasking.functions.RemoveLastCharsLongTest;
import org.talend.dataquality.datamasking.functions.RemoveLastCharsStringTest;
import org.talend.dataquality.datamasking.functions.ReplaceAllTest;
import org.talend.dataquality.datamasking.functions.ReplaceCharactersTest;
import org.talend.dataquality.datamasking.functions.ReplaceFirstCharsIntegerTest;
import org.talend.dataquality.datamasking.functions.ReplaceFirstCharsLongTest;
import org.talend.dataquality.datamasking.functions.ReplaceFirstCharsStringTest;
import org.talend.dataquality.datamasking.functions.ReplaceLastCharsIntegerTest;
import org.talend.dataquality.datamasking.functions.ReplaceLastCharsLongTest;
import org.talend.dataquality.datamasking.functions.ReplaceLastCharsStringTest;
import org.talend.dataquality.datamasking.functions.ReplaceNumericIntegerTest;
import org.talend.dataquality.datamasking.functions.ReplaceNumericLongTest;
import org.talend.dataquality.datamasking.functions.ReplaceNumericStringTest;
import org.talend.dataquality.datamasking.functions.SetToNullTest;
/**
* created by jgonzalez on 20 août 2015 Detailled comment
*
*/
@RunWith(Suite.class)
@SuiteClasses({ BetweenIndexesKeepTest.class, BetweenIndexesRemoveTest.class, BetweenIndexesReplaceTest.class,
DateVarianceTest.class, GenerateAccountNumberFormatTest.class, GenerateAccountNumberSimpleTest.class,
GenerateBetweenDateTest.class, GenerateBetweenIntegerTest.class, GenerateBetweenLongTest.class,
GenerateBetweenStringTest.class, GenerateCreditCardFormatLongTest.class, GenerateCreditCardFormatStringTest.class,
GenerateCreditCardLongTest.class, GenerateCreditCardStringTest.class, GenerateFromFileHashIntegerTest.class,
GenerateFromFileHashLongTest.class, GenerateFromFileHashStringTest.class, GenerateFromFileIntegerTest.class,
GenerateFromFileLongTest.class, GenerateFromFileStringTest.class, GenerateFromPatternTest.class,
GeneratePhoneNumberFrenchTest.class, GeneratePhoneNumberGermanyTest.class, GeneratePhoneNumberJapanTest.class,
GeneratePhoneNumberUkTest.class, GeneratePhoneNumberUsTest.class, GenerateSsnFrenchTest.class,
GenerateSsnGermanyTest.class, GenerateSsnJapanTest.class, GenerateSsnUkTest.class, GenerateSsnUsTest.class,
KeepFirstCharsIntegerTest.class, KeepFirstCharsLongTest.class, KeepFirstCharsStringTest.class,
KeepLastCharsIntegerTest.class, KeepLastCharsLongTest.class, KeepLastCharsStringTest.class, KeepYearTest.class,
MaskAddressTest.class, NumericVarianceIntegerTest.class, NumericVarianceLongTest.class, RemoveFirstCharsIntegerTest.class,
RemoveFirstCharsLongTest.class, RemoveFirstCharsStringTest.class, RemoveLastCharsIntegerTest.class,
RemoveLastCharsLongTest.class, RemoveLastCharsStringTest.class, ReplaceAllTest.class, ReplaceCharactersTest.class,
ReplaceFirstCharsIntegerTest.class, ReplaceFirstCharsLongTest.class, ReplaceFirstCharsStringTest.class,
ReplaceLastCharsIntegerTest.class, ReplaceLastCharsLongTest.class, ReplaceLastCharsStringTest.class,
ReplaceNumericIntegerTest.class, ReplaceNumericLongTest.class, ReplaceNumericStringTest.class, SetToNullTest.class,
MaskEmailLocalPartByXTest.class, MaskEmailLocalPartRandomlyTest.class, MaskFullEmailDomainByXTest.class,
MaskFullEmailDomainRandomlyTest.class, MaskTopEmailDomainByXTest.class, MaskTopEmailDomainRandomlyTest.class })
public class AllTests {
/*
* Bloc intentionnaly left empty
*/
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.log4j.Logger;
/**
* @author jteuladedenantes
*
* This class allows to generate unique random pattern from a list of fields. Each field define a set of possible
* values.
*/
public class GenerateUniqueRandomPatterns implements Serializable {
private static final long serialVersionUID = -5509905086789639724L;
private static final Logger LOGGER = Logger.getLogger(GenerateUniqueRandomPatterns.class);
/**
* The random key to make impossible the decoding
*/
private Integer key;
/**
* The list of all possible values for each field
*/
private List<AbstractField> fields;
/**
* The product of width fields, i.e. the combination of all possibles values
*/
private long longestWidth;
/**
* BasedWidthsList is used to go from a base to an other
*/
private List<Long> basedWidthsList;
public GenerateUniqueRandomPatterns(List<AbstractField> fields) {
super();
this.fields = fields;
// longestWidth init
longestWidth = 1L;
for (int i = 0; i < getFieldsNumber(); i++) {
long width = this.fields.get(i).getWidth();
longestWidth *= width;
}
LOGGER.debug("longestWidth = " + longestWidth);
// basedWidthsList init
basedWidthsList = new ArrayList<Long>();
basedWidthsList.add(1L);
for (int i = getFieldsNumber() - 2; i >= 0; i--)
basedWidthsList.add(0, this.fields.get(i + 1).getWidth() * this.basedWidthsList.get(0));
LOGGER.debug("basedWidthsList = " + basedWidthsList);
}
public List<AbstractField> getFields() {
return fields;
}
public void setFields(List<AbstractField> fields) {
this.fields = fields;
}
public int getFieldsNumber() {
return fields.size();
}
public void setKey(int key) {
this.key = key;
}
/**
* @param strs, the string input to encode
* @return the new string encoding
*/
public StringBuilder generateUniqueString(List<String> strs) {
// check inputs
if (strs.size() != getFieldsNumber())
return null;
// encode the fields
List<Long> listToMask = new ArrayList<Long>();
long encodeNumber;
for (int i = 0; i < getFieldsNumber(); i++) {
encodeNumber = fields.get(i).encode(strs.get(i));
if (encodeNumber == -1) {
return null;
}
listToMask.add(encodeNumber);
}
// generate the unique random number from the old one
List<Long> uniqueMaskedNumberList = getUniqueRandomNumber(listToMask);
// decode the fields
StringBuilder result = new StringBuilder("");
for (int i = 0; i < getFieldsNumber(); i++) {
result.append(fields.get(i).decode(uniqueMaskedNumberList.get(i)));
}
return result;
}
/**
* @param listToMask, the numbers list for each field
* @return uniqueMaskedNumberList, the masked list
*/
private List<Long> getUniqueRandomNumber(List<Long> listToMask) {
// numberToMask is the number to masked created from listToMask
long numberToMask = 0L;
for (int i = 0; i < getFieldsNumber(); i++)
numberToMask += listToMask.get(i) * basedWidthsList.get(i);
LOGGER.debug("numberToMask = " + numberToMask);
if (key == null)
setKey((new Random()).nextInt() % 10000 + 1000);
long coprimeNumber = findLargestCoprime(Math.abs(key));
// uniqueMaskedNumber is the number we masked
long uniqueMaskedNumber = (numberToMask * coprimeNumber) % longestWidth;
LOGGER.debug("uniqueMaskedNumber = " + uniqueMaskedNumber);
// uniqueMaskedNumberList is the unique list created from uniqueMaskedNumber
List<Long> uniqueMaskedNumberList = new ArrayList<Long>();
for (int i = 0; i < getFieldsNumber(); i++) {
// baseRandomNumber is the quotient of the Euclidean division between uniqueMaskedNumber and
// basedWidthsList.get(i)
long baseRandomNumber = uniqueMaskedNumber / basedWidthsList.get(i);
uniqueMaskedNumberList.add(baseRandomNumber);
// we reiterate with the remainder of the Euclidean division
uniqueMaskedNumber %= basedWidthsList.get(i);
}
return uniqueMaskedNumberList;
}
/**
*
* @param the key from we want to find a coprime number with longestWidth
* @return the largest coprime number with longestWidth less than key
*/
private long findLargestCoprime(long key) {
if (pgcdModulo(key, longestWidth) == 1) {
return key;
} else {
return findLargestCoprime(key - 1);
}
}
private long pgcdModulo(long a, long b) {
if (b == 0)
return a;
return pgcdModulo(b, a % b);
}
/**
* @return the sum of fields length (i.e. the number of characters in a field)
*/
public int getFieldsCharsLength() {
int length = 0;
for (AbstractField field : fields) {
length += field.getLength();
}
return length;
}
}
<file_sep>output.. = target/classes
bin.includes = META-INF/,\
target/classes/,\
changelog.txt,\
.,\
README.md
source.. = src/main/java/
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.semantic.broadcast;
import java.io.Serializable;
import java.util.Set;
/**
* A POJO representing index document to be diffused across cluster computing executers such as Apache Spark.
*/
public class BroadcastDocumentObject implements Serializable {
private static final long serialVersionUID = -1650549578529804062L;
private String category;
private Set<String> valueSet;
/**
* @param category the category reference
* @param valueSet the values of the document
*/
public BroadcastDocumentObject(String category, Set<String> valueSet) {
this.category = category;
this.valueSet = valueSet;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Set<String> getValueSet() {
return valueSet;
}
public void setValueSet(Set<String> valueSet) {
this.valueSet = valueSet;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(category).append(" -> ");
for (String str : valueSet) {
builder.append(str).append(", ");
}
return builder.toString();
}
}
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.talend.dataquality</groupId>
<artifactId>dataquality-libraries</artifactId>
<version>1.6.0-SNAPSHOT</version>
<relativePath>../dataquality-libraries</relativePath>
</parent>
<artifactId>dataquality-sampling</artifactId>
<version>${dataquality.sampling.snapshot.version}</version>
<packaging>bundle</packaging>
<name>dataquality-sampling</name>
<description>Reservoir sampling, data masking, data duplication</description>
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<scala.version>2.10.5</scala.version>
<scala.binary.version>2.10</scala.binary.version>
<spark.version>1.6.0</spark.version>
</properties>
<dependencies>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.talend.daikon</groupId>
<artifactId>daikon</artifactId>
</dependency>
<!-- spark dependencies -->
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala.version}</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_${scala.binary.version}</artifactId>
<version>${spark.version}</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_${scala.binary.version}</artifactId>
<version>${spark.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- logging stuff -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber</artifactId>
<version>7.3.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<excludes>
<exclude>org/talend/dataquality/sampling/collectors/*.java</exclude>
</excludes>
<testExcludes>
<testExclude>org/talend/dataquality/sampling/collectors/*.java</testExclude>
</testExcludes>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
/**
* created by jgonzalez on 22 juin 2015. This class is used when the requested function is either BetweenIndexesKeep,
* BetweenIndexesRemove or BetweenIndexesReplace. It will set the bounds of the indexes according to the input length.
*
*/
public abstract class BetweenIndexes extends CharactersOperation<String> {
private static final long serialVersionUID = 1114307514352123034L;
@Override
protected String getDefaultOutput() {
return EMPTY_STRING;
}
@Override
protected String getOutput(String str) {
return str;
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
/**
* created by jgonzalez on 18 juin 2015. See NumericVariance.
*
*/
public class NumericVarianceInteger extends NumericVariance<Integer> {
private static final long serialVersionUID = -5691096627763244343L;
@Override
protected Integer doGenerateMaskedField(Integer i) {
if (i == null) {
return 0;
} else {
super.init();
int value = getNonOverAddResult(i, getNonOverMultiResult(i, rate).intValue() / 100);
return value;
}
}
/**
*
* Get result which value1 * value2 and handle over flow case
*
* @param value1
* @param value2
* @return When result is over flow then get one value which nearby MAX_VALUE or MIN_VALUE
*/
private Integer getNonOverMultiResult(int value1, int value2) {
if (value1 == 0 || value2 == 0) {
return 0;
}
if (value1 > 0 && value2 > 0) {
if (value1 < Integer.MAX_VALUE / value2) {
return value1 * value2;
} else {
return Integer.MAX_VALUE - Integer.MAX_VALUE % (value1 > value2 ? value1 : value2);
}
} else if (value1 < 0 && value2 < 0) {
if (value1 != Integer.MIN_VALUE && Math.abs(value1) < Integer.MAX_VALUE / Math.abs(value2)) {
return value1 * value2;
} else {
if (Integer.MIN_VALUE == value1 || Integer.MIN_VALUE == value2) {
return Integer.MAX_VALUE;
}
return Integer.MAX_VALUE - Integer.MAX_VALUE % (value1 < value2 ? value1 : value2);
}
} else {
if (value1 != Integer.MIN_VALUE && Math.abs(value1) < Integer.MAX_VALUE / Math.abs(value2)) {
return value1 * value2;
} else {
if (Integer.MIN_VALUE == value1 || Integer.MIN_VALUE == value2) {
return Integer.MIN_VALUE;
}
return Integer.MIN_VALUE - Integer.MIN_VALUE % (Math.abs(value1) > Math.abs(value2) ? value1 : value2);
}
}
}
/**
*
* Get result which value1 + value2 and handle over flow case
*
* @param value1
* @param value2
* @return When resule is over flow then change + or - to avoid over flow generate
*/
private Integer getNonOverAddResult(int value1, int value2) {
if (value1 > 0 && value2 > 0) {
if (value1 < Integer.MAX_VALUE - value2) {
return value1 + value2;
} else {
return Math.abs(value1 - value2);
}
} else if (value1 < 0 && value2 < 0) {
if (value1 > Integer.MIN_VALUE - value2) {
return value1 + value2;
} else {
return -Math.abs(value1 - value2);
}
} else {
return value1 + value2;
}
}
}
<file_sep>// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.datamasking.functions;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
/**
*
* @author dprot
*
* The Chinese SSN has 4 fields : the first one, on 6 digits, stands for the birth place; the second one, with format
* YYYYMMDD for the date of birth; the third one, with 3 digits; the last one, on one digit, is a checksum key
*/
public class GenerateUniqueSsnChn extends AbstractGenerateUniqueSsn {
private static final long serialVersionUID = 4514471121590047091L;
private static final Logger LOGGER = Logger.getLogger(GenerateUniqueSsnChn.class);
private static final List<Integer> keyWeight = Collections
.unmodifiableList(Arrays.asList(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2));
private static final int KEYMOD = 11; // $NON-NLS-1$
private static final List<String> keyString = Collections
.unmodifiableList(Arrays.asList("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"));
private String computeChineseKey(String ssnNumber) {
int key = 0;
for (int i = 0; i < 17; i++) {
key += Character.getNumericValue(ssnNumber.charAt(i)) * keyWeight.get(i);
}
key = key % KEYMOD;
return keyString.get(key);
}
@Override
protected StringBuilder doValidGenerateMaskedField(String str) {
// read the input strWithoutSpaces
List<String> strs = new ArrayList<String>();
strs.add(str.substring(0, 6));
strs.add(str.substring(6, 14));
strs.add(str.substring(14, 17));
StringBuilder result = ssnPattern.generateUniqueString(strs);
if (result == null) {
return null;
}
// Add the security key specified for Chinese SSN
String controlKey = computeChineseKey(result.toString());
result.append(controlKey);
return result;
}
@Override
protected List<AbstractField> createFieldsListFromPattern() {
List<AbstractField> fields = new ArrayList<AbstractField>();
InputStream is = GenerateUniqueSsnChn.class.getResourceAsStream("RegionListChina.txt");
try {
List<String> places = IOUtils.readLines(is, "UTF-8");
fields.add(new FieldEnum(places, 6));
} catch (IOException e) {
LOGGER.error("The file of chinese regions is not correctly loaded " + e.getMessage(), e);
}
fields.add(new FieldDate());
fields.add(new FieldInterval(0, 999));
checkSumSize = 1;
return fields;
}
}
| 712053187a1a3bcd39dc64f30bffbf77d8d8006d | [
"Markdown",
"Maven POM",
"INI",
"Java",
"Shell"
] | 73 | Java | bdiouf/data-quality | 1ce3e3c44ebd1f346b028ecce19c9cbefd0b9071 | 1ca2f74d2eb00a171cd1674e83a777f3631cc84f |
refs/heads/master | <repo_name>Kvnsm/push_swap<file_sep>/srcs/checker/transform_arg_to_array.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* transform_arg_to_array.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/30 01:36:16 by ksam #+# #+# */
/* Updated: 2021/05/24 16:31:38 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../../includes/push_swap.h"
int arg_verification(int res, int *array, int current)
{
int i;
i = 0;
while (i <= current - 2)
{
if (array[i] == res)
return (0);
i++;
}
return (1);
}
int *transform_argument_to_array(int argc, char**argv)
{
int index;
int *res;
int *array;
index = 1;
array = malloc(sizeof(int) * (argc - 1));
while (index < argc)
{
res = ft_atoi_utimate(argv[index]);
if (res == NULL)
{
free(array);
ft_error("Int not in range detected");
}
if (arg_verification(*res, array, index) == 1)
array[index - 1] = *res;
else
{
free(array);
ft_error("Duplicate int in stack");
}
index++;
}
return (reverse_array(array, argc));
}
int *reverse_array(int *array, int argc)
{
int i;
int size;
int *ret;
i = 0;
size = argc - 2;
ret = malloc(sizeof(int) * (size + 1));
while (size >= 0)
{
ret[i] = array[size];
size--;
i++;
}
free(array);
return (ret);
}
<file_sep>/srcs/stack.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* stack.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/30 04:46:08 by ksam #+# #+# */
/* Updated: 2021/05/24 16:38:26 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
int ft_stack_has(t_stack *stack, int item)
{
int index;
index = 0;
while (index <= stack->top)
{
if (stack->array[index++] == item)
return (1);
}
return (0);
}
t_stack *ft_add(t_stack_master *stack_master, t_stack *stack, char *s)
{
int *i;
i = ft_atoi_utimate(s);
if (!i)
{
ft_stack_master_free(stack_master);
dprintf(2, "\033[0;31mError\n'%s' is not a correct INT.\033[0m\n", s);
exit (EXIT_FAILURE);
}
else if (ft_stack_has(stack, *i))
{
ft_stack_master_free(stack_master);
dprintf(2, "\033[0;31mError\n%d is already on stack A.\033[0m\n", *i);
exit (EXIT_FAILURE);
}
return (ft_stack_add(stack, *i));
}
t_stack *ft_stack_add(t_stack *old_stack, int new_item)
{
t_stack *new_stack;
char out[60];
new_stack = NULL;
if (old_stack == NULL)
new_stack = ft_stack_create(1);
else if (!(ft_stack_has_place(old_stack, 1)))
{
ft_print_stack(old_stack);
sprintf(out, "The stack is full, can't push on it (size = %d)",
old_stack->capacity);
ft_error(out);
}
else
new_stack = old_stack;
ft_stack_push(new_stack, new_item);
return (new_stack);
}
t_stack *ft_stack_create(unsigned int capacity)
{
t_stack *stack;
stack = (t_stack *)malloc(sizeof(t_stack));
if (stack == NULL)
ft_error_memomy();
stack->capacity = capacity;
stack->top = -1;
stack->array = (int *)malloc(stack->capacity * sizeof(int));
if (stack->array == NULL)
ft_error_memomy();
return (stack);
}
<file_sep>/srcs/ft_initialize.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_initialize.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/27 18:46:49 by ksam #+# #+# */
/* Updated: 2021/05/24 16:36:48 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
t_stack_master *ft_initialize_stack_master(void)
{
t_stack_master *stack_master;
stack_master = ft_calloc(1, sizeof(t_stack_master));
if (stack_master == NULL)
ft_error_memomy();
stack_master->is_colored = 0;
stack_master->is_instruction = 0;
stack_master->instructions = 0;
stack_master->is_verbose = 0;
stack_master->is_hiding_default_output = 0;
return (stack_master);
}
void ft_stack_master_free(t_stack_master *stack_master)
{
ft_stack_free_stack(stack_master->a);
ft_stack_free_stack(stack_master->b);
free(stack_master);
}
t_stack_master *ft_duplicate_stack_master(t_stack_master *stack_master)
{
t_stack_master *new_stack_master;
int i;
new_stack_master = ft_initialize_stack_master();
new_stack_master->a = ft_stack_create(stack_master->a->capacity);
i = 0;
while (i <= stack_master->a->top)
ft_stack_add(new_stack_master->a, stack_master->a->array[i++]);
new_stack_master->b = ft_stack_create(stack_master->b->capacity);
i = 0;
while (i <= stack_master->b->top)
ft_stack_add(new_stack_master->b, stack_master->b->array[i++]);
return (new_stack_master);
}
void ft_create_stack_master(t_stack_master *stack_master, int max_stack_size)
{
stack_master->a = ft_stack_create(max_stack_size);
stack_master->b = ft_stack_create(max_stack_size);
}
<file_sep>/srcs/checker/free_functions.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* free_functions.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/13 16:02:41 by ksam #+# #+# */
/* Updated: 2021/05/25 11:31:10 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../../includes/push_swap.h"
void free_all(int *number_to_order, t_stack_master *stack_master)
{
free(number_to_order);
ft_stack_free_stack(stack_master->a);
ft_stack_free_stack(stack_master->b);
if (stack_master)
free(stack_master);
}
void free_manager(t_master *manager, char **instructions)
{
while (manager->count)
data_eraser(manager, manager->first, 1);
if (manager)
free(manager);
if (instructions)
free(instructions);
}
<file_sep>/srcs/algo.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* algo.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/14 02:18:08 by ksam #+# #+# */
/* Updated: 2021/05/24 16:33:52 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
int ft_get_cercle(int index, t_stack *stack)
{
if (index > stack->top)
index = index - stack->top - 1;
return (stack->array[index]);
}
/**
* Sort automatically stacks with specific algo
*/
void ft_auto_sort(t_stack_master *stack_master)
{
if (stack_master->is_verbose == 1)
ft_print_master_stack(stack_master);
ft_auto_sortV5(stack_master);
if (!ft_is_correct(stack_master))
{
ft_warn("Stack_master is not sorted");
printf("\e[93m");
ft_print_master_stack(stack_master);
printf("\e[0m");
}
if (stack_master->is_verbose == 1 || stack_master->is_instruction == 1)
{
ft_print_instructions(stack_master);
}
}
void ft_auto_sortV5_2(t_stack_master *stack_master, int bad_index_a)
{
int bad_index_b;
bad_index_b = is_bad_index_only_b(stack_master);
if (ft_stack_is_empty(stack_master->a) && bad_index_b > -1)
jump_to_index(stack_master, bad_index_b, 1);
else if (bad_index_a > -1)
{
ft_perfect_shot_a(stack_master,
stack_master->a->array[*get_index_of_smallest(
stack_master->a, NULL)],
stack_master->a->array[*get_index_of_biggest(
stack_master->a, NULL)]);
}
else if (stack_master->b->top > 0)
{
ft_perfect_shot_b(stack_master,
stack_master->b->array[*get_index_of_smallest(
stack_master->b, NULL)],
stack_master->b->array[*get_index_of_biggest(
stack_master->b, NULL)]);
}
else if (stack_master->b->top < 2)
ft_sort_and_print(stack_master, "pb");
else
ft_error("Can't sort with algoV5");
}
void ft_auto_sortV5(t_stack_master *stack_master)
{
int top;
int bad_index_a;
while (!(ft_is_correct(stack_master)))
{
bad_index_a = is_bad_index_only_a(stack_master);
if (ft_stack_is_empty(stack_master->b) && bad_index_a > -1)
jump_to_index(stack_master, bad_index_a, 0);
else if (ft_stack_is_empty(stack_master->b)
&& ft_can_be_revert(stack_master->a))
ft_sort_and_print(stack_master, "sa");
else if (ft_stack_is_empty(stack_master->a)
&& ft_is_upside_down(stack_master->b))
{
top = stack_master->b->top;
while (top-- >= 0)
ft_sort_and_print(stack_master, "pa");
break ;
}
else
ft_auto_sortV5_2(stack_master, bad_index_a);
if (stack_master->b->top > 1 && is_bad_index_only_b(stack_master) == -1)
ft_error("Stack B is not sorted");
}
}
<file_sep>/srcs/checker_particularity_II.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* checker_particularity_II.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/13 16:54:12 by ksam #+# #+# */
/* Updated: 2021/05/24 16:35:07 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
int is_bad_index_only_a(t_stack_master *stack_master)
{
int *start_index;
int i;
int i1;
int i2;
if (ft_stack_is_empty(stack_master->a))
return (-1);
i = -1;
start_index = get_index_of_biggest(stack_master->a, NULL);
while (++i < stack_master->a->top)
{
if (i + *start_index > stack_master->a->top)
i1 = i + *start_index - stack_master->a->top - 1;
else
i1 = i + *start_index;
if (i + *start_index + 1 > stack_master->a->top)
i2 = i + *start_index - stack_master->a->top;
else
i2 = i + *start_index + 1;
if (stack_master->a->array[i1] < stack_master->a->array[i2])
return (-1);
}
return (i2);
}
int is_bad_index_only_b(t_stack_master *stack_master)
{
int *start_index;
int i;
int i1;
int i2;
if (ft_stack_is_empty(stack_master->b))
return (-1);
i = -1;
i1 = 0;
start_index = get_index_of_smallest(stack_master->b, NULL);
while (++i < stack_master->b->top)
{
if (i + *start_index > stack_master->b->top)
i1 = i + *start_index - stack_master->b->top - 1;
else
i1 = i + *start_index;
if (i + *start_index + 1 > stack_master->b->top)
i2 = i + *start_index - stack_master->b->top;
else
i2 = i + *start_index + 1;
if (stack_master->b->array[i1] > stack_master->b->array[i2])
return (-1);
}
return (i2);
}
<file_sep>/Makefile
# **************************************************************************** #
# #
# ::: :::::::: #
# Makefile :+: :+: :+: #
# +:+ +:+ +:+ #
# By: ksam <<EMAIL>> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2020/03/04 12:37:16 by ksam #+# #+# #
# Updated: 2021/05/22 20:10:55 by ksam ### ########lyon.fr #
# #
# **************************************************************************** #
CC = gcc
NAME = push_swap
NAME_CHECKER = checker
NAME_RANDOMIZE = randomize
LIB_PATH = libft/libft.a
NORM_DIRS = srcs/ includes/ libft/
INCLUDES = includes/push_swap.h
SRCS = srcs/algo.c \
srcs/basic_sort.c \
srcs/checker_particularity_II.c \
srcs/checker_particularity.c \
srcs/doubly_linked_list.c \
srcs/ft_args.c \
srcs/ft_atoi_utimate.c \
srcs/ft_error.c \
srcs/ft_initialize.c \
srcs/get_big_index.c \
srcs/instructions_utils.c \
srcs/jump_to_index.c \
srcs/jump_to_index2.c \
srcs/perfect_shot.c \
srcs/push_swap_utils.c \
srcs/random.c \
srcs/sort.c \
srcs/stack.c \
srcs/stack2.c \
srcs/stack3.c
SRCS_PUSH_SWAP = srcs/push_swap/main.c \
srcs/push_swap/unit_tests.c
SRCS_CHECKER = srcs/checker/checker.c \
srcs/checker/free_functions.c \
srcs/checker/instructions_initializor.c \
srcs/checker/main.c \
srcs/checker/transform_arg_to_array.c
SRCS_RANDOMIZE = srcs/randomize/main.c
OBJS = $(SRCS:.c=.o)
OBJS_PUSH_SWAP = $(SRCS_PUSH_SWAP:.c=.o)
OBJS_CHECKER = $(SRCS_CHECKER:.c=.o)
OBJS_RANDOMIZE = $(SRCS_RANDOMIZE:.c=.o)
# CFLAGS = -Wextra -Wall -Werror
CFLAGS = -Wextra -Wall -g3 -fsanitize=address
all: $(NAME) $(NAME_CHECKER)
$(NAME): $(OBJS) $(OBJS_PUSH_SWAP) $(INCLUDES)
make -C libft
$(CC) ${CFLAGS} $(OBJS) $(OBJS_PUSH_SWAP) $(LIB_PATH) -o $(NAME)
$(NAME_CHECKER): $(OBJS) $(OBJS_CHECKER) $(INCLUDES)
make -C libft
$(CC) ${CFLAGS} $(OBJS) $(OBJS_CHECKER) $(LIB_PATH) -o $(NAME_CHECKER)
$(NAME_RANDOMIZE): $(OBJS) $(OBJS_RANDOMIZE) $(INCLUDES)
make -C libft
$(CC) ${CFLAGS} $(OBJS) $(OBJS_RANDOMIZE) $(LIB_PATH) -o $(NAME_RANDOMIZE)
.c.o:
${CC} ${CFLAGS} -c $< -o $@
clean:
make $@ -C libft
rm -f $(OBJS)
rm -f $(OBJS_PUSH_SWAP)
rm -f $(OBJS_CHECKER)
rm -f $(OBJS_RANDOMIZE)
fclean: clean
rm -f $(NAME)
rm -f $(NAME_CHECKER)
rm -f $(NAME_RANDOMIZE)
re:
make fclean
make all
random: $(NAME_RANDOMIZE)
.PHONY: all clean fclean re random
<file_sep>/srcs/jump_to_index2.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* jump_to_index2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/13 17:37:07 by ksam #+# #+# */
/* Updated: 2021/05/24 16:37:50 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
void jump_to_index(t_stack_master *stack_master, int index, int a_or_b)
{
int top;
int times;
t_stack *stack;
if (a_or_b == 0)
stack = stack_master->a;
else if (a_or_b == 1)
stack = stack_master->b;
else
{
printf("WARN > a_or_b bad parameter `bool`. jump_to_index cancelled\n");
return ;
}
top = stack->top;
times = top - index;
if (times <= (top + 1) / 2)
ra_or_rb(stack_master, times, a_or_b);
else
rra_or_rrb(stack_master, index + 1, a_or_b);
}
void ra_or_rb(t_stack_master *stack_master, int times, int a_or_b)
{
while (times > 0)
{
if (a_or_b == 0)
ft_sort_and_print(stack_master, "ra");
else
ft_sort_and_print(stack_master, "rb");
times--;
}
}
void rra_or_rrb(t_stack_master *stack_master, int times, int a_or_b)
{
while (times > 0)
{
if (a_or_b == 0)
ft_sort_and_print(stack_master, "rra");
else
ft_sort_and_print(stack_master, "rrb");
times--;
}
}
void rr_or_rrr(t_stack_master *stack_master, int times, int rr_or_rrr)
{
while (times > 0)
{
if (rr_or_rrr == 0)
ft_sort_and_print(stack_master, "rr");
else
ft_sort_and_print(stack_master, "rrr");
times--;
}
}
<file_sep>/srcs/perfect_shot.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* perfect_shot.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/19 09:32:36 by tglory #+# #+# */
/* Updated: 2021/05/24 16:37:52 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
t_perfect_shot *init_perfect_shot(void)
{
t_perfect_shot *p_shot;
p_shot = ft_calloc(1, sizeof(t_perfect_shot));
if (p_shot == NULL)
ft_error_memomy();
p_shot->i_a = 0;
p_shot->i_b = 0;
p_shot->t_a = -1;
p_shot->t_b = -1;
p_shot->t_total = -1;
return (p_shot);
}
void ft_perfect_shot_b2(t_stack_master *stack_master, int min_b, int max_b,
t_perfect_shot *ps)
{
ps->v1 = ft_get_cercle(ps->i_b, stack_master->b);
ps->v2 = ft_get_cercle(ps->i_b + 1, stack_master->b);
ps->i_a = 0;
while (ps->i_a <= stack_master->a->top)
{
ps->value = stack_master->a->array[ps->i_a];
if ((ps->v1 < ps->value && ps->value < ps->v2)
|| ((ps->v1 < ps->value || ps->v2 > ps->value)
&& ps->v2 == min_b && ps->v1 == max_b))
{
ps->t_a = index_to_times(ps->i_a, stack_master->a->top);
ps->t_b = index_to_times(ps->i_b, stack_master->b->top);
if (ps->t_a + ps->t_b == 0 || ps->t_total == -1
|| ps->t_a + ps->t_b < ps->t_total)
{
ps->t_total = ps->t_a + ps->t_b;
ps->saved_a = ps->i_a;
ps->saved_b = ps->i_b;
}
}
ps->i_a++;
}
ps->i_b++;
}
int ft_perfect_shot_b(t_stack_master *stack_master, int min_b, int max_b)
{
t_perfect_shot *ps;
ps = init_perfect_shot();
while (ps->i_b <= stack_master->b->top)
ft_perfect_shot_b2(stack_master, min_b, max_b, ps);
if (ps->t_total < 0)
ft_error("Cannot find perfect shot B");
jump_to_index_both(stack_master, ps->saved_a, ps->saved_b);
free(ps);
ft_sort_and_print(stack_master, "pb");
return (1);
}
void ft_perfect_shot_a2(t_stack_master *stack_master, int min_a, int max_a,
t_perfect_shot *ps)
{
ps->v1 = ft_get_cercle(ps->i_a, stack_master->a);
ps->v2 = ft_get_cercle(ps->i_a + 1, stack_master->a);
ps->i_b = 0;
while (ps->i_b <= stack_master->b->top)
{
ps->value = stack_master->b->array[ps->i_b];
if ((ps->v1 > ps->value && ps->value > ps->v2)
|| ((ps->v1 > ps->value || ps->v2 < ps->value)
&& ps->v2 == max_a && ps->v1 == min_a))
{
ps->t_a = index_to_times(ps->i_a, stack_master->a->top);
ps->t_b = index_to_times(ps->i_b, stack_master->b->top);
if (ps->t_a + ps->t_b == 0 || ps->t_total == -1
|| ps->t_a + ps->t_b < ps->t_total)
{
ps->t_total = ps->t_a + ps->t_b;
ps->saved_a = ps->i_a;
ps->saved_b = ps->i_b;
}
}
ps->i_b++;
}
ps->i_a++;
}
int ft_perfect_shot_a(t_stack_master *stack_master, int min_a, int max_a)
{
t_perfect_shot *ps;
ps = init_perfect_shot();
while (ps->i_a <= stack_master->a->top)
ft_perfect_shot_a2(stack_master, min_a, max_a, ps);
if (ps->t_total < 0)
ft_error("Cannot find perfect shot A");
jump_to_index_both(stack_master, ps->saved_a, ps->saved_b);
free(ps);
ft_sort_and_print(stack_master, "pa");
return (1);
}
<file_sep>/srcs/random.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* random.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/17 00:24:59 by tglory #+# #+# */
/* Updated: 2021/05/24 16:37:57 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
#include <time.h>
int ft_contain_int(int *nbs, int i, int size)
{
int i2;
i2 = 0;
while (i2 < size)
{
if (nbs[i2++] == i)
return (1);
}
return (0);
}
int *ft_random_integers(int nb, int max_nb)
{
int i;
int random;
int *nbs;
if (max_nb > 0 && max_nb < nb)
ft_error("Unable to generate random numbers, "
"max_nb < nb");
i = 0;
nbs = malloc(nb * sizeof(int));
if (nbs == NULL)
ft_error_memomy();
srand(time(NULL));
while (i < nb)
{
random = -1;
while (random == -1 || ft_contain_int(nbs, random, nb) == 1)
{
if (max_nb <= 0)
random = rand();
else
random = rand() % (max_nb + 1);
}
nbs[i++] = random;
}
return (nbs);
}
<file_sep>/srcs/push_swap/main.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/25 12:58:02 by ksam #+# #+# */
/* Updated: 2021/05/24 16:32:03 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../../includes/push_swap.h"
int main(int argc, char **argv)
{
t_stack_master *stack_master;
if (argc <= 1)
ft_error("You need to add int in argument to sort it.\n-v = verbose, "
"-c last action colored, -h hide default output,\n"
"-a <1 or 2 or 3 or 4 or 5> algo version, -i show count of "
"instructions.\nOR -r <stack_size> without ints.");
else if (!ft_strncmp(argv[1], "-r", 3))
{
ft_test_args(argc, argv);
return (EXIT_SUCCESS);
}
stack_master = ft_args_to_stack_master(argv, argc - 1);
ft_auto_sort(stack_master);
ft_stack_master_free(stack_master);
return (EXIT_SUCCESS);
}
<file_sep>/srcs/push_swap_utils.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* push_swap_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/25 16:34:47 by tglory #+# #+# */
/* Updated: 2021/05/24 16:37:55 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
void ft_print_stack(t_stack *stack)
{
int i;
i = 0;
printf("pile : ");
if (stack != NULL)
{
if (ft_stack_is_empty(stack))
printf("EMPTY");
else
{
printf("size = %d > ", (stack->top + 1));
if (stack->top > 500 || stack->top < 0)
{
printf("\tError while print, size not conformed or > 500\n");
return ;
}
while (i <= stack->top)
printf("%d ", stack->array[i++]);
}
}
else
printf("NULL");
printf("\n");
}
void ft_print_int_double_array(int **array, int size)
{
int i;
i = 0;
printf("int 2 array : ");
if (array != NULL)
{
if (size == 0)
printf("EMPTY");
else
{
printf("size = %d > ", size);
while (i < size)
{
printf("%d-%d ", array[i][0], array[i][1]);
i++;
}
}
}
else
printf("NULL");
printf("\n");
}
void ft_print_int_array(int *array, int size)
{
int i;
i = 0;
printf("int array : ");
if (array != NULL)
{
if (size == 0)
printf("EMPTY");
else
{
printf("size = %d > ", size);
while (i < size)
printf("%d ", array[i++]);
}
}
else
printf("NULL");
printf("\n");
}
void ft_print_master_stack(t_stack_master *stack_master)
{
printf("A ");
ft_print_stack(stack_master->a);
printf("B ");
ft_print_stack(stack_master->b);
}
<file_sep>/srcs/checker/main.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/26 14:35:39 by ksam #+# #+# */
/* Updated: 2021/05/13 16:22:34 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../../includes/push_swap.h"
void exec_instructions(t_stack_master *t_stack_master, t_master *manager)
{
manager->current = manager->first;
while (manager->current)
{
ft_sort(t_stack_master, manager->current->val);
manager->current = manager->current->next;
}
if (ft_is_correct(t_stack_master) == 1)
printf("OK!\n");
else
printf("KO !\n");
}
int main(int argc, char **argv)
{
int *number_to_order;
char *buffer;
char **instructions;
t_master *manager;
t_stack_master *stack_master;
manager = manager_initializor();
instructions = instructions_initializor();
if (argc > 1)
{
number_to_order = transform_argument_to_array(argc, argv);
if (number_to_order)
{
while (get_next_line(0, &buffer) > 0)
data_backpusher(manager, buffer);
free(buffer);
check_instructions(manager, instructions);
stack_master = fill_astack_with_arg(number_to_order, argc - 1);
exec_instructions(stack_master, manager);
free_all(number_to_order, stack_master);
}
}
free_manager(manager, instructions);
return (0);
}
<file_sep>/srcs/doubly_linked_list.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* doubly_linked_list.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/25 18:01:09 by ksam #+# #+# */
/* Updated: 2021/05/13 17:25:21 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
t_master *manager_initializor(void)
{
t_master *manager;
manager = malloc(sizeof(t_master));
if (manager == NULL)
exit(1);
manager->first = NULL;
manager->last = NULL;
manager->current = NULL;
manager->count = 0;
return (manager);
}
void data_backpusher(t_master *manager, char *val)
{
t_data *new;
new = ft_calloc(1, sizeof(t_data));
if (new == NULL)
exit(1);
new->prev = manager->last;
new->val = val;
if (!manager->first)
manager->first = new;
if (manager->last)
manager->last->next = new;
manager->last = new;
manager->count++;
}
void data_frontpusher(t_master *manager, char *val)
{
t_data *new;
new = ft_calloc(1, sizeof(t_data));
if (new == NULL)
exit(1);
new->next = manager->first;
new->val = val;
manager->first = new;
manager->count++;
if (new->next)
new->next->prev = new;
if (!manager->last)
manager->last = new;
}
void data_eraser(t_master *manager, t_data *new, int i)
{
if (new == manager->first)
{
if (new->next)
new->next->prev = NULL;
manager->first = new->next;
}
else
new->prev->next = new->next;
if (new == manager->last)
{
if (new->prev)
new->prev->next = NULL;
manager->last = new->prev;
}
else
new->next->prev = new->prev;
if (i == 1)
free(new->val);
free(new);
manager->count--;
}
<file_sep>/srcs/jump_to_index.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* jump_to_index.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/13 17:37:07 by ksam #+# #+# */
/* Updated: 2021/05/24 16:37:46 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
int index_to_times(int index, int top)
{
int times;
times = top - index;
if (times <= (top + 1) / 2)
return (times);
else
return (index + 1);
}
void jump_to_index_both3(t_stack_master *stack_master, int times_a,
int times_b)
{
if (times_b < times_a)
{
rr_or_rrr(stack_master, -times_a, 1);
rra_or_rrb(stack_master, -times_b - -times_a, 1);
}
else if (times_a == times_b)
rr_or_rrr(stack_master, -times_a, 1);
else
{
rr_or_rrr(stack_master, -times_b, 1);
rra_or_rrb(stack_master, -times_a - -times_b, 0);
}
}
int jump_to_index_both2(t_stack_master *stack_master, int times_a,
int times_b)
{
if (times_b > 0 && times_a > 0)
{
if (times_b > times_a)
{
rr_or_rrr(stack_master, times_a, 0);
ra_or_rb(stack_master, times_b - times_a, 1);
}
else if (times_a == times_b)
rr_or_rrr(stack_master, times_a, 0);
else
{
rr_or_rrr(stack_master, times_b, 0);
ra_or_rb(stack_master, times_a - times_b, 0);
}
}
else if (times_b < 0 && times_a < 0)
jump_to_index_both3(stack_master, times_a, times_b);
else
return (1);
return (0);
}
void jump_to_index_both(t_stack_master *stack_master, int index_a,
int index_b)
{
int top;
int times_a;
int times_b;
top = stack_master->a->top;
times_a = top - index_a;
if (times_a > (top + 1) / 2)
times_a = -(index_a + 1);
top = stack_master->b->top;
times_b = top - index_b;
if (times_b > (top + 1) / 2)
times_b = -(index_b + 1);
if (jump_to_index_both2(stack_master, times_a, times_b) == 1)
{
if (index_a != stack_master->a->top)
jump_to_index(stack_master, index_a, 0);
if (index_b != stack_master->b->top)
jump_to_index(stack_master, index_b, 1);
}
}
<file_sep>/srcs/checker/checker.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* checker.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/25 15:10:35 by ksam #+# #+# */
/* Updated: 2021/05/24 16:57:38 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../../includes/push_swap.h"
int compare_instruction(char *buffer, char *instructions)
{
if (buffer)
{
if ((ft_strcmp(buffer, instructions) != 0) \
&& (ft_strlen(buffer) == ft_strlen(instructions)))
return (1);
}
return (0);
}
void check_instructions(t_master *manager, char **instructions)
{
int i;
manager->current = manager->first;
while (manager->current)
{
i = 0;
while (i <= 10)
{
if (compare_instruction(manager->current->val, \
instructions[i]) == 1)
break ;
if (i == 10)
{
ft_error("Instruction not found");
exit (1);
}
i++;
}
manager->current = manager->current->next;
}
}
t_stack_master *fill_astack_with_arg(int *nb, int argc)
{
t_stack_master *stack_master;
int k;
k = 0;
stack_master = malloc(sizeof(t_stack_master));
stack_master->a = ft_stack_create(argc);
stack_master->b = ft_stack_create(argc);
while (k < argc)
{
ft_stack_add(stack_master->a, nb[k]);
k++;
}
return (stack_master);
}
<file_sep>/includes/push_swap.h
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* push_swap.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/25 13:05:23 by tglory #+# #+# */
/* Updated: 2021/05/24 16:51:36 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#ifndef PUSH_SWAP_H
# define PUSH_SWAP_H
# include <unistd.h>
# include <stdio.h>
# include <stdlib.h>
# include "../libft/libft.h"
# include "../libft/gnl/get_next_line.h"
typedef struct s_data
{
char *val;
int free;
struct s_data *prev;
struct s_data *next;
} t_data;
typedef struct s_master
{
unsigned int count;
t_data *first;
t_data *last;
t_data *current;
} t_master;
typedef struct s_stack
{
int top;
int capacity;
int *array;
} t_stack;
typedef struct s_stack_master
{
t_stack *a;
t_stack *b;
int instructions;
int is_instruction;
int is_verbose;
int is_colored;
int is_hiding_default_output;
} t_stack_master;
typedef struct s_perfect_shot
{
int i_b;
int saved_a;
int i_a;
int saved_b;
int t_a;
int t_b;
int t_total;
int v1;
int v2;
int value;
} t_perfect_shot;
void ft_print_int_array(int *array, int size);
void ft_print_int_double_array(int **array, int size);
void ft_print_stack(t_stack *stack);
void ft_print_master_stack(t_stack_master *stack_master);
int ft_sort(t_stack_master *stack_master, char *operator);
void ft_stack_master_free(t_stack_master *stack_master);
int ft_stack_peek(t_stack *stack);
int ft_stack_pop(t_stack *stack);
void ft_stack_push(t_stack *stack, int item);
int ft_stack_is_empty(t_stack *stack);
int ft_stack_is_full(t_stack *stack);
t_stack *ft_stack_create(unsigned int capacity);
t_stack *ft_stack_add(t_stack *old_stack, int new_item);
int ft_stack_has_place(t_stack *stack, int i);
void ft_stack_free_stack(t_stack *stack);
t_stack *ft_add(t_stack_master *stack_master, t_stack *stack, char *s);
t_stack_master *ft_duplicate_stack_master(t_stack_master *stack_master);
t_stack_master *ft_args_to_stack_master(char **argv, int max_stack_size);
t_stack_master *ft_initialize_stack_master(void);
void ft_create_stack_master(t_stack_master *stack_master,
int max_stack_size);
int *ft_atoi_utimate(const char *str);
void ft_warn(char *msg);
void ft_error(char *msg);
void ft_error_master(t_stack_master *stack_master, char *msg);
void ft_error_memomy(void);
/**
*___________________________DOUBLY LINKED LIST___________________________
*/
/**
* DOUBLY LINKED LIST FUNCTIONS
*/
t_master *manager_initializor(void);
void data_backpusher(t_master *manager, char *val);
void data_frontpusher(t_master *manager, char *val);
void data_eraser(t_master *manager, t_data *new, int i);
/**
*_________________________________CHECKER_________________________________
*/
/**
* CHECKER FUNCTIONS
*/
void check_instructions(t_master *manager, char **instructions);
t_stack_master *fill_astack_with_arg(int *nb, int argc);
/**
* FREE FUNCTIONS
*/
void free_all(int *number_to_order, t_stack_master *stack_master);
void free_manager(t_master *manager, char **instructions);
/**
* INSTRUCTIONS INITIALIZOR
*/
char **instructions_initializor(void);
/**
* TRANSFORM ARGUMENT TO ARRAY
*/
int *transform_argument_to_array(int argc, char**argv);
int *reverse_array(int *array, int argc);
/**
*_________________________________PUSH SWAP_________________________________
*/
/**
* BASIC SORT
*/
int ft_swap(t_stack *stack);
int ft_push(t_stack_master *stack, int bool);
int ft_rotate(t_stack *stack);
int ft_reverse_rotate(t_stack *stack);
/**
* CHECKER PARTICULARITY
*/
int ft_is_correct_order(t_stack *stack);
int ft_is_upside_down(t_stack *stack);
int ft_is_correct(t_stack_master *stack_master);
int ft_can_be_revert(t_stack *stack);
int can_be_revert_process(t_stack *stack, int one, int two);
int is_bad_index_only_b(t_stack_master *stack_master);
int is_bad_index_only_a(t_stack_master *stack_master);
/**
* UTILS
*/
int *get_index_of_biggest(t_stack *stack, int *under);
int *get_index_of_smallest(t_stack *stack, int *upper);
void jump_to_index(t_stack_master *stack_master, int index,
int a_or_b);
void jump_to_index_both(t_stack_master *stack_master, int index_a,
int index_b);
int index_to_times(int index, int top);
int ft_get_cercle(int index, t_stack *stack);
int ft_get_perfect_index_b(int value, int **perfect_stack_array,
int perfect_stack_size, t_stack *stackDest);
int *ft_random_integers(int nb, int max_nb);
int ft_contain_int(int *nbs, int i, int size);
int ft_perfect_shot_a(t_stack_master *stack_master, int min_b,
int max_b);
int ft_perfect_shot_b(t_stack_master *stack_master, int min_b,
int max_b);
void ra_or_rb(t_stack_master *stack_master, int times, int a_or_b);
void rra_or_rrb(t_stack_master *stack_master, int times, int a_or_b);
void rr_or_rrr(t_stack_master *stack_master, int times,
int rr_or_rrr);
/**
* EXECUTE
*/
int ft_sort_and_print(t_stack_master *stack_master, char *operator);
void ft_auto_sort(t_stack_master *stack_master);
void ft_auto_sortV5(t_stack_master *stack_master);
/**
* TEST
*/
void ft_test_all(void);
void ft_test_numbers(int *nbs, int size);
void ft_test_args(int argc, char **argv);
void ft_print_instructions(t_stack_master *stack_master);
#endif<file_sep>/srcs/checker_particularity.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* checker_particularity.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/13 17:03:45 by ksam #+# #+# */
/* Updated: 2021/05/13 17:03:45 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
int ft_is_correct_order(t_stack *stack)
{
int i;
i = 0;
while (i < stack->top)
{
if (stack->array[i] < stack->array[i + 1])
return (0);
i++;
}
return (1);
}
int ft_is_upside_down(t_stack *stack)
{
int i;
i = 0;
while (i < stack->top)
{
if (stack->array[i] > stack->array[i + 1])
return (0);
i++;
}
return (1);
}
int ft_is_correct(t_stack_master *stack_master)
{
int i;
if (ft_stack_is_empty(stack_master->a)
|| !ft_stack_is_empty(stack_master->b))
return (0);
i = 0;
while (i < stack_master->a->top)
{
if (stack_master->a->array[i] < stack_master->a->array[i + 1])
return (0);
i++;
}
return (1);
}
/** Check if we can revert the 2 first value of stack
* @param perfect_array get this with ft_get_perfect_stack()
*/
int ft_can_be_revert(t_stack *stack)
{
int one;
int two;
if (stack->top <= 0)
return (0);
one = stack->array[stack->top];
two = stack->array[stack->top - 1];
if (one < two)
return (0);
if (stack->top == 1)
return (1);
return (can_be_revert_process(stack, one, two));
}
int can_be_revert_process(t_stack *stack, int top_int, int top_minus_1_int)
{
int *i;
int index_0_int;
int top_minus_2_int;
index_0_int = stack->array[0];
top_minus_2_int = stack->array[stack->top - 2];
if (index_0_int == top_minus_2_int)
return (1);
i = get_index_of_biggest(stack, &top_int);
if (i != NULL && *i == top_minus_1_int)
return (1);
return (0);
}
<file_sep>/srcs/sort.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sort.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/14 02:18:39 by ksam #+# #+# */
/* Updated: 2021/05/24 16:38:09 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
int ft_sort2(t_stack_master *stack_master, char *operator)
{
int i;
if (ft_strncmp(operator, "sb", 2) == 0)
return (ft_swap(stack_master->b));
else if (ft_strncmp(operator, "pa", 2) == 0)
return (ft_push(stack_master, 0));
else if (ft_strncmp(operator, "pb", 2) == 0)
return (ft_push(stack_master, 1));
else if (ft_strncmp(operator, "ra", 2) == 0)
return (ft_rotate(stack_master->a));
else if (ft_strncmp(operator, "rb", 2) == 0)
return (ft_rotate(stack_master->b));
else if (ft_strncmp(operator, "rr", 2) == 0)
{
i = ft_rotate(stack_master->a);
if (i <= 0)
return (i);
return (ft_rotate(stack_master->b));
}
else
{
dprintf(2, "ERROR > Unknown operator '%s'.\n", operator);
return (-2);
}
}
/** Execute operator one by one for stacks
* @param operator rra rrb rrr sa sb ss pa pb ra rb rr
* @return 0 for usless operator, 1 for succes, -1 for null t_stack,
* -2 for unknown @param operator
*/
int ft_sort(t_stack_master *stack_master, char *operator)
{
int i;
stack_master->instructions++;
if (ft_strncmp(operator, "rra", 3) == 0)
return (ft_reverse_rotate(stack_master->a));
else if (ft_strncmp(operator, "rrb", 3) == 0)
return (ft_reverse_rotate(stack_master->b));
else if (ft_strncmp(operator, "rrr", 3) == 0)
{
i = ft_reverse_rotate(stack_master->a);
if (i <= 0)
return (i);
return (ft_reverse_rotate(stack_master->b));
}
else if (ft_strncmp(operator, "sa", 2) == 0)
return (ft_swap(stack_master->a));
else if (ft_strncmp(operator, "ss", 2) == 0)
{
i = ft_swap(stack_master->a);
if (i <= 0)
return (i);
return (ft_swap(stack_master->b));
}
return (ft_sort2(stack_master, operator));
}
int ft_sort_and_print(t_stack_master *stack_master, char *operator)
{
int i;
i = ft_sort(stack_master, operator);
if (i == 0)
dprintf(2, "ERROR operator %s failed.\n", operator);
else if (i < 0)
{
if (i == -1)
dprintf(2, "ERROR > Stack Empty '%s'.\n", operator);
else if (i == -2)
dprintf(2, "ERROR > Unknown operator '%s'.\n", operator);
}
else
{
if (stack_master->is_colored && ft_is_correct(stack_master))
printf("\033[32m%s\033[0m\n", operator);
else if (!stack_master->is_hiding_default_output)
printf("%s\n", operator);
if (stack_master->is_verbose)
ft_print_master_stack(stack_master);
return (i);
}
ft_stack_master_free(stack_master);
exit(EXIT_FAILURE);
}
<file_sep>/srcs/basic_sort.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* basic_sort.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/25 13:08:51 by ksam #+# #+# */
/* Updated: 2021/05/24 16:34:23 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
/**
* TODO
* add protection like stack != NULL
*/
#include "../includes/push_swap.h"
int ft_swap(t_stack *stack)
{
int swap;
if (stack == NULL)
return (-1);
if (stack->top < 1)
return (0);
swap = stack->array[stack->top];
stack->array[stack->top] = stack->array[stack->top - 1];
stack->array[stack->top - 1] = swap;
return (1);
}
int ft_push(t_stack_master *stack_master, int bool)
{
if (bool == 1 && !ft_stack_is_empty(stack_master->a))
stack_master->b = ft_stack_add(stack_master->b,
ft_stack_pop(stack_master->a));
else if (bool == 0 && !ft_stack_is_empty(stack_master->b))
stack_master->a = ft_stack_add(stack_master->a,
ft_stack_pop(stack_master->b));
else if (bool == 0 || bool == 1)
return (0);
else
return (-3);
return (1);
}
int ft_rotate(t_stack *stack)
{
int swap;
int index;
if (stack == NULL)
return (-1);
if (stack->top <= 0)
return (0);
index = stack->top;
swap = (stack->array)[index];
while (--index >= 0)
(stack->array)[index + 1] = (stack->array)[index];
(stack->array)[index + 1] = swap;
return (1);
}
int ft_reverse_rotate(t_stack *stack)
{
int swap;
int index;
if (stack == NULL)
return (-1);
if (stack->top <= 0)
return (0);
index = 0;
swap = (stack->array)[index];
while (index < stack->top)
{
(stack->array)[index] = (stack->array)[index + 1];
index++;
}
(stack->array)[stack->top] = swap;
return (1);
}
<file_sep>/libft/ft_split.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tglory <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/10/26 17:54:11 by tglory #+# #+# */
/* Updated: 2021/03/31 05:06:55 by tglory ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdlib.h>
static char **ft_free(char **str)
{
int i;
i = 0;
while (*str[i] != '\0')
{
free(str[i]);
i++;
}
free(str);
return (NULL);
}
static char *ft_cpyword(char *dst, char const *s, char c, int *i)
{
int len;
len = 0;
while (s[(*i)] == c)
(*i)++;
while (s[(*i)] != c && s[(*i)] != '\0')
{
dst[len] = s[*i];
len++;
(*i)++;
}
dst[len] = '\0';
return (dst);
}
static int ft_lenword(char const *s, char c, int *i)
{
int len;
len = 0;
while (s[(*i)] == c)
(*i)++;
while (s[(*i)] != c && s[(*i)] != '\0')
{
len++;
(*i)++;
}
return (len);
}
static int ft_countword(char const *s, char c)
{
int i;
int count;
i = 0;
count = 0;
while (s[i] != '\0')
{
if (i == 0 && s[i] != c)
count++;
if (s[i] != c && (i > 0) && s[i - 1] == c)
count++;
i++;
}
return (count);
}
char **ft_split(char const *s, char c)
{
int len;
int l;
int count;
int i;
char **str;
len = 0;
l = 0;
i = 0;
if (s == 0)
return ((char **)ft_strdup(""));
count = ft_countword(s, c);
str = (char **)malloc(sizeof(char *) * count);
if (str == 0)
return (0);
while (i < count)
{
str[i] = (char *)malloc(sizeof(char) * ft_lenword(s, c, &len) + 1);
if (str[i] == 0)
return (ft_free(str));
str[i] = ft_cpyword(str[i], s, c, &l);
i++;
}
str[i] = 0;
return (str);
}
<file_sep>/srcs/ft_atoi_utimate.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_atoi_utimate.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/20 08:07:40 by ksam #+# #+# */
/* Updated: 2021/05/24 16:35:52 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
int *ft_atoi_utimate2(const char *str, long nb, int neg, int *ret)
{
int swap;
int i;
i = 0;
if (!(*str >= '0' && *str <= '9'))
return (NULL);
while (*str >= '0' && *str <= '9')
{
nb = nb * 10 + (*str - 48);
if (i++ > 10 || (neg == -1 && nb > 2147483648)
|| (neg == 1 && nb > 2147483647))
return (NULL);
str++;
}
while ((*str == '\t') || (*str == '\v') || (*str == '\n')
|| (*str == '\r') || (*str == '\f') || (*str == ' '))
str++;
if (*str != 0)
return (NULL);
swap = ((int)nb * neg);
ret = &swap;
return (ret);
}
/** Atoi without allowing letter, and check INT range. It return a pointer
* @return int* or NULL if @param str is not in INT range
*/
int *ft_atoi_utimate(const char *str)
{
long nb;
int neg;
int *ret;
nb = 0;
neg = 1;
ret = NULL;
while ((*str == '\t') || (*str == '\v') || (*str == '\n')
|| (*str == '\r') || (*str == '\f') || (*str == ' '))
str++;
if (*str == '-')
{
neg = -1;
str++;
}
else if (*str == '+')
str++;
return (ft_atoi_utimate2(str, nb, neg, ret));
}
<file_sep>/srcs/get_big_index.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_big_index.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/02 05:09:45 by ksam #+# #+# */
/* Updated: 2021/05/24 16:36:59 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
/** Get the index of the biggest number of stack
* @param under is the highest non-inclusive number that can be taken.
* NULL if didn't need.
* @return NULL if the index cannot be retrive
*/
int *get_index_of_biggest(t_stack *stack, int *under)
{
int index;
int *saved_index;
int *saved_int;
int swap;
index = stack->top;
saved_int = NULL;
saved_index = NULL;
while (index >= 0)
{
if ((!under || stack->array[index] < *under)
&& (!saved_int || *saved_int < stack->array[index]))
{
saved_int = &(stack->array[index]);
swap = index;
saved_index = &swap;
}
index--;
}
return (saved_index);
}
int *get_index_of_smallest(t_stack *stack, int *upper)
{
int index;
int *saved_index;
int *saved_int;
int swap;
index = stack->top;
saved_int = NULL;
saved_index = NULL;
while (index >= 0)
{
if ((!upper || stack->array[index] > *upper)
&& (!saved_int || *saved_int > stack->array[index]))
{
saved_int = &(stack->array[index]);
swap = index;
saved_index = &swap;
}
index--;
}
return (saved_index);
}
<file_sep>/srcs/push_swap/unit_tests.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* unit_tests.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/14 02:34:45 by ksam #+# #+# */
/* Updated: 2021/05/24 19:03:43 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../../includes/push_swap.h"
void unit_tests(t_stack_master *stack_master)
{
t_stack_master *stack_master2;
stack_master2 = ft_duplicate_stack_master(stack_master);
stack_master2->is_instruction = 1;
stack_master2->is_hiding_default_output = 1;
ft_auto_sort(stack_master2);
ft_stack_master_free(stack_master2);
}
void ft_test_random(int nb)
{
int *nbs;
nbs = ft_random_integers(nb, nb);
ft_test_numbers(nbs, nb);
}
void ft_test_numbers(int *nbs, int size)
{
t_stack_master *stack_master;
stack_master = ft_initialize_stack_master();
ft_create_stack_master(stack_master, size);
printf("Test for %d numbers >\n", size);
while (size)
ft_stack_add(stack_master->a, nbs[--size]);
unit_tests(stack_master);
free(nbs);
ft_stack_master_free(stack_master);
}
void ft_test_all(void)
{
int *nbs;
int nb;
nb = 3;
nbs = malloc(nb * sizeof(int));
nbs[0] = 2;
nbs[1] = 1;
nbs[2] = 0;
printf("\n\nSIMPLE VERSION 1 > ");
ft_test_numbers(nbs, nb);
nb = 5;
nbs = malloc(nb * sizeof(int));
nbs[0] = 1;
nbs[1] = 5;
nbs[2] = 2;
nbs[3] = 4;
nbs[4] = 3;
printf("\n\nSIMPLE VERSION 2 > ");
ft_test_numbers(nbs, nb);
printf("\n\nSIMPLE VERSION 3 > ");
ft_test_random(5);
printf("\n\nMIDDLE VERSION > ");
ft_test_random(100);
printf("\n\nADVANCED VERSION > ");
ft_test_random(500);
}
void ft_test_args(int argc, char **argv)
{
int *i;
if (argc >= 3)
{
i = ft_atoi_utimate(argv[2]);
if (i == NULL)
ft_error("Argument n°3 need to be an int");
else
ft_test_random(*i);
}
else
ft_test_all();
}
<file_sep>/srcs/instructions_utils.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* instructions_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/14 03:00:06 by ksam #+# #+# */
/* Updated: 2021/05/24 16:37:41 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
int colored_instructions2(t_stack_master *stack_master)
{
int pt;
pt = -1;
if (stack_master->a->capacity == 3)
{
if (stack_master->instructions <= 3)
pt = 5;
else
pt = 0;
}
else if (stack_master->a->capacity == 500)
{
if (stack_master->instructions <= 5500)
pt = 5;
else if (stack_master->instructions <= 7000)
pt = 4;
else if (stack_master->instructions <= 8500)
pt = 3;
else if (stack_master->instructions <= 10000)
pt = 2;
else if (stack_master->instructions <= 11500)
pt = 1;
}
return (pt);
}
int colored_instructions(t_stack_master *stack_master)
{
int pt;
pt = 0;
if (stack_master->a->capacity == 5)
{
if (stack_master->instructions <= 12)
pt = 5;
}
else if (stack_master->a->capacity == 100)
{
if (stack_master->instructions <= 700)
pt = 5;
else if (stack_master->instructions <= 900)
pt = 4;
else if (stack_master->instructions <= 1100)
pt = 3;
else if (stack_master->instructions <= 1300)
pt = 2;
else if (stack_master->instructions <= 1500)
pt = 1;
}
else
return (colored_instructions2(stack_master));
return (pt);
}
void ft_print_instructions(t_stack_master *stack_master)
{
int pt;
pt = colored_instructions(stack_master);
if (pt == 5)
printf("\e[42mPERFECT ");
else if (pt == 4)
printf("\e[92mTrès Bien ");
else if (pt == 3)
printf("\e[32mBien ");
else if (pt == 2)
printf("\e[96mPeux mieux faire ");
else if (pt == 1)
printf("\e[93mBof ");
else if (pt == 0)
{
printf("\e[101mKO ");
}
printf("%d instructions pour %d chiffres\033[0m\n",
stack_master->instructions, stack_master->a->capacity);
}
<file_sep>/srcs/stack3.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* stack3.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/30 04:46:08 by tglory #+# #+# */
/* Updated: 2021/05/24 16:38:37 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
void ft_stack_push(t_stack *stack, int item)
{
if (ft_stack_is_full(stack))
ft_error("The stack you trying to push on is full");
stack->array[++stack->top] = item;
}
/**
* get the last (index 0) int of stack
*/
int ft_stack_pop(t_stack *stack)
{
if (ft_stack_is_empty(stack))
ft_error("The stack you are trying to pop is empty");
return (stack->array[stack->top--]);
}
/**
* get the last (index 0) int of stack and remove it
*/
int ft_stack_peek(t_stack *stack)
{
if (ft_stack_is_empty(stack))
ft_error("The stack you are trying to peek is empty");
return (stack->array[stack->top]);
}
<file_sep>/srcs/stack2.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* stack2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/30 04:46:08 by tglory #+# #+# */
/* Updated: 2021/05/24 16:38:35 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
void ft_stack_free_stack(t_stack *stack)
{
if (stack == NULL)
return ;
if (stack->capacity > 0)
free(stack->array);
free(stack);
}
int ft_stack_is_full(t_stack *stack)
{
return (stack->top == stack->capacity - 1);
}
int ft_stack_is_empty(t_stack *stack)
{
return (stack->top == -1);
}
/**
* if momory is allocated for @param i objects
*/
int ft_stack_has_place(t_stack *stack, int i)
{
return (stack->capacity > stack->top + i);
}
<file_sep>/srcs/ft_args.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_args.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksam <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/20 14:48:20 by ksam #+# #+# */
/* Updated: 2021/05/24 16:35:31 by ksam ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "../includes/push_swap.h"
int ft_args_to_stack_master2(t_stack_master *stack_master, char *arg)
{
if (!ft_strncmp(arg, "-c", 3))
stack_master->is_colored = 1;
else if (!ft_strncmp(arg, "-v", 3))
stack_master->is_verbose = 1;
else if (!ft_strncmp(arg, "-i", 3))
stack_master->is_instruction = 1;
else if (!ft_strncmp(arg, "-h", 3))
stack_master->is_hiding_default_output = 1;
else
return (0);
return (1);
}
t_stack_master *ft_args_to_stack_master(char **argv, int max_stack_size)
{
t_stack_master *stack_master;
int i;
stack_master = ft_initialize_stack_master();
i = max_stack_size;
while (i)
{
if (ft_args_to_stack_master2(stack_master, argv[i--]) == 1)
max_stack_size--;
else
break ;
}
if (max_stack_size == 0)
ft_error_master(stack_master, "You need to add integer in arguments");
ft_create_stack_master(stack_master, max_stack_size);
while (max_stack_size)
ft_add(stack_master, stack_master->a, argv[max_stack_size--]);
return (stack_master);
}
| 3a110938e63e0df0ff9520dd7ce9b8694001f652 | [
"C",
"Makefile"
] | 28 | C | Kvnsm/push_swap | dc354e5c94ef67c0a4bcac9f6a82e30515f1ccde | 374c42ba9496b49d02481afced127ec3e6fca874 |
refs/heads/master | <repo_name>SlidingSteven/SecurityQuestionEvaluator<file_sep>/README.md
# SecurityQuestionEvaluator
## Introduction
This application was built to demonstrate how security questions on personal accounts pose a [serious weakness](https://www.wired.com/2016/09/time-kill-security-questions-answer-lies/) to the actual security of the account. This app tackles the problem from a few angles -
1. If you are in the account creation process, you can go to the [Home Page](https://sqschecker1.wn.r.appspot.com/) and enter the URL. This app will then scrape all questions from the page and will check if the questions contain key words we found in many "weak" questions.
2. If you want a demo of what public information is available on you, navigate to the [Public Info Demo](https://sqschecker1.wn.r.appspot.com/Full-Public-Info-Search) and enter your name and zipcode. The app will then pass that info to [FastPeopleSearch.com](fastpeoplesearch.com) and scrape the public info from the page using beautiful soup.
3. Another demo we have is to show the weakness of the common security question- ["What is your mother's maiden name?"](https://sqschecker1.wn.r.appspot.com/Mothers-Maiden-Name-Demo) For this we perform the same search and scrape technique as we did in the public info search, but this time we look a little deeper and pull the family list of the person entered and return each unique last name of all of the family memnbers.
4. If you are in need of a [secure answer](https://sqschecker1.wn.r.appspot.com/Secure-Answers) and don't know what to do, you can use our app to give one idea. On this page we take in a few answer components and return each permutation of that combination. It is not the most ideal solution but for some questions it is better than giving the most accurate answer.
This is not meant to be a complete solution but it should give users a good idea of what is out there and one potential fix for how to avoid issues with weak account questions.
## Goal
* Provide a way for people with no background in computer security to gain insight on the security level of security questions.
* Provide insight to users on how much information can be divulged from a small source of public information.
## Link
You can visit our site here- https://sqschecker1.wn.r.appspot.com/
Or view an API of the public info demo here- https://sqschecker1.wn.r.appspot.com/Full-Public-Info-Search?first_name=&last_name=&zipcode=
Example of the formatting- https://sqschecker1.wn.r.appspot.com/Full-Public-Info-Search?first_name=Bobby&last_name=Sue&zipcode=12345
## CHECKPOINTS
1. [x] Research Paper
2. [x] Lightning Talk
3. [x] Meet with professor
4. [x] Final Product
## How To Run
This flask app runs on Python 3. When I downloaded Python 3 it makes me use "python3" in the shell to run it, some people may only need to use 'python'. You can use pipenv to install dependencies and activate the shell-
```
python3 -m pipenv install
python3 -m pipenv shell
```
Next navigate to the folder with the file app.py and run
```
python3 app.py
```
Then go to http://127.0.0.1:5000/ to see the index page
# Explanation of each page
## Home Page
To check the strength of a set of particular security questions on a particular page
* enter the URL into the input.
* Select 'Run checker' to see if unsafe questions were found or not.
## The Team
Visit this page to learn more about our team and their roles in the creation of the SQS Checker.
## Demo Mothers Maiden Name
To find if your mother maiden name can be found, enter first name, last name, zip code.
* Select 'Run checker' to view results.
## Creating a Secure answer
In the case that you have no other option but to answer a weak question then the best thing you can do is to add components to your answer. You can add up to 5 components, and the SQS Checker will generate various passwords related to your mothers maiden name. They will contain special characters, which will make your security question harder to crack.
* Enter mothers name for component 1
* mothers birthday for component 2
and so on.
## Public Info Demo
* Enter First name, last name and zipcode
* Select run checker to check if your public information can be found by the SQS Checker
<file_sep>/requirements.txt
asn1crypto==0.24.0
backports.functools-lru-cache==1.6.1
beautifulsoup4==4.6.0
certifi==2020.4.5.1
chardet==3.0.4
cheroot==8.3.0
CherryPy==3.8.2
click==7.1.1
contextlib2==0.6.0.post1
cryptography==2.1.4
cycler==0.10.0
docopt==0.6.2
enum34==1.1.6
Flask==1.1.2
grip==4.5.2
gunicorn==20.0.4
idna==2.9
ipaddress==1.0.17
itsdangerous==1.1.0
jaraco.functools==2.0
Jinja2==2.11.1
keyring==10.6.0
keyrings.alt==3.0
kiwisolver==1.1.0
Markdown==3.1.1
MarkupSafe==1.1.1
matplotlib==2.2.5
more-itertools==5.0.0
numpy==1.16.6
oauthlib==3.1.0
pandas==0.24.2
parse==1.15.0
path-and-address==2.0.1
portend==2.6
pycrypto==2.6.1
Pygments==2.5.2
pyparsing==2.4.7
python-dateutil==2.4.2
pytz==2019.3
pyxdg==0.25
requests==2.23.0
requests-oauthlib==1.0.0
SecretStorage==2.3.1
six==1.14.0
spotipy==2.11.1
soupsieve==1.9.5
subprocess32==3.5.4
tempora==1.14.1
urllib3==1.25.8
Werkzeug==1.0.1
zc.lockfile==2.0
<file_sep>/publicInfoSearch.py
from bs4 import BeautifulSoup
from bs4.element import Comment
import urllib.request
import re
# This code will help to parse out the plain text from the html https://stackoverflow.com/questions/1936466/beautifulsoup-grab-visible-webpage-text
def vis_tag(element):
#discard invisible html because it does not matter to this project
if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
return False
#return visible
if isinstance(element, Comment):
return False
return True
def html_to_text(body):
#get the body of html
soup = BeautifulSoup(body, 'html.parser')
#find text
texts = soup.findAll(text=True)
#apply above filter to html
visible_texts = filter(vis_tag, texts)
return u" ".join(t.strip() for t in visible_texts)
def text_from_cards(body):
soup = BeautifulSoup(body, 'html.parser')
cards = soup.findAll("div", {"class": "card"})
#texts = soup.findAll(text=True)
visible_texts = filter(vis_tag, cards)
return u" ".join(t.strip() for t in visible_texts)
def SafeQuestions(listOfFlags, Questions):
for word in listOfFlags:
if word in Questions:#Not safe!
return False
return True #No flag word found
# followed tutorial to find this.
# This was a hurdle because it seems some webpages will and wont be accessed with beautiful soup
class AppURLopener(urllib.request.FancyURLopener):
version = "Mozilla/5.0"
#This is used to make a person object for each person the fastpeoplesearch returned
#since we have to investigate all possibilities we found this the easiest way to keep everything straight
class Person:
def __init__(self, name,age,link,family,aliases,addresses, mothersMaidenNames):
self.name = name
self.age = age
self.link = link
self.family = family
self.aliases = aliases
self.addresses = addresses
self.mothersMaidenNames = mothersMaidenNames
def get_age(self):
return(self.age)
def get_name(self):
return(self.name)
def get_link(self):
return(self.link)
def get_family(self):
return(self.family)
def get_aliases(self):
return(self.aliases)
def get_addresses(self):
return(self.addresses)
def get_Mothers_Maiden_Name(self):
return(self.mothersMaidenNames)
#formats the url to include input from the user
def formatURL(url):
base = 'https://www.fastpeoplesearch.com'
base += url
return base
#get high level details on each person returned
def highLevelDetails(url):
#initialize new opener
opener = AppURLopener()
#read contents returned
html = opener.open(url).read()
#get the soup
soup = BeautifulSoup(html, 'html.parser')
#grab the more in depth details link
links = soup.findAll("a", {"class": "btn btn-primary link-to-details"}, href=True)
listOfLinks = []
for link in links:
newLink = formatURL(link['href'])
listOfLinks.append(newLink)
h3s = soup.findAll("h3")
listOfNames = []
listOfAges = []
cards = soup.findAll("div", {"class":"card-block"})
for card in cards:
name = card
card_contents = name.get_text().split("\n")
for el in card_contents:
el.strip()
card_contents = list(filter(None, card_contents))
[x for x in card_contents if x]
ctr = 0
relatives_index = 100
for el in card_contents:
if "Age: " in el:
curr_age = el.replace("Age: ", "")
listOfAges.append(curr_age)
if "Full Name: " in el:
curr_name = el.replace("Full Name: ", "")
listOfNames.append(curr_name)
if "Mother, father" in el:
relatives_index = ctr
if ctr > relatives_index:
if " • " in el:
family = el.split(" • ")
ctr += 1
# get the everyone's current address, plan to include this on the api in my TODO
addresses = soup.findAll("a", {"title": re.compile('^Search people living at')}, text=True)
listOfAddresses = []
for address in addresses:
listOfAddresses.append(address.contents)
return listOfLinks, listOfNames, listOfAges
# the last function checked high level but returned a link to drill into each person found
def checkFurtherDetails(url):
#initialize opener
opener = AppURLopener()
#open the link to the person
html = opener.open(url).read()
# make the soup
soup = BeautifulSoup(html, 'html.parser')
# find the relatives table, build a list of each relative element
relatives_table = soup.findAll("div", {"id": "relative-links"})
relative_elements = relatives_table[0].findAll("div", {"class": "detail-box-content"})[0].find_all("dl", {"class": "col-sm-12 col-md-4"})
# build list of each relative from the list of elements
listOfRevs = []
for rel in relative_elements:
listOfRevs.append(rel.get_text().replace("\n","").strip())
# reformat the names to exclude the ages
formattedFamily = []
for member in listOfRevs:
member_name = member.split("Age")[0].strip()
formattedFamily.append(member_name)
# compile a list of last names, maiden name is likely to be here
mothersMaidenNames=[]
for member in formattedFamily:
if member.split()[1] not in mothersMaidenNames:
mothersMaidenNames.append(member.split()[1])
spouse = soup.find("div", {"id":"aka-links"})
listOfAliases = []
aliases = spouse.find('h3').contents
for alias in aliases:
alias = str(alias).strip('\t\r\n')
listOfAliases.append(alias)
listOfAliases = listOfAliases[0].split(" • ")
# compile a list of previous addresses
addresses = soup.findAll("a", {"title": re.compile('^Search people who live at')})
listOfAddresses = []
for address in addresses:
listOfAddresses += address.contents
addresses = soup.findAll("div", {"class": "detail-box-address"})
i=0
newListOfAddresses = []
for address in listOfAddresses:
address = str(address).strip('\t\r\n')
if "<br/>" not in address:
newListOfAddresses.append(address)
# return all that is found
return(formattedFamily, listOfAliases, newListOfAddresses,mothersMaidenNames)
def publicInformation(first, last, zipcode):
# build the url according to input
url = "https://www.fastpeoplesearch.com/name/" + first.lower() + "-" + last.lower() + "_" + zipcode
# fill out the high level details
links, names, ages = highLevelDetails(url)
# compile a list of people
peopleFound = []
i =0
for name in names:
familyMembers,aliases,newListOfAddresses,mothersMaidenNames = checkFurtherDetails(links[i])
# create a person object
tempPerson = Person(name, ages[i], links[i], familyMembers, aliases, newListOfAddresses, mothersMaidenNames)
# add the person to a list
peopleFound.append(tempPerson)
i += 1
return peopleFound
<file_sep>/newbs4.py
from bs4 import BeautifulSoup
from bs4.element import Comment
import urllib.request
import re
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
# This code will help to parse out the plain text from the html https://stackoverflow.com/questions/1936466/beautifulsoup-grab-visible-webpage-text
def vis_tag(element):
#discard invisible html because it does not matter to this project
if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
return False
#return visible
if isinstance(element, Comment):
return False
return True
def html_to_text(body):
#get the body of html
soup = BeautifulSoup(body, 'html.parser')
#find text
texts = soup.findAll(text=True)
#apply above filter to html
visible_texts = filter(vis_tag, texts)
return u" ".join(t.strip() for t in visible_texts)
def SafeQuestions(listOfFlags,Questions):
#Old function to determine if unsafe questions existed
for word in listOfFlags:
if word in Questions:#Not safe!
#print(Questions)
return False
return True #No flag word found
# followed tutorial to find this.
# This was a hurdle because it seems some webpages will and wont be accessed with beautiful soup
class AppURLopener(urllib.request.FancyURLopener):
version = "Mozilla/5.0"
# function to check url for targeted words
def checkURL(url):
#use SO function to open the webpage
opener = AppURLopener()
#get the html
html = opener.open(url).read()
#stringWithQuestions = re.compile(r'([A-Z][^\?]*[\?])', re.M)
#stringWithQuestions = re.search('^[A-Z].*\?$', str(html))
# use above funtion to get all of the visible text
html = html_to_text(html)
#print(html)
#split visible text on punctuation
stringWithQuestions = re.split('(?<=[.!?]) +', str(html))
#stringWithQuestions = re.findall('[A-Z].*process.$', str(html))
# find the questions on the page
listOfQs = []
for line in stringWithQuestions:
if "?" in line:
#print(line)
listOfQs.append(line)
#for q in listOfQs:
#print(q)
strg1 =""
with open('out.txt', 'w') as f:
strg = stringWithQuestions#.findall(html_to_text(html))
for sentence in strg:
strg1 = strg1 + sentence + "\n"
#print(strg1, file=f)
listOfFlags1 = ["maiden", "address", "name"]
dictOfWordsVals = {
"maiden" : 2,
"mother's maiden name" : 3,
"address" : 2,
"name" : 2,
"school" : 1,
"high school" : 2,
"highschool" : 2,
"college" : 2,
"college major" : 2,
"city" : 2,
"state" : 2,
"country" : 3,
"occupation" : 1,
"job" : 1,
"town" : 2,
"born" : 2,
"hair color" : 3,
"eye color" : 3,
"favorite movie" : 1,
"zipcode" : 3,
"zip code" : 3,
"zip-code" : 3,
"born": 1,
"spouse" : 2,
"graduate" : 1,
"favorite sport": 1
}
dictOfWordsReasons = {
"maiden" : " A maiden name can be guessed quite easily using public records.",
"mother's maiden name" : "A maiden name can be guessed quite easily using public records.",
"address" :"Past addresses are quite easily found using public records.",
"name" :"Public records keep a list of names suspected to be relatives. Additionally if you keep a friends list on social media this can be used against you by an attacker.",
"school" :"This is less likely to be found with a public records site but could easily be found through a person's social media.",
"high school" :
"This is less likely to be found with a public records site but could easily be found through a person's social media.",
"highschool" : "This is less likely to be found with a public records site but could easily be found through a person's social media.",
"college" : "This is less likely to be found with a public records site but could easily be found through a person's social media.",
"college major" : "This is less likely to be found with a public records site but could easily be found through a person's social media.",
"city" : "A list of cities stored in public record associated with your previous addresses could be used by an attacker to guess an answer to this question.",
"state" : "A list of states stored in public record associated with your previous addresses could be used by an attacker to guess an answer to this question.",
"country" : "A list of countries stored in public record associated with your previous addresses could be used by an attacker to guess an answer to this question.",
"occupation" : "Public records do not track occupation but this is something that could easily be found through a LinkedIn account or really any form of social media.",
"job" : "Public records do not track occupation but this is something that could easily be found through a LinkedIn account or really any form of social media.",
"town" : "A list of towns stored in public record associated with your previous addresses could be used by an attacker to guess an answer to this question.",
"born" : "Information regarding your birthdate or place of birth could be easily deduced by an attacker using public record",
"hair color" : "An attacker could easily look up a victim's social media to find information regarding hair color.",
"eye color" : "An attacker could easily look up a victim's social media to find information regarding eye color.",
"favorite movie" : "If you have a list of liked movies on Facebook this can be found easily by an attacker.",
"zipcode" : "A list of zipcodes stored in public record associated with your previous addresses could be used by an attacker to guess an answer to this question.",
"zip code" : "A list of zipcodes stored in public record associated with your previous addresses could be used by an attacker to guess an answer to this question.",
"zip-code" : "A list of zipcodes stored in public record associated with your previous addresses could be used by an attacker to guess an answer to this question.",
"spouse" : "Spousal information can be found quite easily with public record.",
"graduate" : "Graduation information can be found quite easily with a person's facebook.",
"favorite sport": "If an attacker knows a victim's social media this may be used against them to find the favorite sport."
}
#print("list of questions, ", listOfFlags1)
#print(dictOfWordsVals)
#for key in dictOfWordsVals:
# print(key)
stringOfOutput = []
for line in listOfQs:
for key in dictOfWordsVals:
if key in line:
#HTML Formats how the table will print out
stringTemp = key + ": " + dictOfWordsReasons[key] + "<th/><th> " + line + "<th/>"
stringOfOutput.append(stringTemp)
#print(key, " : ", dictOfWordsReasons[key], "\n", line, "\n")
#listOfQs.append(line)
for line in stringOfOutput:
#line = line.split('\n')
print(line)
##Attempt to make table better
stringOfOutputNew = []
for line in listOfQs:
for key in dictOfWordsVals:
if key in line:
#HTML Formats how the table will print out
stringTemp = key + ": " + dictOfWordsReasons[key] + "<br/> "
stringOfOutputNew.append(stringTemp)
return(stringOfOutput)
#print(listOfQs) print("are the questions safe?")
ruling = SafeQuestions(listOfFlags1,strg1)
if ruling:
print("Safe!")
#return True
else:
print("Not Safe!")
#return False
#strg1.split("\n")
#print(sentence)
#checkURL('https://www.loginradius.com/blog/2019/01/best-practices-choosing-good-security-questions/')
<file_sep>/main.py
from flask import Flask, request, render_template, jsonify
import newbs4
import publicInfoSearch
import itertools
import os
from collections import OrderedDict
from pprint import pprint
import json
app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False
#Url entry page
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
url = request.form['url']
ruling = newbs4.checkURL(url)
if ruling:
return render_template('SSQ Checker/resultsUnsafe.html', ruling = ruling)
else:
return render_template('SSQ Checker/resultsSafe.html', ruling = "NO UNSAFE QUESTIONS FOUND")
else:
return render_template('SSQ Checker/index.html')
# team page
@app.route('/team', methods=['GET', 'POST'])
def team():
return render_template('SSQ Checker/team.html')
# Page for the demonstration of a full public search
@app.route('/Full-Public-Info-Search', methods=['GET', 'POST'])
def fullSearch():
if request.method =='POST':
first_name = request.form['first']
last_name = request.form['last']
zipcode = request.form['zipcode']
try:
PeopleFound = publicInfoSearch.publicInformation(first_name, last_name, zipcode)
i=0
newList = []
data_list = []
json_obj = {}
for person in PeopleFound:
newString = ""
newString += PeopleFound[i].get_name() + "<br/>"
newString += PeopleFound[i].get_age() + "<br/>"
addresses = PeopleFound[i].get_addresses()
for address in addresses:
addy = address + "<br/>"
newString += addy
aliases = PeopleFound[i].get_aliases()
for alias in aliases:
ali = alias + "<br/>"
newString += ali
familyMembers = PeopleFound[i].get_family()
for family in familyMembers:
fam = family + "<br/>"
newString += fam
newList.append(newString)
curr_person = {
"name": PeopleFound[i].get_name(),
"age": PeopleFound[i].get_age(),
"addresses": PeopleFound[i].get_addresses()
}
data_list.append(json.dumps(curr_person))
i+=1
for el in data_list:
print(el)
#pprint(data_list)
if PeopleFound:
return render_template('SSQ Checker/FullSearchDemo.html', PeopleFound = newList)
else:
return render_template('SSQ Checker/FullSearchDemo.html', PeopleFound = "No Potential Information Found", flag = True)
except ValueError:
return render_template('SSQ Checker/FullSearchDemo.html', Error = "No Potential Information Found")
# else = GET request
else:
# check for query params (section following the ? in the url below)
# https://sqs-checker.herokuapp.com/Full-Public-Info-Search?first_name=Bobby&last_name=Sue&zipcode=12345
# by checking for these particular params, I am forcing the user to also use those particular params
# In other words, this is how the params are set to 'first_name', 'last_name' and 'zipcode'
if 'first_name' in request.args and 'last_name' in request.args and 'zipcode' in request.args:
# if the params exist then try to do a search with their contents
try:
# get the params from the url
first_name = request.args['first_name']
last_name = request.args['last_name']
zipcode = request.args['zipcode']
# perform the same search as we did with the post request
PeopleFound = publicInfoSearch.publicInformation(first_name, last_name, zipcode)
i=0
# declare a list to put person results in
data_list = []
# for each person in the list that was found, add their person info
for person in PeopleFound:
curr_person = {
"name": PeopleFound[i].get_name(),
"age": PeopleFound[i].get_age(),
"addresses": PeopleFound[i].get_addresses(),
"aliases": PeopleFound[i].get_aliases(),
"family": PeopleFound[i].get_family()
}
#add the person to the list
data_list.append(curr_person)
i+=1
# return the list as a json object
return jsonify(data_list)
# if 1- the contents are formatted incorrectly, or 2- the contents return no results then return an error message
except:
return """Error: A field is missing or no data was returned.
See below for formatting-\n
https://sqs-checker.herokuapp.com/Full-Public-Info-Search?first_name=Bobby&last_name=Sue&zipcode=12345
If you think you have it properly formatted you can try searching your name on fastpeoplesearch.com which is where I scrape from."""
# if there are no query params then just return the html for the entry
return render_template('SSQ Checker/FullSearchDemo.html')
#Mother's maiden name demo
@app.route('/Mothers-Maiden-Name-Demo', methods=['GET', 'POST'])
def MaidenNameDemo():
if request.method == 'POST':
first_name = request.form['first']
last_name = request.form['last']
zipcode = request.form['zipcode']
try:
PeopleFound = publicInfoSearch.publicInformation(first_name, last_name, zipcode)
maidenNames = []
for person in PeopleFound:
tempNames = person.get_Mothers_Maiden_Name()
for tempName in tempNames:
if tempName not in maidenNames:
maidenNames.append(tempName)
if PeopleFound:
return render_template('SSQ Checker/MaidenDemoSearch.html', listOfPeople = maidenNames)
else:
return render_template('SSQ Checker/MaidenNameDemo.html', listOfPeople = "No Potential Maiden Names Found", flag = True)
except ValueError:
return render_template('SSQ Checker/MaidenNameDemo.html', listOfPeople = "No Potential Maiden Names Found")
else:
return render_template('SSQ Checker/MaidenDemoSearch.html')#, ruling = "SAFE")
#Secure answer builder demo
@app.route('/Secure-Answers', methods=['GET', 'POST'])
def secureAnswers():
if request.method == 'POST':
component0 = request.form['component0']
component1 = request.form['component1']
component2 = request.form['component2']
component3 = request.form['component3']
component4 = request.form['component4']
#
#
# COPY SECTION FOR API
#
#
# TODO FOR API: COPY FROM HERE
listOfRecommendations = []
numComponents = 0
if component0:
numComponents += 1
listOfRecommendations.append(component0)
if component1:
numComponents += 1
listOfRecommendations.append(component1)
if component2:
numComponents += 1
listOfRecommendations.append(component2)
if component3:
numComponents += 1
listOfRecommendations.append(component3)
if component4:
numComponents += 1
listOfRecommendations.append(component4)
perm = itertools.permutations(listOfRecommendations)
betterFormattedList = []
if numComponents == 1:
for i in list(perm):
betterFormattedList.append(i[0])
print(betterFormattedList)
if numComponents == 2:
for i in list(perm):
betterFormattedList.append(i[0]+"--"+i[1])
print(betterFormattedList)
if numComponents == 3:
for i in list(perm):
betterFormattedList.append(i[0]+"--"+i[1]+"--"+i[2])
print(betterFormattedList)
if numComponents == 4:
for i in list(perm):
betterFormattedList.append(i[0]+"--"+i[1]+"--"+i[2]+"--"+i[3])
print(betterFormattedList)
if numComponents == 5:
for i in list(perm):
betterFormattedList.append(i[0]+"--"+i[1]+"--"+i[2]+"--"+i[3]+"--"+i[4])
print(betterFormattedList)
# TODO FOR API: TO HERE
#
#
# COPY SECTION FOR API
#
#
return render_template('SSQ Checker/SecureInput.html', betterFormattedList = betterFormattedList)
else:
# check if query params exist (If it were me I'd check for "component1, component2... so on, just like in the post method above.")
# if the query params exist then run the code from line 170-208 (I have comments around the code), return the jsonify-ed list
# else return error message
return render_template('SSQ Checker/SecureInput.html')#, ruling = "SAFE")
#runs the app
if __name__ == '__main__':
app.debug = True
app.run()#port = os.environ["PORT"])
<file_sep>/requirementsOld.txt
beautifulsoup4==4.6.0
Click==7.0
Flask==1.1.1
gunicorn==20.0.4
itsdangerous==1.1.0
Jinja2==2.10.3
MarkupSafe==1.1.1
soupsieve==1.9.5
Werkzeug==0.16.0
| 905ec8d7d3dbc4a211066c85856dd2f6ae2d5efe | [
"Markdown",
"Python",
"Text"
] | 6 | Markdown | SlidingSteven/SecurityQuestionEvaluator | abdefe634424da439a288dd9659cda4ab8fadd97 | 8dcb5669c12f2ebe6b786091bc12cc3eb88e05ff |
refs/heads/master | <file_sep>package main;
import java.util.*;
public class Horse {
public static void main(String[] args) {
int[] N = {5,15,17,3,8,11,6,55,7};
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < N.length; i++) {
list.add(N[i]);
}
Collections.sort(list);
System.out.println(list);
Integer result = null;
Integer tmp = null;
for (int i = 0; i < list.size()-1; i++) {
tmp = list.get(i+1) - list.get(i);
if (result == null) {
result = tmp;
} else if (tmp < result) {
result = tmp;
}
}
System.out.println(result);
}
}
| e7d775114498d2feb30d47d1ac76438fdd30c8db | [
"Java"
] | 1 | Java | Rafosk/horse | d36eaecc2a47e48aaf34e2f3479d0818b4396056 | e67ac62141d69a1235d4be85d397d5ba2a4ff9eb |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
import glob
# The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell
from pathlib import Path
# The final path component, without its suffix
mon_chemin = input('Quel est le chemin relatif du répertoire contenant les fichiers csv ?\n')
#"./MIB_Files/"
mon_alias = input('Alias du fichier py créé (sera ./MaBase_alias.py) ?\n')
mon_fic = "MaBase_%s.py" % mon_alias
mes_csv_file = {Path(f).stem:open(f,"r") for f in glob.glob(mon_chemin + "*.csv")}
mes_csv = {Path(f).stem:open(f,"r").readlines() for f in glob.glob(mon_chemin + "*.csv")}
mon_py = open(mon_fic,"w+")
def creer_classes():
for b in mes_csv:
mon_py.write("class " + b[4:-1] + ":\n\tdef __init__(self")
lignes = mes_csv[b]
attributs = lignes[0].split()[0].split(',')
for a in attributs:
mon_py.write(", " + a)
mon_py.write("):\n\t\t")
for a in attributs:
mon_py.write("self.%s = %s\n\t\t" % (a,a))
mon_py.write("\n\n")
def creer_bases():
for b in mes_csv:
nom = b[4:-1]
mon_py.write(b + " = { ")
lignes = mes_csv[b]
for index,ligne in enumerate(lignes[1:]):
ligne = ligne.split()[0].split(',')
debut = '' if index == 0 else ', '
mon_py.write(debut + nom + "(")
for att in ligne[:-1]:
mon_py.write("'" + att + "', ")
mon_py.write("'" + ligne[-1] +"')")
mon_py.write(" }\n\n")
def ferme():
for b in mes_csv_file:
mes_csv_file[b].close()
mon_py.close()
creer_classes()
creer_bases()
ferme()
| d69a399c5df3b64cef14d796267d37bcd82bd90e | [
"Python"
] | 1 | Python | Pamfeu/Complements_Info_L1_UCO_Angers | e8658a5c506695a6cfb73405cb3883e37e618c20 | f7728d3096c53fe3c20b932e3813bf64fb5392e9 |
refs/heads/master | <file_sep>// omp_studio.cpp: определяет точку входа для консольного приложения.
//
//#include "stdafx.h"
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
const int Size = 2000;
int a[Size][Size];
int b[Size][Size];
int c[Size][Size];
int main(int argc, char *argv[])
{
double start_time;
double end_time;
double search_time1;
double search_time2;
int i, j, k, sum;
int rand = 2;
for (int q = 0; q < Size; q++){
for (int w = 0; w < Size; w++){
a[q][w] = rand;
b[q][w] = rand;
}
rand++;
}
start_time = omp_get_wtime();
for (i = 0; i < Size; ++i) for (j = 0; j < Size; ++j) {
sum = 0;
for (k = 0; k < Size; ++k)
sum += a[i][k] * b[k][j];
c[i][j] = sum;
}
search_time1 = omp_get_wtime() - start_time;
start_time = omp_get_wtime(); // начальное время
#pragma omp parallel for private (j,i,k)
for (i = 0; i < Size; ++i) for (j = 0; j < Size; ++j) {
sum = 0;
for (k = 0; k < Size; ++k)
sum += a[i][k] * b[k][j];
c[i][j] = sum;
}
end_time = omp_get_wtime();
search_time2 = end_time - start_time;
std::cout << "Step by step:" << search_time1 << std::endl;
std::cout << "Parallel: " << search_time2 << std::endl;
std::cout << "/n" << std::endl;
return 0;
}
| d1f145e151dae3904a55590bc24fa1a1ce6476ab | [
"C++"
] | 1 | C++ | amdandrew/borisova-olga | 42151e241d9c4287cc20365b56f99c18a13b2d56 | a6b15cbe01d9dde79131395767bae685b03e1617 |
refs/heads/master | <file_sep>function showMenu(){
var element = document.getElementById('menu-list');
element.style.transform = "scale(1,1)";
};
function hideMenu(){
var element = document.getElementById('menu-list');
element.style.transform = "scale(0,0)";
};
/*set min-height*/
function myFunction() {
var h = window.innerHeight;
var section1 = document.getElementById('omnie'),
section2 = document.getElementById('kontakt'),
section3 = document.getElementById('glowna');
section1.style.minHeight= h + "px";
section2.style.minHeight= h + "px";
section3.style.minHeight= h + "px";
};
myFunction();
window.addEventListener("resize", myFunction);
/*end of set min-height */
| 965ac524309e14a458445a4cb7ccf951419c609e | [
"JavaScript"
] | 1 | JavaScript | ArTooDToo/Exercise | f814b4925629acc9cf75781fc9ebef20fb2ce659 | 6c93f50f3de418045892324ba812970e6e0b02b2 |
refs/heads/master | <repo_name>JP97/MyProjectMVC<file_sep>/Utilities/ApiHelper.cs
using MyProjectMVC.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace MyProjectMVC.Utilities
{
public class ApiHelper
{
public string GetRequest { get; set; } = "https://localhost:44342/api/teams";
public string Post { get; set; } = "https://localhost:44342/api/teams";
public List<Team> GetTeams()
{
List<Team> teams = new List<Team>();
string json = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GetRequest);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
json = reader.ReadToEnd();
}
teams = JsonConvert.DeserializeObject<List<Team>>(json);
return teams;
}
public string PostTeamData(Team team)
{
//laver det opject du vil poste til en json fil som er en string
string payLoad = JsonConvert.SerializeObject(team);
//URI som er linket til api
Uri uri = new Uri(Post);
//laver et httpcontext som indeholder dit payload, måden den skal encode det og media type.
HttpContent content = new StringContent(payLoad, System.Text.Encoding.UTF8, "application/json");
//kald af metoden der poster som får både uri og content som parameter og
//som får statuscode tilbage som string
var response = UpLoadUserDataPost(uri, content);
return response.ToString();
}
private async Task<string> UpLoadUserDataPost(Uri uri, HttpContent content)
{
string response = string.Empty;
using (HttpClient c = new HttpClient())
{
HttpResponseMessage result = await c.PostAsync(uri, content);
//check if statuscode is successfull, hvis ja bliver det gemt i response
//hvis ikke er den bare tom, kan så tjekkes i controlleren med et try catch
if (result.IsSuccessStatusCode)
{
response = result.StatusCode.ToString();
}
}
return response;
}
}
}
<file_sep>/Data/MyProjectMVCContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MyProjectMVC.Models;
namespace MyProjectMVC.Data
{
public class MyProjectMVCContext : DbContext
{
public MyProjectMVCContext (DbContextOptions<MyProjectMVCContext> options)
: base(options)
{
}
public DbSet<Player> Player { get; set; }
public DbSet<Team> Team { get; set; }
}
}
<file_sep>/Utilities/GenericApiHelper.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace MyProjectMVC.Utilities
{
public class GenericApiHelper<T>
{
private T model;
public string Address { get; set; }
public List<string> Headers { get; set; }
public GenericApiHelper(T Model)
{
model = Model;
}
public T PopulateModel()
{
string json = GetJsonData();
JsonConvert.PopulateObject(json, model);
return model;
}
private string GetJsonData()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Address);
request.Method = "GET";
foreach (string h in Headers)
{
request.Headers.Add(h);
}
string json;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
json = reader.ReadToEnd();
}
return json;
}
}
}
<file_sep>/Models/ViewModels/Teamwithplayer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyProjectMVC.Models.ViewModels
{
public class Teamwithplayer
{
public IEnumerable<Team> Teams { get; set; }
public IEnumerable<Player> Players { get; set; }
}
}
| 6a95e55aa66c1f9ce1a6f865e46492fd4bc7095d | [
"C#"
] | 4 | C# | JP97/MyProjectMVC | 06af13940c8bcacfc8630a45691ff888bfbc535e | 4280d7de6b64e6ab667668468472b40cb506e1b1 |
refs/heads/master | <repo_name>biammsilva/programacaoScripts<file_sep>/manada2.js
function Cachorro(){
this.barulho="Au";
}
function Gato(){
this.barulho="Miau";
}
function ManadaVirgula(){
tempo=1;
bar=", ";
Manada.call(this);
}
function ManadaSustenidaDupla(){
tempo=2;
bar="# ";
Manada.call(this);
}
function Manada(){
lista=[];
this.adicionar=function(x){
lista.push(x);
}
this.barulhos=function(){
s="";
for (var i = 0; i<lista.length; i++) {
if (i==lista.length-1) {
s+=lista[i].barulho;
}else{
for(var j=0;j<tempo-1;j++){
s+=lista[i].barulho+bar;
}
}
}
return s;
}
}
ManadaSustenidaDupla.prototype=new Manada();
ManadaVirgula.prototype=new Manada();
///////////////////////////////////////////////////////////////////////////////////////////////
var manadaVirgula = new ManadaVirgula();
var manadaSustenidaDupla = new ManadaSustenidaDupla();
var animais = [new Cachorro(), new Gato()];
animais.forEach(function (animal) {
manadaVirgula.adicionar(animal);
manadaSustenidaDupla.adicionar(animal);
});
// Print Esperado: Au, Miau
console.log(manadaVirgula.barulhos());
// Print Esperado: Au# Au# Miau# Miau
console.log(manadaSustenidaDupla.barulhos());
<file_sep>/observer.js
function gerarListener(){
var obj={contador: 0};
listeners=[];
obj.executar = function(){
obj.contador++;
var evento={"contador": obj.contador};
for (var i = 0; i < listeners.length; i++) {
listeners[i](evento);
}
}
obj.adicionarOuvinte = function(func){
listeners.push(func);
}
return obj;
}
var contadorObserver=gerarListener();
contadorObserver.adicionarOuvinte(
function(evento){
console.log("1 ouvinte"+evento.contador);
});
contadorObserver.adicionarOuvinte(
function(evento){
console.log("2 ouvinte"+evento.contador);
});
contadorObserver.executar();
contadorObserver.executar();
contadorObserver.executar();
contadorObserver.executar();
contadorObserver.executar();
contadorObserver.executar();
contadorObserver.executar();
contadorObserver.executar(); | 3d6f7ab150ad41aa3259430472a4f5080135f58f | [
"JavaScript"
] | 2 | JavaScript | biammsilva/programacaoScripts | a5ea01161d6947f1eeee294666ff6da128d10411 | fc0f61852e0ffd769bab71b61fb9ee51b884e49c |
refs/heads/master | <file_sep>//
// GradientView.swift
// ImageViewer
//
// Created by Admin on 6/1/18.
// Copyright © 2018 Admin. All rights reserved.
//
import GradientView
import Foundation
extension UIView {
func drawTopGradient(){
self.layer.mask = CAGradientLayer.topGradient(withBound: self.bounds)
self.backgroundColor = UIColor.black
}
func drawBottomGradient(){
self.layer.mask = CAGradientLayer.bottomGradient(withBound: self.bounds)
self.backgroundColor = UIColor.black
}
}
<file_sep>//
// borrar.swift
// ImageViewer
//
// Created by Admin on 5/31/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
import SQLite
class Borrar {
var unInt: Int64
init(withRow row_item: Row) {
unInt = row_item[Borrar_Table.unInt]
}
init(withMergedRow row_item: Row) {
unInt = row_item[Borrar_Table.Borrar[Borrar_Table.unInt]]
}
var debug :String {
return "\(unInt)"
}
}
class Borrar_Table {
static let Borrar = Table("borrar")
static let unInt = Expression<Int64>("unInt")
}
func tester_Borrar_Table() {
do {
let dd = try StoryDatabase.shared.db.prepare(Borrar_Table.Borrar)
for ddItem in dd {
let dde = Borrar(withRow: ddItem)
print("dde: \(dde.debug)")
}
} catch {
print("\(error)")
}
}
<file_sep># Uncomment the next line to define a global platform for your project
platform :ios, '9.0'
inhibit_all_warnings!
target 'ImageViewer' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# ---------- Pods for ImageViewer
# database (SQLite) library
pod 'SQLite.swift', '0.11.5'
# gradient view library
pod 'GradientView', '2.3.3'
# image slider library
pod 'ImageSlideshow', '1.5.3'
# reactive functional libraries
pod 'RxSwift', '4.0.0'
# swift code formatter
pod 'SwiftFormat/CLI', '0.33.6'
# logging
pod 'CocoaLumberjack/Swift', '3.4.2'
# di framework
pod 'Swinject', '2.4.0'
pod 'SwinjectStoryboard', '1.2.1'
# navigation library
pod 'Presentr', '1.3.2'
# loading splash
pod 'NVActivityIndicatorView'
# ---------- Pods for ImageViewer end
target 'ImageViewerTests' do
inherit! :search_paths
# Pods for testing
end
target 'ImageViewerUITests' do
inherit! :search_paths
# Pods for testing
end
end
<file_sep>//
// SplashViewModel.swift
// ImageViewer
//
// Created by Admin on 6/6/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
import RxSwift
import CocoaLumberjack
class SplashViewModel {
var databaseService : DatabaseService!
enum STATE: Int {
case IDLE = 0
case GETTING_CATALOG = 1
case GETTING_CATALOG_ERROR = 2
case GETTING_CATALOG_SUCCESS = 3
}
var state: BehaviorSubject<STATE> = BehaviorSubject<STATE>(value: STATE.IDLE)
func getTopImageList() -> Single<[Image]?>{
return Single<[Image]?>.create { single in
guard let imageList = self.databaseService.getTopImageList() else {
fatalError()
}
single(.success(imageList))
return Disposables.create()
}
}
func getFavoritesImageList() -> [Image]! {
guard let imageList = databaseService.getFavoritesImageList() else {
return nil
}
if imageList.count == 0 {
return nil
}
return imageList
}
func getSpecialImageList() -> [[Image]] {
return databaseService.getSpecialImageList()
}
func getImageList() -> Single<[[Image]]> {
return Single<[[Image]]>.create { single in
var imageSet = self.getSpecialImageList()
if let favoritesImageList = self.getFavoritesImageList() {
// for item in favoritesImageList {
// guard let _ = item.getUIImage() else {
// DDLogError("Cannot get image")
// continue
// }
// }
imageSet.append(favoritesImageList)
}
single(.success(imageSet))
return Disposables.create()
}
}
private func initImageList(){
_ = getImageList()
.asObservable()
.subscribe(onNext: {imageSet in
for itemList in imageSet {
for item in itemList {
guard let _ = item.getUIImage() else {
DDLogError("Cannot get image")
continue
}
}
}
Assets.shared.imageSet = imageSet
self.state.onNext(.GETTING_CATALOG_SUCCESS)
})
}
private func initTopImage(){
_ = getTopImageList()
.asObservable()
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.subscribe(onNext: {imageList in
guard let imageList = imageList else {
return
}
for item in imageList {
guard let _ = item.getUIImage() else {
DDLogError("Cannot get image")
continue
}
}
Assets.shared.topImageList = imageList
self.initImageList()
})
}
func initImageAsset(){
self.state.onNext(.GETTING_CATALOG)
initTopImage()
}
}
<file_sep>//
// LogFormatter.swift
// ImageViewer
//
// Created by Admin on 5/31/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
import CocoaLumberjack
public class LogFormatter: NSObject, DDLogFormatter {
let dateFormatter = DateFormatter()
let appName = Bundle.main.infoDictionary![kCFBundleNameKey as String] ?? "unknown_app"
public override init() {
super.init()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSSZ"
}
public func format(message logMessage: DDLogMessage) -> String? {
let logLevel: String
switch logMessage.flag {
case DDLogFlag.error:
logLevel = "ERROR"
case DDLogFlag.warning:
logLevel = "WARNING"
case DDLogFlag.info:
logLevel = "INFO"
case DDLogFlag.debug:
logLevel = "DEBUG"
default:
logLevel = "VERBOSE"
}
let dt = dateFormatter.string(from: logMessage.timestamp)
let logMsg = logMessage.message
let lineNumber = logMessage.line
let file = logMessage.file
let functionName = logMessage.function
let threadId = logMessage.threadID
return "\(dt) \(appName)[\(threadId)] [\(logLevel)] \(logMsg) (\(file):\(lineNumber) - \(functionName ?? "anonymous"))"
}
}
<file_sep>//
// ImageService.swift
// ImageViewer
//
// Created by Admin on 5/31/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
import SQLite
class ImageService {
func getImageList() -> [Image]! {
let query = Image_Table.Image
do {
var arr_result = [Image]()
for item in try StoryDatabase.shared.db.prepare(query) {
let obj = Image(withRow: item)
arr_result.append(obj)
}
return arr_result
} catch {
print("\(error)")
}
return nil
}
func getImage(byId idImage:Int64) -> Image! {
let query = Image_Table.Image.filter(Image_Table.idImage == idImage).limit(1)
do {
guard let row_item = try StoryDatabase.shared.db.pluck(query) else {
return nil
}
return Image(withRow: row_item)
} catch {
print("\(error)")
}
return nil
}
}
<file_sep>//
// CollectionImage.swift
// ImageViewer
//
// Created by Admin on 5/31/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
import SQLite
class CollectionImage {
var idCollection: Int64
var idImage: Int64
init(withRow row_item: Row) {
idCollection = row_item[CollectionImage_Table.idCollection]
idImage = row_item[CollectionImage_Table.idImage]
}
init(withMergedRow row_item: Row) {
idCollection = row_item[CollectionImage_Table.CollectionImage[CollectionImage_Table.idCollection]]
idImage = row_item[CollectionImage_Table.CollectionImage[CollectionImage_Table.idImage]]
}
var debug :String {
return "\(idCollection) \(idImage)"
}
}
class CollectionImage_Table {
static let CollectionImage = Table("collection_image")
static let idCollection = Expression<Int64>("idCollection")
static let idImage = Expression<Int64>("idImage")
}
func tester_CollectionImage_Table() {
do {
let dd = try StoryDatabase.shared.db.prepare(CollectionImage_Table.CollectionImage)
for ddItem in dd {
let dde = CollectionImage(withRow: ddItem)
print("dde: \(dde.debug)")
}
} catch {
print("\(error)")
}
}
<file_sep>//
// UIView.swift
// ImageViewer
//
// Created by Admin on 5/31/18.
// Copyright © 2018 Admin. All rights reserved.
//
import UIKit
import Foundation
extension UIView {
func fadeTransition(_ duration:CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name:
kCAMediaTimingFunctionEaseInEaseOut)
animation.type = kCATransitionFade
animation.duration = duration
layer.add(animation, forKey: kCATransitionFade)
}
}
<file_sep>//
// CAGradientLayer.swift
// ImageViewer
//
// Created by Admin on 6/1/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
import UIKit
extension CAGradientLayer {
static func topGradient(withBound bound:CGRect)->CAGradientLayer {
let gradient = CAGradientLayer()
gradient.startPoint = CGPoint(x: 0.5, y: 0.0)
gradient.endPoint = CGPoint(x: 0.5, y: 1.0)
let whiteColor = UIColor.blue
gradient.colors = [whiteColor.withAlphaComponent(1.0).cgColor, whiteColor.withAlphaComponent(1.0), whiteColor.withAlphaComponent(0.0).cgColor]
gradient.locations = [NSNumber(value: 0.0), NSNumber(value: 0.8),NSNumber(value: 1.0)]
gradient.frame = bound
return gradient
}
static func bottomGradient(withBound bound:CGRect)->CAGradientLayer {
let whiteColor = UIColor.blue
let gradient = CAGradientLayer()
gradient.startPoint = CGPoint(x: 0.5, y: 0.0)
gradient.endPoint = CGPoint(x: 0.5, y:1.0)
gradient.colors = [whiteColor.withAlphaComponent(0.0).cgColor, whiteColor.withAlphaComponent(1.0), whiteColor.withAlphaComponent(1.0).cgColor]
gradient.locations = [NSNumber(value: 0.0), NSNumber(value: 0.2),NSNumber(value: 1.0)]
gradient.frame = bound
return gradient
}
}
<file_sep>//
// CollectionImageService.swift
// ImageViewer
//
// Created by Admin on 5/31/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
import SQLite
import CocoaLumberjack
class CollectionImageService {
func getCollectionImageList(byId idCollection:Int64) -> [CollectionImage]! {
let query = CollectionImage_Table.CollectionImage.filter(CollectionImage_Table.idCollection == idCollection)
do {
var arr_result = [CollectionImage]()
for item in try StoryDatabase.shared.db.prepare(query) {
let obj = CollectionImage(withRow: item)
arr_result.append(obj)
}
return arr_result
} catch {
DDLogError("\(error)")
}
return nil
}
func addCollectionImage(id idCollection:Int64, idImage: Int64){
let query = CollectionImage_Table.CollectionImage
.insert(
CollectionImage_Table.idCollection <- idCollection,
CollectionImage_Table.idImage <- idImage
)
do {
_ = try StoryDatabase.shared.db.run(query)
}catch{
DDLogError(error.localizedDescription)
}
}
func removeCollectionImage(id idCollection:Int64, idImage: Int64){
let query = CollectionImage_Table.CollectionImage
.filter(
CollectionImage_Table.idCollection == idCollection &&
CollectionImage_Table.idImage == idImage
)
_ = try! StoryDatabase.shared.db.run(query.delete())
}
}
<file_sep>//
// MenuViewController.swift
// ImageViewer
//
// Created by Admin on 6/2/18.
// Copyright © 2018 Admin. All rights reserved.
//
import UIKit
class MenuViewController: UIViewController {
@IBOutlet weak var languageButtonOutlet: UIButton!
@IBOutlet weak var closeImageOutlet: UIImageView!
@IBOutlet weak var facebookImageOutlet: UIImageView!
@IBOutlet weak var twiterImageOutlet: UIImageView!
@IBOutlet weak var instagramImageOutlet: UIImageView!
@IBOutlet weak var pintestImageOutlet: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// init langualge buootn
languageButtonOutlet.layer.cornerRadius = languageButtonOutlet.frame.height / 2
initMenu()
initLinkImage()
}
@objc func menuImageTapped(tapGestureRecognizer: UITapGestureRecognizer){
if let revealVC = revealViewController() {
// revealVC.rearViewRevealWidth = self.view.frame.width
revealVC.rightViewRevealWidth = self.view.frame.width
revealVC.rightRevealToggle(animated: true)
view.addGestureRecognizer(revealVC.panGestureRecognizer())
view.addGestureRecognizer(revealVC.tapGestureRecognizer())
}
}
func initMenu(){
let tapMenuImage_GestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(menuImageTapped(tapGestureRecognizer:)))
closeImageOutlet.isUserInteractionEnabled = true
closeImageOutlet.addGestureRecognizer(tapMenuImage_GestureRecognizer)
}
func openURL(_ url:String) {
guard let url = URL(string: url) else {
return //be safe
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
@objc func facebookImageTapped(tapGestureRecognizer: UITapGestureRecognizer){
openURL("https://www.facebook.com")
}
@objc func twiterImageTapped(tapGestureRecognizer: UITapGestureRecognizer){
openURL("https://twitter.com")
}
@objc func instagramImageTapped(tapGestureRecognizer: UITapGestureRecognizer){
openURL("https://www.instagram.com")
}
@objc func pintestImageTapped(tapGestureRecognizer: UITapGestureRecognizer){
openURL("https://www.pinterest.com")
}
func initLinkImage() {
let tapFacebookImage_GestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(facebookImageTapped(tapGestureRecognizer:)))
facebookImageOutlet.isUserInteractionEnabled = true
facebookImageOutlet.addGestureRecognizer(tapFacebookImage_GestureRecognizer)
let tapTwiterImage_GestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(twiterImageTapped(tapGestureRecognizer:)))
twiterImageOutlet.isUserInteractionEnabled = true
twiterImageOutlet.addGestureRecognizer(tapTwiterImage_GestureRecognizer)
let tapInstagramImage_GestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(instagramImageTapped(tapGestureRecognizer:)))
instagramImageOutlet.isUserInteractionEnabled = true
instagramImageOutlet.addGestureRecognizer(tapInstagramImage_GestureRecognizer)
let tapPintestImage_GestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(pintestImageTapped(tapGestureRecognizer:)))
pintestImageOutlet.isUserInteractionEnabled = true
pintestImageOutlet.addGestureRecognizer(tapPintestImage_GestureRecognizer)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
<file_sep>//
// AppDelegate+DependencyInjection.swift
// ImageViewer
//
// Created by Admin on 6/1/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
import Swinject
import SwinjectStoryboard
extension AppDelegate {
func registerServices() {
// auth service and api
diContainer.register(DatabaseService.self) { _ in
let databaseService = DatabaseService()
return databaseService
}
}
func registerViewModels(){
diContainer.register(SplashViewModel.self) { r in
let splashViewModel = SplashViewModel()
splashViewModel.databaseService = r.resolve(DatabaseService.self)
return splashViewModel
}
diContainer.register(MainViewModel.self) { r in
let mainViewModel = MainViewModel()
return mainViewModel
}
// diContainer.register(ImageViewModel.self) { r in
// let imageViewModel = ImageViewModel()
// imageViewModel.databaseService = r.resolve(DatabaseService.self)
// return imageViewModel
// }
}
func registerViewControllers(){
diContainer.storyboardInitCompleted(SplashViewController.self) { r, c in
c.viewModel = r.resolve(SplashViewModel.self)
}
diContainer.storyboardInitCompleted(MainViewController.self) { r, c in
c.viewModel = r.resolve(MainViewModel.self)
}
// diContainer.storyboardInitCompleted(ImageViewerController.self) { r, c in
// c.viewModel = r.resolve(ImageViewModel.self)
// }
}
}
<file_sep>//
// AppDelegate.swift
// ImageViewer
//
// Created by Admin on 5/31/18.
// Copyright © 2018 Admin. All rights reserved.
//
import UIKit
import Swinject
import SwinjectStoryboard
import CocoaLumberjack
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// MARK: - AppDelegate fields
let window = UIWindow(frame: UIScreen.main.bounds)
// MARK: - dependency injection fields
let diContainer = Container()
var mainSwinjectStoryboard: SwinjectStoryboard!
fileprivate func grabStoryboard() -> String {
if UIDevice.current.userInterfaceIdiom == .pad {
return "Main"
} else {
return "iPhone"
}
}
override init() {
super.init()
mainSwinjectStoryboard = SwinjectStoryboard.create(name: grabStoryboard(), bundle: nil, container: diContainer)
registerServices()
registerViewModels()
registerViewControllers()
NSSetUncaughtExceptionHandler { exception in
DDLogError("Uncaught exception [\(exception)] occurred")
DDLogError("Uncaught exception's stack trace:\n\(exception.callStackSymbols)")
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window.makeKeyAndVisible()
window.rootViewController = mainSwinjectStoryboard.instantiateInitialViewController()
initLogging()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Logging configuration
private func initLogging() {
// log to Xcode console
DDTTYLogger.sharedInstance.logFormatter = LogFormatter()
DDLog.add(DDTTYLogger.sharedInstance)
// log to Apple System Logs
// DDASLLogger.sharedInstance.logFormatter = LogFormatter()
// DDLog.add(DDASLLogger.sharedInstance)
}
}
// MARK: State restoration
extension AppDelegate {
func application(_: UIApplication, shouldSaveApplicationState _: NSCoder) -> Bool {
return true
}
func application(_: UIApplication, shouldRestoreApplicationState _: NSCoder) -> Bool {
return true
}
}
<file_sep>//
// String.swift
// ImageViewer
//
// Created by Admin on 5/31/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
extension String {
var fileName : String {
return NSURL(fileURLWithPath: self).deletingPathExtension?.lastPathComponent ?? ""
}
var fileExtension : String {
return NSURL(fileURLWithPath: self).pathExtension ?? ""
}
}
<file_sep>//
// ImageCollectionViewCell.swift
// ImageViewer
//
// Created by Admin on 6/2/18.
// Copyright © 2018 Admin. All rights reserved.
//
import UIKit
class ImageCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var authorOutlet: UILabel!
@IBOutlet weak var titleOutlet: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
}
<file_sep>//
// StoryDatabase.swift
// ImageViewer
//
// Created by Admin on 5/31/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
import SQLite
class StoryDatabase {
static let shared = StoryDatabase()
static let NAME = "temp_StoryDatabase"
static let VERSION = 1
var db: Connection!
init() {
do {
// TODO: need a helper function to reload database dynamically based on selected story
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let tempDb = documentsDirectory.appendingPathComponent("tmp.sqlite")
if !FileManager.default.fileExists(atPath: tempDb.path) {
let dbURL = Bundle.main.url(forResource: "img_vwr_db", withExtension: "sqlite")
try FileManager.default.copyItem(at: dbURL!, to: tempDb)
}
db = try Connection(tempDb.absoluteString)
} catch {
print("Error \(error) occurred while trying to load SQLite database for story")
fatalError()
}
}
}
<file_sep>//
// MainViewController+ImageSlide.swift
// ImageViewer
//
// Created by Admin on 5/31/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
import ImageSlideshow
import GradientView
import CocoaLumberjack
extension MainViewController {
override func viewDidLayoutSubviews() {
initGradient()
}
func initImageSlider() {
self.imageSlideOutlet.contentScaleMode = .scaleAspectFill
var imageSourceList = [ImageSource]()
for item in self.topImageList {
guard let imageSource = item.getImageSource() else {
DDLogError("Cannot get imageSource")
continue
}
imageSourceList.append(imageSource)
}
self.imageSlideOutlet.setImageInputs(imageSourceList)
self.authorLabelOutlet.text = self.topImageList.first?.author
self.imageTitleLabelOutlet.text = self.topImageList.first?.imageTitle
self.imageSlideOutlet.currentPageChanged = { page in
if let author = self.topImageList[page].author{
self.authorLabelOutlet.fadeTransition(0.8)
self.authorLabelOutlet.text = author
}
if let title = self.topImageList[page].imageTitle {
self.imageTitleLabelOutlet.fadeTransition(0.8)
self.imageTitleLabelOutlet.text = title
}
}
initImageSliderTap()
// imageSliderAutoPlay()
}
@objc func imageSliderTapped(tapGestureRecognizer: UITapGestureRecognizer){
let size = self.imageSlideOutlet.images.count
if size == 0 { return }
let current = self.imageSlideOutlet.currentPage
let inputSource = self.imageSlideOutlet.images[current]
let uiImageView = UIImageView()
inputSource.load(to: uiImageView) { (uiimage) in
guard let uiimage = uiimage else{
return
}
let configuration = ImageViewerConfiguration { config in
config.image = uiimage
}
// let appDelegate = UIApplication.shared.delegate as! AppDelegate
let imageViewController = ImageViewerController(configuration:configuration)// appDelegate.mainSwinjectStoryboard.instantiateViewController(withIdentifier: "ImageViewerController")
// as! ImageViewerController
// imageViewController.configuration = configuration
imageViewController.image_dbItem = self.topImageList[current]
self.present(imageViewController, animated: true)
}
}
func initImageSliderTap(){
let tapImageSlider_GestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageSliderTapped(tapGestureRecognizer:)))
imageSlideOutlet.isUserInteractionEnabled = true
imageSlideOutlet.addGestureRecognizer(tapImageSlider_GestureRecognizer)
}
func imageSliderAutoPlay(){
Timer.scheduledTimer(withTimeInterval: 3, repeats: true, block: { _ in
self.imageSilderUpdate()
})
}
private func imageSilderUpdate(){
let size = self.imageSlideOutlet.images.count
if size == 0 { return }
let current = self.imageSlideOutlet.currentPage
let newImageIndex = (current + 1) % size
self.imageSlideOutlet.setCurrentPage(newImageIndex, animated: true)
}
func initGradient() {
imageGradientTopOutlet.drawTopGradient()
imageGradientBottomOutlet.drawBottomGradient()
}
}
<file_sep>//
// collection.swift
// ImageViewer
//
// Created by Admin on 5/31/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
import SQLite
class Collection {
var idCollection: Int64
var collectionName: String!
init(withRow row_item: Row) {
idCollection = row_item[Collection_Table.idCollection]
collectionName = row_item[Collection_Table.collectionName]
}
init(withMergedRow row_item: Row) {
idCollection = row_item[Collection_Table.Collection[Collection_Table.idCollection]]
collectionName = row_item[Collection_Table.Collection[Collection_Table.collectionName]]
}
var debug :String {
return "\(idCollection) \(collectionName)"
}
}
class Collection_Table {
static let Collection = Table("collection")
static let idCollection = Expression<Int64>("idCollection")
static let collectionName = Expression<String?>("collectionName")
}
func tester_Collection_Table() {
do {
let dd = try StoryDatabase.shared.db.prepare(Collection_Table.Collection)
for ddItem in dd {
let dde = Collection(withRow: ddItem)
print("dde: \(dde.debug)")
}
} catch {
print("\(error)")
}
}
<file_sep>//
// ImageViewModel.swift
// ImageViewer
//
// Created by Admin on 6/6/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
class ImageViewModel {
var databaseService = DatabaseService ()
func isFavoriteImage(_ image:Image) -> Bool{
return databaseService.isFavoriteImage(image)
}
}
<file_sep>//
// Assets.swift
// ImageViewer
//
// Created by Admin on 6/6/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
import RxSwift
import CocoaLumberjack
class Assets {
static let shared = Assets()
let databaseService = DatabaseService()
let updated: BehaviorSubject<Bool?> = BehaviorSubject<Bool?>(value: nil)
var topImageList:[Image]!
var imageSet:[[Image]]!
// var favoriteImageList:[Image]!
func refresh() -> Bool {
DispatchQueue.global(qos: .background).async {
// return Completable.create { completable in
guard let favoritesImageList = self.databaseService.getFavoritesImageList() else {
if Assets.shared.imageSet.count == 5 {
Assets.shared.imageSet.removeLast()
}
self.updated.onNext(false)
return
}
for item in favoritesImageList {
guard let _ = item.getUIImage() else {
DDLogError("Cannot get image")
continue
}
}
if Assets.shared.imageSet.count == 5 {
Assets.shared.imageSet[4] = favoritesImageList
} else if Assets.shared.imageSet.count == 4 {
Assets.shared.imageSet.append( favoritesImageList )
}else{
fatalError()
}
// completable(.completed)
self.updated.onNext(true)
// return Disposables.create()
}
// }
return true
}
}
<file_sep>//
// Image.swift
// ImageViewer
//
// Created by Admin on 5/31/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
import UIKit
import SQLite
import CocoaLumberjack
import ImageSlideshow
class Image {
var idImage: Int64
var idAuthor: Int64
var author: String!
var imageTitle: String!
var wImg: Int!
var hImg: Int!
var wImgThumb: Int!
var hImgThumb: Int!
var imageFileName: String!
var imageThumbFileName: String!
// [MARK] temp variable for ui update
var uiImage:UIImage!
var imageSource:ImageSource!
// [MARK] temp variable for ui update -- end
init(withRow row_item: Row) {
idImage = row_item[Image_Table.idImage]
idAuthor = row_item[Image_Table.idAuthor]
author = row_item[Image_Table.author]
imageTitle = row_item[Image_Table.imageTitle]
wImg = row_item[Image_Table.wImg]
hImg = row_item[Image_Table.hImg]
wImgThumb = row_item[Image_Table.wImgThumb]
hImgThumb = row_item[Image_Table.hImgThumb]
imageFileName = row_item[Image_Table.imageFileName]
imageThumbFileName = row_item[Image_Table.imageThumbFileName]
}
init(withMergedRow row_item: Row) {
idImage = row_item[Image_Table.Image[Image_Table.idImage]]
idAuthor = row_item[Image_Table.Image[Image_Table.idAuthor]]
author = row_item[Image_Table.Image[Image_Table.author]]
imageTitle = row_item[Image_Table.Image[Image_Table.imageTitle]]
wImg = row_item[Image_Table.Image[Image_Table.wImg]]
hImg = row_item[Image_Table.Image[Image_Table.hImg]]
wImgThumb = row_item[Image_Table.Image[Image_Table.wImgThumb]]
hImgThumb = row_item[Image_Table.Image[Image_Table.hImgThumb]]
imageFileName = row_item[Image_Table.Image[Image_Table.imageFileName]]
imageThumbFileName = row_item[Image_Table.Image[Image_Table.imageThumbFileName]]
}
func getUIImage() -> UIImage! {
if self.uiImage == nil {
guard var filename = self.imageFileName else{
return nil
}
guard let uiImage = UIImage(named: filename, in: Bundle(for: type(of: self)), compatibleWith: nil) else{
DDLogError("uiImage else")
return nil
}
self.uiImage = uiImage
return self.uiImage
}
return self.uiImage
}
func getImageSource() -> ImageSource!{
guard let ui_image = getUIImage() else{
return nil
}
return ImageSource(image:ui_image)
}
var debug :String {
return "\(idImage) \(author) \(wImg) \(imageFileName)"
}
}
class Image_Table {
static let Image = Table("image")
static let idImage = Expression<Int64>("idImage")
static let idAuthor = Expression<Int64>("idAuthor")
static let author = Expression<String?>("author")
static let imageTitle = Expression<String?>("imageTitle")
static let wImg = Expression<Int>("wImg")
static let hImg = Expression<Int>("hImg")
static let wImgThumb = Expression<Int>("wImgThumb")
static let hImgThumb = Expression<Int>("hImgThumb")
static let imageFileName = Expression<String?>("imageFileName")
static let imageThumbFileName = Expression<String?>("imageThumbFileName")
}
func tester_Image_Table() {
do {
let dd = try StoryDatabase.shared.db.prepare(Image_Table.Image)
for ddItem in dd {
let dde = Image(withRow: ddItem)
print("dde: \(dde.debug)")
}
} catch {
print("\(error)")
}
}
<file_sep>//
// ImageTableViewCell.swift
// ImageViewer
//
// Created by Admin on 6/6/18.
// Copyright © 2018 Admin. All rights reserved.
//
import UIKit
class ImageTableViewCell: UITableViewCell {
weak var viewController:UIViewController!
@IBOutlet weak var titleLabelOutlet: UILabel!
@IBOutlet weak var collectionViewOutlet: UICollectionView!
var imageList:[Image]!{
didSet {
collectionViewOutlet.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
initCollectionView()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>//
// MainViewController.swift
// ImageViewer
//
// Created by Admin on 5/31/18.
// Copyright © 2018 Admin. All rights reserved.
//
import UIKit
import ImageSlideshow
import GradientView
import RxSwift
class MainViewController: UIViewController {
// MARK: menu image outlet
@IBOutlet weak var menuImageOutlet: UIImageView!
// MARK: image slider outlet
@IBOutlet weak var imageSlideOutlet: ImageSlideshow!
@IBOutlet weak var imageGradientTopOutlet: UIView!
@IBOutlet weak var imageGradientBottomOutlet: UIView!
@IBOutlet weak var authorLabelOutlet: UILabel!
@IBOutlet weak var imageTitleLabelOutlet: UILabel!
// MARK: table view outlet
@IBOutlet weak var tableViewOutlet: UITableView!
// MARK: other
var viewModel : MainViewModel!
var topImageList:[Image]!
var imageSet:[[Image]]!
override func viewDidLoad() {
super.viewDidLoad()
initMenu()
initViewModel()
initImageSlider()
initTableView()
}
@objc func menuImageTapped(tapGestureRecognizer: UITapGestureRecognizer){
if let revealVC = revealViewController() {
if UIDevice.current.userInterfaceIdiom == .pad {
revealVC.rearViewRevealWidth = 300
}else{
revealVC.rearViewRevealWidth = self.view.frame.width
}
revealVC.rearViewRevealOverdraw = 0
revealVC.revealToggle(animated: true)
view.addGestureRecognizer(revealVC.panGestureRecognizer())
view.addGestureRecognizer(revealVC.tapGestureRecognizer())
}
}
func initMenu(){
let tapMenuImage_GestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(menuImageTapped(tapGestureRecognizer:)))
menuImageOutlet.isUserInteractionEnabled = true
menuImageOutlet.addGestureRecognizer(tapMenuImage_GestureRecognizer)
}
func initViewModel() {
self.topImageList = Assets.shared.topImageList
self.imageSet = Assets.shared.imageSet
_ = Assets.shared.updated.asObservable()
.observeOn(MainScheduler.instance)
.subscribe(onNext: { containFavorite in
guard let _ = containFavorite else {
return
}
self.imageSet = Assets.shared.imageSet
self.tableViewOutlet.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
<file_sep>//
// SplashViewController.swift
// ImageViewer
//
// Created by Admin on 6/6/18.
// Copyright © 2018 Admin. All rights reserved.
//
import UIKit
import RxSwift
import CocoaLumberjack
import NVActivityIndicatorView
class SplashViewController: UIViewController {
@IBOutlet weak var loadingOutlet: NVActivityIndicatorView!
let disposeBag = DisposeBag()
var viewModel:SplashViewModel!
override func viewDidLoad() {
super.viewDidLoad()
initViewModel()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func initViewModel() {
viewModel.state
.observeOn(MainScheduler.instance)
.subscribe(onNext: { status in
switch status {
case .IDLE:
DDLogDebug("IDLE")
case .GETTING_CATALOG:
DDLogDebug("GETTING_CATALOG")
self.loadingOutlet.color = UIColor.white
self.loadingOutlet.startAnimating()
case .GETTING_CATALOG_ERROR:
DDLogError("GETTING_CATALOG_ERROR")
case .GETTING_CATALOG_SUCCESS:
DDLogDebug("GETTING_CATALOG_SUCCESS")
self.gotoMainPage()
}
}).disposed(by: disposeBag)
viewModel.initImageAsset()
}
func gotoMainPage(){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let catalogController = appDelegate.mainSwinjectStoryboard.instantiateViewController(withIdentifier: "vc_reveal")
as! SWRevealViewController
appDelegate.window.rootViewController = catalogController
}
}
<file_sep>//
// Image.swift
// ImageViewer
//
// Created by Admin on 5/31/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
import SQLite
class Image {
var idImage: Int64
var idAuthor: Int64
var author: String!
var imageTitle: String!
var wImg: Int!
var hImg: Int!
var wImgThumb: Int!
var hImgThumb: Int!
var imageFileName: String!
var imageThumbFileName: String!
init(withRow story_item: Row) {
idImage = story_item[Image_Table.idImage]
idAuthor = story_item[Image_Table.idAuthor]
author = story_item[Image_Table.author]
imageTitle = story_item[Image_Table.imageTitle]
wImg = story_item[Image_Table.wImg]
hImg = story_item[Image_Table.hImg]
wImgThumb = story_item[Image_Table.wImgThumb]
hImgThumb = story_item[Image_Table.hImgThumb]
imageFileName = story_item[Image_Table.imageFileName]
imageThumbFileName = story_item[Image_Table.imageThumbFileName]
}
init(withMergedRow story_item: Row) {
idImage = story_item[Image_Table.Image[Image_Table.idImage]]
idAuthor = story_item[Image_Table.Image[Image_Table.idAuthor]]
author = story_item[Image_Table.Image[Image_Table.author]]
imageTitle = story_item[Image_Table.Image[Image_Table.imageTitle]]
wImg = story_item[Image_Table.Image[Image_Table.wImg]]
hImg = story_item[Image_Table.Image[Image_Table.hImg]]
wImgThumb = story_item[Image_Table.Image[Image_Table.wImgThumb]]
hImgThumb = story_item[Image_Table.Image[Image_Table.hImgThumb]]
imageFileName = story_item[Image_Table.Image[Image_Table.imageFileName]]
imageThumbFileName = story_item[Image_Table.Image[Image_Table.imageThumbFileName]]
}
}
class Image_Table {
static let Image = Table("image")
static let idImage = Expression<Int64>("idImage")
static let idAuthor = Expression<Int64>("idAuthor")
static let author = Expression<String?>("author")
static let imageTitle = Expression<String?>("imageTitle")
static let wImg = Expression<Int>("wImg")
static let hImg = Expression<Int>("hImg")
static let wImgThumb = Expression<Int>("wImgThumb")
static let hImgThumb = Expression<Int>("hImgThumb")
static let imageFileName = Expression<String?>("imageFileName")
static let imageThumbFileName = Expression<String?>("imageThumbFileName")
}
func tester1_Image_Table() {
do {
let dd = try StoryDatabase.shared.db.prepare(Image_Table.Image)
for ddItem in dd {
let dde = Image(withRow: ddItem)
print("dde: \(dde)")
}
} catch {
print("\(error)")
}
}
<file_sep>//
// MainViewController+tableview.swift
// ImageViewer
//
// Created by Admin on 6/6/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
import UIKit
extension MainViewController : UITableViewDataSource, UITableViewDelegate {
func initTableView(){
self.tableViewOutlet.dataSource = self
self.tableViewOutlet.delegate = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.imageSet.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if UIDevice.current.userInterfaceIdiom == .pad {
return 340
} else{
return 50.5 + CGFloat(280 * self.imageSet[indexPath.row].count)
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ImageTableViewCell", for: indexPath) as! ImageTableViewCell
switch indexPath.row {
case 0:
cell.titleLabelOutlet.text = "Special collection, 1997-1998"
break
case 1:
cell.titleLabelOutlet.text = "Special collection, 1999-2000"
break
case 2:
cell.titleLabelOutlet.text = "Special collection, 2000-2001"
break
case 3:
cell.titleLabelOutlet.text = "Special collection, 2001-2002"
break
case 4:
cell.titleLabelOutlet.text = "Favorites"
break
default:break
}
cell.viewController = self
cell.imageList = self.imageSet[indexPath.row]
return cell
}
}
<file_sep>//
// DatabaseService.swift
// ImageViewer
//
// Created by Admin on 5/31/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
import SQLite
class DatabaseService {
enum CollectionName:Int64 {
case TopSilder = 0
case Favorites = 1
case SpecialCollection1997_1998 = 20001
case SpecialCollection1999_2000 = 20002
case SpecialCollection2000_2001 = 20003
case SpecialCollection2001_2002 = 20004
}
let collectionImageService = CollectionImageService()
let imageService = ImageService()
func getTopImageList() -> [Image]!{
guard let collectionImageList = collectionImageService.getCollectionImageList(byId: CollectionName.TopSilder.rawValue) else{
return nil
}
var list_image = [Image]()
for item in collectionImageList {
guard let image = imageService.getImage(byId: item.idImage) else{
continue
}
list_image.append(image)
}
return list_image
}
func getFavoritesImageList() -> [Image]!{
guard let collectionImageList = collectionImageService.getCollectionImageList(byId: CollectionName.Favorites.rawValue) else{
return nil
}
if collectionImageList.count == 0 {
return nil
}
var list_image = [Image]()
for item in collectionImageList {
guard let image = imageService.getImage(byId: item.idImage) else{
continue
}
list_image.append(image)
}
return list_image
}
private func getImageList(byId collectionId:Int64)->[Image]!{
guard let collectionImageList = collectionImageService.getCollectionImageList(byId: collectionId) else{
return nil
}
var list_image = [Image]()
for item in collectionImageList {
guard let image = imageService.getImage(byId: item.idImage) else{
continue
}
list_image.append(image)
}
return list_image
}
func getSpecialImageList() -> [[Image]]{
var imageSet = [[Image]]()
if let image1 = getImageList(byId:CollectionName.SpecialCollection1997_1998.rawValue) {
imageSet.append(image1)
}
if let image2 = getImageList(byId:CollectionName.SpecialCollection1999_2000.rawValue) {
imageSet.append(image2)
}
if let image3 = getImageList(byId:CollectionName.SpecialCollection2000_2001.rawValue) {
imageSet.append(image3)
}
if let image4 = getImageList(byId:CollectionName.SpecialCollection2001_2002.rawValue) {
imageSet.append(image4)
}
return imageSet
}
func isFavoriteImage(_ image:Image) -> Bool {
guard let collectionImageList = collectionImageService.getCollectionImageList(byId: CollectionName.Favorites.rawValue) else{
return false
}
for item in collectionImageList {
if item.idImage == image.idImage {
return true
}
}
return false
}
func changeFavoriteImage(_ image:Image, _ checked:Bool){
if checked {
if isFavoriteImage(image) {
return
}
collectionImageService.addCollectionImage(id: CollectionName.Favorites.rawValue, idImage: image.idImage)
} else{
if !isFavoriteImage(image) {
return
}
collectionImageService.removeCollectionImage(id: CollectionName.Favorites.rawValue, idImage: image.idImage)
}
}
}
<file_sep>//
// ImageDescriptionTableViewController.swift
// ImageViewer
//
// Created by Admin on 6/6/18.
// Copyright © 2018 Admin. All rights reserved.
//
import UIKit
class ImageDescriptionTableViewController: UITableViewController {
var image_dbItem:Image!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.backgroundColor = .clear
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.row {
case 0: return 0
case 1: return 50
case 2: return self.view.frame.height - 50
// case 3: return self.view.frame.height - 50 - 500
default: return 60
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 3
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ImageDescriptionTableViewCell", for: indexPath) as! ImageDescriptionTableViewCell
switch indexPath.row {
case 0: cell.layer.backgroundColor = UIColor.red.withAlphaComponent(0.1).cgColor
// cell.layer.opacity = 0.01
// UIColor.clear.cgColor
case 1: cell.labelOutlet.text = image_dbItem.author
case 2: cell.labelOutlet.text = image_dbItem.imageTitle
default: break
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
self.dismiss(animated: true, completion: nil)
}
}
}
<file_sep>//
// MainViewModel.swift
// ImageViewer
//
// Created by Admin on 5/31/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
class MainViewModel {
}
| 5bedcaaef581d365097e82c02ecf40e073b43bb2 | [
"Swift",
"Ruby"
] | 29 | Swift | assassins719/imagegallery | 21c99581bdac3ac94afd32a815fdaca1f317f2dd | d646d4511626e8f3e2942b3e11c905f2be774f0d |
refs/heads/master | <repo_name>deepcrawler/TriangleTypeDetector<file_sep>/src/test/equilateralTriangleTest.java
package test;
import org.junit.Test;
import triangle.triangleType;
public class equilateralTriangleTest extends baseTriangleTest {
@Test
public void equilateralTriangle_Random() {
int min=1;
int max=100;
for (int i = min; i <=max ; i++) {
int randomNum = getRandomInt(min, max);
checkTriangle(randomNum, randomNum, randomNum,triangleType.equilateral);
}
}
}
<file_sep>/src/triangle/triangleDetector.java
package triangle;
public class triangleDetector implements ItriangleDetector{
public triangleType detect(int a, int b, int c)
{
if (a <= Math.abs((long)b - c) || a >= (long)b + c)//I convert int to long to handle Overflow issues of int type
return triangleType.invalid;
else if (a == b && b == c)
return triangleType.equilateral;
else if (a == b || b == c || a == c)
return triangleType.isosceles;
else
return triangleType.scalene;
}
}
<file_sep>/README.md
**TriangleDetector**
For a valid triangle with length of sides a, b and c, three equation must be passed:
a < b + c
c < a + b
b < c + a
We can simplify above equations as the following:
|a - b | < c < a + b
If we consider 8 byte integer for storing length of triangle sides, when one of the side has a length equal to 31 ^ 2, memory overflow will be happen. For guarding from this situation we should rewrite equation as the following:
|(long)a - b| < c < (long)a + c
So, with casting a side length to long (16 byte Integer), memory overflow will never happen.
As we know, zero or negative values are not acceptable values for triangle sides, which As you notice, the above equation be able to filer these values.
**Simple IOC (Inversion of Control Container)**
Triangle Detector is a sample which may be extend to broader problems, I wrote Simple IOC for showing this reality that this project could be used as a scalable and larger starter kit for larger problem contexts.
In general, IOC help us to distinguish and separate business declaration from business implementation.
So, with this architecture, we can simplify replacing a current business implementation with other implementations.
For seeing how to use Simple IOC, please see the usage of ItriangleDetector in the code.
Simple IOC only support Scoped Life time and a scope will be available with running the beginScope method from iocContainer class.
The output of beginScope is an instance of ServiceProvider class.
In fact, ServiceProvider store the created instances of requested of interfaces by code.
ServiceProvider implements AutoClosable interface so that by the end of a scope, all related used resource can be freed.
Due to use Scoped lift time and ConcurrentHashMap data structure, Parallel usage of Simple IOC is possible and it is definitely a major advantage for using it.
**triangleApp**
I separated the context domain of Triangle Detector by implementing triangleApp class.
Within this class, SimpleIOC will be initialized and we can get an instance of ServiceProvider by calling beginScope() method.
**Triangle Detector Tests**
Five test suite defined as the five test class which all of them inherited from baseTriangletest:
- **baseTrianglTest**: it is an abstract class which include before and after codes that must run in each test method ( before and after it). Please see before and after annotations in this class. Also, it has some common methods for triangle detector inherited test classes.
- **boundariesTriangleTest**: The tests in this class have responsibility for checking boundaries situations. For example when a side have 2^31 value for length or zero value.
- **equilateralTriangleTest**: The tests in this class, have responsibility for checking the correctness of the Triangle Detector algorithm for identifying equilateral triangles.
- **isoscelesTriangleTest**: The tests in this class, have responsibility for checking the correctness of the Triangle Detector algorithm for identifying isosceles triangles.
- **scaleneTriangleTest**: The tests in this class, have responsibility for checking the correctness of the Triangle Detector algorithm for identifying scalene triangles.
- **invalidTriangleTest**: The tests in this class, have responsibility for checking the correctness of the Triangle Detector algorithm for identifying invalid triangles.
- **triangleTestPrimer**: It bundles all the test classes which can run by JUnitCore.runclasses method of Junit 4.0 framework.
**How to use from Triangle Detector:**
try(var scope=triangleApp.beginScope()){
ItriangleDetector detector= scope.getService(ItriangleDetector.class);
var res=detector.detect(3,5,7);
System.out.println("detected Triangle Type is:"+res);
}
catch(Exception ex){
}
<file_sep>/src/triangle/ItriangleDetector.java
package triangle;
public interface ItriangleDetector {
triangleType detect(int a, int b, int c);
}
<file_sep>/src/test/baseTriangleTest.java
package test;
import app.triangleApp;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import simpleioc.serviceProvider;
import triangle.ItriangleDetector;
import triangle.triangleType;
import java.util.concurrent.ThreadLocalRandom;
public abstract class baseTriangleTest {
serviceProvider scope=null;
@Before
public void BeforeTest()
{
scope= triangleApp.beginScope();
}
@After
public void AfterTest()
{
try {
if (scope != null)
scope.close();
}
catch (Exception ex)
{
System.out.println("Exception:" +ex.getMessage());
ex.printStackTrace();
}
}
protected void checkTriangle(int a, int b, int c, triangleType expectedtt){
var res = getTriangleDetector().detect(a, b, c);
printTriangle(a, b, c, res);
Assert.assertTrue(res == expectedtt);
}
protected int getRandomInt(int min, int max){
return ThreadLocalRandom.current().nextInt(min, max + 1);
}
private void printTriangle(int a, int b, int c, triangleType tt){
System.out.printf("Run triangle detctor with %d,%d,%d sides, detected triangle type is %s %n",a,b,c,tt);
}
private ItriangleDetector getTriangleDetector(){
try {
return scope.getService(ItriangleDetector.class);
} catch (Exception e) {
System.out.println("Exception:" +e.getMessage());
e.printStackTrace();
return null;
}
}
}
<file_sep>/src/test/invalidTriangleTest.java
package test;
import org.junit.Test;
import triangle.triangleType;
public class invalidTriangleTest extends baseTriangleTest {
@Test
public void invalidTriangle_LittleSide() {
int a=50;
int b=30;
for(int c=1;c<=a-b;c++) {
checkTriangle(a, b, c,triangleType.invalid);
}
}
@Test
public void invalidTriangle_LargeSide() {
int a=50;
int b=30;
for(int c=a+b;c<=(a+b)+ 10 ;c++) {
checkTriangle(a, b, c,triangleType.invalid);
}
}
@Test
public void invalidTriangle_NegativeOrZeroSide() {
int a=50;
int b=30;
for(int c=0;c>=(a-b)- b ;c--) {
checkTriangle(a, b, c,triangleType.invalid);
}
}
}
<file_sep>/src/simpleioc/iocContainer.java
package simpleioc;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public class iocContainer {
private ConcurrentHashMap<Class, Class> IOCStore = null;
private ConcurrentHashMap<UUID, serviceProvider> IOCColl = null;
static iocContainer instance = null;
static Object locker = new Object();
public static iocContainer getInstance()
{
synchronized (locker)
{
if (instance == null)
instance = new iocContainer();
return instance;
}
}
public iocContainer()
{
IOCStore = new ConcurrentHashMap<Class, Class>();
IOCColl = new ConcurrentHashMap<UUID, serviceProvider>();
}
public Class getImpClass(Class t)
{
return IOCStore.get(t);
}
public void register(Class tint,Class timp)
{
IOCStore.put(tint,timp);
}
public serviceProvider beginScope()
{
UUID guid = UUID.randomUUID();
var sp = new serviceProvider(guid, this);
IOCColl.putIfAbsent(guid, sp);
return sp;
}
public void removeScope(UUID guid)
{
serviceProvider ignore;
IOCColl.remove(guid);
}
}
| a336b69d71bf8d0c2cf1e5304f5affd7d4210f0f | [
"Markdown",
"Java"
] | 7 | Java | deepcrawler/TriangleTypeDetector | f6ca5930bb040b86f53c742196e20b2aa633f8b4 | ab4d690b5b92fa7d09f883e778f3adda2f055084 |
refs/heads/master | <file_sep>package main
import (
"fmt"
//"log"
"net"
"os"
"os/exec"
"strconv"
"time"
)
const port = "20008"
const localIP = "172.16.31.10"
const broadcastIP = "172.16.17.32"
func main() {
/* err := cmd.Start()
if err != nil {
log.Fatal(err)
}
log.Printf("Waiting for command to finish...")
err = cmd.Wait()
log.Printf("Command finished with error: %v", err)
*/
iterChan := make(chan string)
quitServer := make(chan int, 2)
quitServer1 := make(chan int)
go server(quitServer, iterChan)
go stimer(quitServer, quitServer1, iterChan)
last_value := <-quitServer1
go client(last_value)
time.Sleep(10 * time.Second)
}
func stimer(quitServer, quitServer1 chan int, iterChan chan string) {
var last_value int
cmd := exec.Command("gnome-terminal", "-x", "sh", "-c", "go run master-backup.go %d", strconv.Itoa(last_value))
last_value = 0
if len(os.Args) > 1 {
last_value, _ = strconv.Atoi(os.Args[1])
fmt.Printf("Initiated with value = %d \n", last_value)
}
for {
timer := time.NewTimer(time.Second * 4)
select {
case <-timer.C:
quitServer <- 1
quitServer1 <- last_value
fmt.Println("new Master1")
cmd.Run()
case cur_value_string := <-iterChan:
cur_value, _ := strconv.Atoi(cur_value_string)
if (cur_value - 1) != (last_value) {
quitServer <- 1
quitServer1 <- last_value
fmt.Println("new Master2")
cmd.Run()
} else {
last_value = cur_value
}
//fmt.Println("En iterasjon i stimer")
}
}
}
func CheckError(err error) {
if err != nil {
fmt.Println("Error: ", err)
}
}
func client(last_value int) {
BroadcastAddr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(broadcastIP, port))
CheckError(err)
LocalAddr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(localIP, port))
CheckError(err)
Conn, err := net.DialUDP("udp", LocalAddr, BroadcastAddr)
CheckError(err)
defer Conn.Close()
i := last_value
for {
fmt.Printf("Sent %d \n", i)
msg := strconv.Itoa(i)
i++
buf := []byte(msg)
_, err := Conn.Write(buf)
if err != nil {
fmt.Println(msg, err)
}
time.Sleep(time.Second * 1)
}
}
func server(quitServer chan int, iterChan chan string) {
BroadcastAddr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(broadcastIP, port))
CheckError(err)
BroadcastConn, err := net.ListenUDP("udp", BroadcastAddr)
CheckError(err)
defer BroadcastConn.Close()
for {
select {
case <-quitServer:
return
default:
buff := make([]byte, 1024)
n, addr, err := BroadcastConn.ReadFromUDP(buff)
fmt.Println("Received ", string(buff[0:n]), " from ", addr)
val_recv := string(buff[0:n])
iterChan <- val_recv
time.Sleep(500 * time.Millisecond)
if err != nil {
fmt.Println("Error: ", err)
}
}
}
}
<file_sep>package helpFunc
import(
"math"
def "config"
)
func Difference_abs(val1 ,val2 int) int{
return int(math.Abs(math.Abs(float64(val1))-math.Abs(float64(val2))))
}
func Order_dir(floor,button int)int{
if button == def.BtnDown{
return -floor
}else{
return floor
}
}<file_sep>package driver
/*
#cgo CFLAGS: -std=c11
#cgo LDFLAGS: -lpthread -lcomedi -lm
#include "elev.h"*/
import "C"
const (
BUTTON_CALL_UP = iota
BUTTON_CALL_DOWN
BUTTON_COMMAND
)
const N_floors int = int(C.N_FLOORS)
func Elev_init() {
C.elev_init()
}
func Set_motor_dir(dirn int) {
C.elev_set_motor_direction(C.elev_motor_direction_t(dirn))
}
func Set_button_lamp(button int, floor int, value int) {
C.elev_set_button_lamp(C.elev_button_type_t(button), C.int(floor), C.int(value))
}
func Set_floor_indicator(floor int) {
C.elev_set_floor_indicator(C.int(floor))
}
//value er litt dårlig navn
func Set_door_open_lamp(value int) {
C.elev_set_door_open_lamp(C.int(value))
}
func Set_stop_lamp(value int) {
C.elev_set_stop_lamp(C.int(value))
}
func Get_button_signal(button int, floor int) int {
return int(C.elev_get_button_signal(C.elev_button_type_t(button), C.int(floor)))
}
func Get_floor_sensor_signal() int {
return int(C.elev_get_floor_sensor_signal())
}
func Get_stop_signal() int {
return int(C.elev_get_stop_signal())
}
<file_sep>package elevRun
import (
def "config"
"driver"
//"fmt"
"helpFunc"
"math"
"queue"
"time"
)
func Elev_init(){
driver.Elev_init()
driver.Set_motor_dir(-1)
defer driver.Set_motor_dir(0)
queue.Get_backup_from_file()
for {
if driver.Get_floor_sensor_signal() != -1 {
return
}
}
}
func Run_elev(outgoingMsg chan def.Message) {
for {
floorSensor := driver.Get_floor_sensor_signal()
update_current_floor(floorSensor)
if at_top_or_bottom(floorSensor) {
def.CurDir = -def.CurDir
}
if (len(queue.Get_Orders()) > 0) && (floorSensor != -1) {
set_direction(queue.Get_Orders()[0],def.CurFloor)
if arrived_at_destination() {
//fmt.Printf("%sFloat cur floor = %v float orders[0] = %v %s \n", def.ColY, float64(floorSensor), math.Abs(float64(def.Orders[0])), def.ColN)
driver.Set_motor_dir(0)
if def.ImConnected{
send_complete_msg(queue.Get_Orders()[0],outgoingMsg)
}else{
turn_off_lights()
}
remove_first_element_in_orders_and_save()
//fmt.Printf("%sOrder to floor %d deleted, current floor = %d\n",def.ColB,queue.Get_Orders()[0],def.CurFloor)
driver.Set_button_lamp(def.BtnInside, def.CurFloor, 0)
open_close_door()
}
}
}
}
func turn_off_lights(){
if queue.Get_Orders()[0] < 0 {
driver.Set_button_lamp(def.BtnDown, def.CurFloor, 0)
} else {
driver.Set_button_lamp(def.BtnUp, def.CurFloor, 0)
}
}
func open_close_door(){
driver.Set_door_open_lamp(1)
time.Sleep(2 * time.Second)
driver.Set_door_open_lamp(0)
}
func remove_first_element_in_orders_and_save(){
queue.Set_Orders(append(queue.Get_Orders()[:0], queue.Get_Orders()[1:]...))
queue.Save_backup_to_file()
}
func set_direction(order,curFloor int){
//var dir float64
if (math.Abs(float64(order)) - float64(curFloor)) != 0 {
//difference divided with abs(difference) gives direction = -1 or 1
dir := (math.Abs(float64(order)) - float64(curFloor)) / (float64(helpFunc.Difference_abs(order, curFloor)))
driver.Set_motor_dir(int(dir))
def.CurDir = int(dir)
//fmt.Printf(def.ColY,"Current dir = %d \n",def.CurDir,def.ColN)
}
}
func arrived_at_destination()bool{
return def.CurFloor == int(math.Abs(float64(queue.Get_Orders()[0])))
}
func at_top_or_bottom(floorSensor int)bool{
return (floorSensor == 0) || (floorSensor == def.NumFloors-1)
}
func send_complete_msg(order int,outgoingMsg chan def.Message){
if order < 0 {
msg := def.Message{Category: def.CompleteOrder, Floor: def.CurFloor, Button: def.BtnDown, Cost: -1}
outgoingMsg <- msg
} else {
msg := def.Message{Category: def.CompleteOrder, Floor: def.CurFloor, Button: def.BtnUp, Cost: -1}
outgoingMsg <- msg
}
}
func update_current_floor(floorSensorSignal int){
if floorSensorSignal != -1 {
def.CurFloor = floorSensorSignal
driver.Set_floor_indicator(floorSensorSignal)
}
}
/*--------------------------------------------------------------------------------------*/
<file_sep>package queue
import (
def "config"
"log"
//"time"
"encoding/json"
"io/ioutil"
"os"
)
/*/--------------Dette legges der vi skal bruke det----------------
var ordrs = []int{-2, 2, -3, 2}
var listlist = []int{-1, 1, -1, 1}
var backupOrd queue.BackupQueue
var kokoko queue.BackupQueue
backupOrd.List = ordrs
kokoko.List = listlist
backupOrd.Save_to_file("orderBackup")
kokoko.Load_from_disk("orderBackup")
fmt.Printf("%v\n", kokoko.List)
*/
type backupQueue struct {
List []int
}
func Get_backup_from_file(){
var backup backupQueue
backup.load_from_file(def.BackupFileName)
Set_Orders(backup.List)
}
func Save_backup_to_file(){
var backup backupQueue
backup.List = Get_Orders()
backup.save_to_file(def.BackupFileName)
}
func (q *backupQueue) save_to_file(filename string) error {
data, err := json.Marshal(&q)
if err != nil {
log.Println(def.ColR, "json.Marshal() error: Failed to backup.", def.ColN)
return err
}
if err := ioutil.WriteFile(filename, data, 0644); err != nil {
log.Println(def.ColR, "ioutil.WriteFile() error: Failed to backup.", def.ColN)
return err
}
return nil
}
// loadFromDisk checks if a file of the given name is available on disk, and
// saves its contents to a queue if the file is present.
func (q *backupQueue) load_from_file(filename string) error {
if _, err := os.Stat(filename); err == nil {
log.Println(def.ColG, "Backup file found, processing...", def.ColN)
data, err := ioutil.ReadFile(filename)
if err != nil {
log.Println(def.ColR, "loadFromDisk() error: Failed to read file.", def.ColN)
}
if err := json.Unmarshal(data, q); err != nil {
log.Println(def.ColR, "loadFromDisk() error: Failed to Unmarshal.", def.ColN)
}
}
return nil
}
<file_sep>package handleOrders
import (
def"config"
"queue"
"driver"
"time"
"fmt"
"helpFunc"
"strconv"
)
type rcvCost struct {
cost int
elevAddr string
}
type rcvOrder struct {
floor int
button int
timer *time.Timer
}
var NumOfOnlineElevs int
func Handle_orders(outgoingMsg chan def.Message) {
var alreadyPushed [def.NumFloors][def.NumButtons]bool
for {
for buttontype := 0; buttontype < 3; buttontype++ {
for floor := 0; floor < def.NumFloors; floor++ {
if button_pushed(buttontype,floor) {
if !alreadyPushed[floor][buttontype] {
set_order_light(buttontype, floor)
handle_new_order(buttontype,floor,outgoingMsg)
}
alreadyPushed[floor][buttontype] = true
} else {
alreadyPushed[floor][buttontype] = false
}
}
}
}
}
func set_order_light(buttontype, floor int){
if !external_order(buttontype) {
driver.Set_button_lamp(buttontype, floor, 1)
}else if def.ImConnected{
driver.Set_button_lamp(buttontype, floor, 1)
}
}
func handle_new_order(buttontype,floor int,outgoingMsg chan def.Message){
if external_order(buttontype) && def.ImConnected {
msg := def.Message{Category: def.NewOrder, Floor: floor, Button: buttontype, Cost: -1}
outgoingMsg <- msg
} else if !external_order(buttontype){
//Internal orders: if the desired floor is under the elevator it is set as a order down
//fmt.Printf("Intern ordre mottat \n")
if floor == def.CurFloor && def.CurDir == 1{
queue.Set_Orders(queue.Update_orderlist(queue.Get_Orders(), -floor, false))
}else if floor < def.CurFloor{
queue.Set_Orders(queue.Update_orderlist(queue.Get_Orders(), -floor, false))
}else if floor == def.NumFloors-1 {
queue.Set_Orders(queue.Update_orderlist(queue.Get_Orders(), -floor, false))
}else{
queue.Set_Orders(queue.Update_orderlist(queue.Get_Orders(), floor, false))
}
queue.Save_backup_to_file()
}
}
func button_pushed(buttontype,floor int)bool{
return driver.Get_button_signal(buttontype, floor) == 1
}
func external_order(buttontype int)bool{
return buttontype == def.BtnUp || buttontype == def.BtnDown
}
//-----------------------------------------------------------------
func Assign_external_order(costMsg, outgoingMsg, orderIsCompleted chan def.Message) {
rcvList := make(map[rcvOrder][]rcvCost)
var notCompletedOrders []rcvOrder
var overtime = make(chan rcvOrder)
var orderNotHandled = make(chan rcvOrder)
//var backupOrderComplete = make(chan rcvOrder)
const notHandledTimeout = 7000 * def.NumFloors * time.Millisecond
const costTimeout = 1000 * time.Millisecond
for {
select {
case msg := <-costMsg:
newOrder := rcvOrder{floor: msg.Floor, button: msg.Button}
backupOrder := rcvOrder{floor: msg.Floor, button: msg.Button}
newCost := rcvCost{cost: msg.Cost, elevAddr: msg.Addr[12:15]}
// Checks if order allready is in rcvList
for oldOrder := range rcvList {
if (newOrder.floor == oldOrder.floor) && (newOrder.button == oldOrder.button) {
newOrder = oldOrder
}
}
// Adds the rcv cost to order in rcvList
if costList, exist := rcvList[newOrder]; exist {
if !cost_already_recieved(newCost,costList) {
rcvList[newOrder] = append(rcvList[newOrder], newCost)
}
} else {
newOrder.timer = time.NewTimer(costTimeout)
rcvList[newOrder] = []rcvCost{newCost}
go cost_timer(newOrder, overtime)
}
if all_costs_recieved(rcvList,newOrder) {
add_new_order(rcvList,newOrder)
delete(rcvList, newOrder)
newOrder.timer.Stop()
backupOrder.timer = time.NewTimer(notHandledTimeout)
notCompletedOrders = append(notCompletedOrders, backupOrder)
go handle_timer(backupOrder, orderNotHandled)
//go handle_backupOrder_complete(backupOrder, backupOrderComplete, orderIsCompleted)
}
case newOrder := <-overtime:
fmt.Print("Assign order timeout: Did not recieve all replies before timeout\n")
add_new_order(rcvList,newOrder)
delete(rcvList, newOrder)
case order := <-orderNotHandled:
fmt.Print("Order to floor %d was not handled in time, resending\n", order.floor )
order.timer.Stop()
if def.ImConnected{
msgs := def.Message{Category: def.NewOrder, Floor: order.floor, Button: order.button, Cost: -1}
outgoingMsg <- msgs
}
case orderMsg := <- orderIsCompleted:
fmt.Printf("BackupOrder sin timer er stoppet\n")
for index,order := range notCompletedOrders{
if orderMsg.Floor == order.floor && orderMsg.Button == order.button{
order.timer.Stop()
notCompletedOrders = append(notCompletedOrders[:index], notCompletedOrders[(index+1):]...)
}
}
}
}
}
func add_new_order(rcvList map[rcvOrder][]rcvCost, newOrder rcvOrder){
if this_elevator_has_the_lowest_cost(rcvList[newOrder]) {
fmt.Printf("%sNew order added to floor = %d with cost = %d\n%s",def.ColY,helpFunc.Order_dir(newOrder.floor,newOrder.button),queue.Cost(queue.Get_Orders(),helpFunc.Order_dir(newOrder.floor,newOrder.button)),def.ColN)
queue.Set_Orders(queue.Update_orderlist(queue.Get_Orders(), helpFunc.Order_dir(newOrder.floor, newOrder.button), false))
fmt.Printf("%sUpdated orders = %v\n%s\n",def.ColY,queue.Get_Orders(),def.ColN)
queue.Save_backup_to_file()
}
}
func all_costs_recieved(rcvList map[rcvOrder][]rcvCost,newOrder rcvOrder)bool{
return len(rcvList[newOrder]) == NumOfOnlineElevs
}
func cost_already_recieved(newCost rcvCost,costList []rcvCost)bool{
for _, adr := range costList {
if newCost.elevAddr == adr.elevAddr {
return true
}
}
return false
}
func cost_timer(newOrder rcvOrder, overtime chan<- rcvOrder) {
<-newOrder.timer.C
overtime <- newOrder
}
func handle_timer(order rcvOrder, orderNotHandled chan<- rcvOrder) {
<-order.timer.C
orderNotHandled <- order
}
func this_elevator_has_the_lowest_cost(listOfCosts []rcvCost) bool {
//fmt.Print("Is this the best elev?\n")
var bestCost = rcvCost{cost: 1000, elevAddr: "999"}
for _, costStruct := range listOfCosts {
//fmt.Printf("cost = %d addr %d\n", costStruct.cost, cS)
if costStruct.cost < bestCost.cost {
bestCost = costStruct
} else if costStruct.cost == bestCost.cost {
costStructAddr, _ := strconv.Atoi(costStruct.elevAddr)
bestCostAddr, _ := strconv.Atoi(bestCost.elevAddr)
// if equal cost: choose the minimum of the last three numbers in IP
if costStructAddr > bestCostAddr {
bestCost = costStruct
}
}
}
if bestCost.elevAddr == def.Laddr[12:15] {
return true
} else {
return false
}
}
<file_sep>package main
//export GOPATH=$HOME/Documents/MagAnd/Heismappe/
import (
def "config"
"driver"
"elevRun"
"fmt"
"helpFunc"
"network"
"queue"
//"strconv"
"time"
"handleOrders"
)
var onlineElevs = make(map[string]network.UdpConnection)
var outgoingMsg = make(chan def.Message, 10)
var incomingMsg = make(chan def.Message, 10)
var deadChan = make(chan network.UdpConnection)
var costMsg = make(chan def.Message, 10)
var orderIsCompleted = make(chan def.Message, 10)
var quitChan = make(chan int)
func main() {
elevRun.Elev_init()
go network.Init(outgoingMsg, incomingMsg)
go elevRun.Run_elev(outgoingMsg)
go handleOrders.Handle_orders(outgoingMsg)
go handleOrders.Assign_external_order(costMsg ,incomingMsg , orderIsCompleted)
go handle_msg(incomingMsg, outgoingMsg, costMsg, orderIsCompleted)
go Quit_program(quitChan)
<-quitChan
}
func handle_msg(incomingMsg, outgoingMsg, costMsg, orderIsCompleted chan def.Message) {
for {
msg := <-incomingMsg
const aliveTimeout = 2 * time.Second
switch msg.Category {
case def.Alive:
//if connection exists
if connection, exist := onlineElevs[msg.Addr]; exist{
connection.Timer.Reset(aliveTimeout)
} else {
add_new_connection(msg.Addr,aliveTimeout)
}
case def.NewOrder:
//fmt.Printf("%sNew external order recieved to floor %d %s \n", def.ColM, helpFunc.Order_dir(msg.Floor, msg.Button), def.ColN)
driver.Set_button_lamp(msg.Button, msg.Floor, 1)
costMsg := def.Message{Category: def.Cost, Floor: msg.Floor, Button: msg.Button, Cost: queue.Cost(queue.Get_Orders(), helpFunc.Order_dir(msg.Floor, msg.Button))}
outgoingMsg <- costMsg
case def.CompleteOrder:
driver.Set_button_lamp(msg.Button, msg.Floor, 0)
orderIsCompleted <- msg
case def.Cost:
//see assign_external_order
costMsg <- msg
}
}
}
func add_new_connection(addr string, aliveTimeout time.Duration){
newConnection := network.UdpConnection{addr, time.NewTimer(aliveTimeout)}
onlineElevs[addr] = newConnection
handleOrders.NumOfOnlineElevs = len(onlineElevs)
go connection_timer(&newConnection)
fmt.Printf("%sConnection to IP %s established!%s\n", def.ColG, addr[0:15], def.ColN)
}
func connection_timer(connection *network.UdpConnection) {
<-connection.Timer.C
deadChan<- *connection
}
//------------------------------------------------------------------
//-----------------------------------------------------------------
func chan_died(deadChan chan network.UdpConnection){
fmt.Printf("Elevator with IP:----- died\n")
connection := <- deadChan
fmt.Printf("Elevator with IP:%d died\n", connection.Addr)
}
func Quit_program(quit chan int) {
for {
time.Sleep(time.Second)
if driver.Get_stop_signal() == 1 {
driver.Set_motor_dir(0)
quit <- 1
}
}
}
<file_sep>package queue
import (
def "config"
"fmt"
"helpFunc"
//"math"
"sort"
"sync"
)
var mutex = &sync.Mutex{}
var orders []int
func Get_Orders()[]int{
mutex.Lock()
copyOrders := make([]int,len(orders))
copy(copyOrders[:],orders)
mutex.Unlock()
return copyOrders
}
func Set_Orders(newOrders []int){
mutex.Lock()
copyOrders := make([]int,len(newOrders))
copy(copyOrders[:],newOrders)
orders = copyOrders
mutex.Unlock()
//fmt.Printf("%sOrder list is updated to %v \t current floor = %d \t cur dir = %d%s\n", def.ColR, Get_Orders(),def.CurFloor,def.CurDir, def.ColN)
}
func append_and_sort_list(orderlist []int, newOrder int) []int {
newOrderlist := append(orderlist, newOrder)
copyOrderlist := make([]int,len(newOrderlist))
copy(copyOrderlist[:],newOrderlist)
sort.Ints(copyOrderlist)
return copyOrderlist
}
func Update_orderlist(orderlist []int, newOrder int, costfunction bool) []int {
//fmt.Printf("pre orders in append = %v \n", Get_Orders())
copyOrderlist := orderlist
if order_exists(copyOrderlist,newOrder){
fmt.Printf("Info from Update_orderlist: Order to floor %d already ordered \n", newOrder)
return copyOrderlist
}
tempOrderlist := append_and_sort_list(copyOrderlist, newOrder)
ordersDown := get_orders_down(tempOrderlist)
ordersUp := get_orders_up(tempOrderlist)
var newOrders []int
if def.CurDir >= 0{
for _,orderUp := range ordersUp{
if orderUp > def.CurFloor{
newOrders = append(newOrders,orderUp)
}else {
ordersDown = append(ordersDown,orderUp)
}
}
newOrders = append_list(newOrders,ordersDown)
}
if def.CurDir == -1{
for _,orderDown := range ordersDown{
if -orderDown < def.CurFloor{
newOrders = append(newOrders,orderDown)
}else {
ordersUp = append(ordersUp,orderDown)
}
}
newOrders = append_list(newOrders,ordersUp)
}
//fmt.Printf("newOrders = %v\n",newOrders)
return newOrders
}
func get_orders_up(orderlist []int)[]int{
var posOrders []int
for _,order := range orderlist{
if order >= 0 {
posOrders = append(posOrders, order)
}
}
return posOrders
}
func get_orders_down(orderlist []int)[]int{
var negOrders []int
for _,order := range orderlist{
if order < 0 {
negOrders = append(negOrders, order)
}
}
return negOrders
}
func append_list(temp1,temp2 []int)[]int{
i := 0
for i < len(temp2) {
temp1 = append(temp1, temp2[i])
i++
}
return temp1
}
func order_exists(copyOrderlist []int,newOrder int)bool{
for j := 0; j < len(copyOrderlist); j++ {
if copyOrderlist[j] == newOrder {
return true
}
}
return false
}
func Get_index(orderlist []int, new_order int) int {
orderlist_length := len(orderlist)
i := 0
for i < orderlist_length {
if orderlist[i] == new_order {
return i
}
i++
}
fmt.Print("Error in Get_index\n")
return -1
}
func Cost(orderlist []int, newOrder int) int {
new_orderlist := Update_orderlist(orderlist, newOrder, true)
index := Get_index(new_orderlist, newOrder)
//fmt.Print(index)
var cost = helpFunc.Difference_abs(def.CurFloor, newOrder)
if len(orderlist) > 0 {
cost = helpFunc.Difference_abs(def.CurFloor, orderlist[0])
for i := 0; i < index-1; i++ {
cost += helpFunc.Difference_abs(orderlist[i], orderlist[i+1])
}
}
return int(cost) + 2*len(Get_Orders())
}
| df989710104cac2a329da6b359c97a937c527322 | [
"Go"
] | 8 | Go | Aarskog/heisprosjekt | 8ce4b789c4b93ffe998beff934194956f64ff06e | 9ad3451bea18c571751ccc12804b5caee41b58b6 |
refs/heads/master | <repo_name>hawx/riviera-admin<file_sep>/actions/subscribe.go
package actions
import (
"errors"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"github.com/PuerkitoBio/goquery"
"golang.org/x/net/html/charset"
"hawx.me/code/riviera/feed"
"hawx.me/code/riviera/subscriptions/opml"
)
func Subscribe(opmlPath, page string) error {
feed, err := findFeed(page)
if err != nil {
return err
}
outline, err := opml.Load(opmlPath)
if err != nil {
return err
}
newfeed, err := getData(feed)
if err != nil {
return err
}
outline.Body.Outline = append(outline.Body.Outline, newfeed)
file, err := os.OpenFile(opmlPath, os.O_WRONLY|os.O_TRUNC, 0)
if err != nil {
return err
}
defer file.Close()
return outline.WriteTo(file)
}
func getData(feeduri string) (opml.Outline, error) {
resp, err := http.Get(feeduri)
if err != nil {
return opml.Outline{}, err
}
channels, err := feed.Parse(resp.Body, charset.NewReaderLabel)
resp.Body.Close()
if err != nil {
return opml.Outline{}, err
}
ch := channels[0]
websiteURL := ""
for _, link := range ch.Links {
if link.Rel != "self" {
websiteURL = link.Href
break
}
}
return opml.Outline{
Type: "rss",
Text: ch.Title,
XMLURL: feeduri,
HTMLURL: websiteURL,
Title: ch.Title,
Description: ch.Description,
}, nil
}
func findFeed(page string) (string, error) {
resp, err := http.Get(page)
if err != nil {
return "", err
}
contentType := resp.Header.Get("Content-Type")
if isFeedType(contentType) {
return page, nil
}
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return "", err
}
for _, node := range doc.Find("link").Nodes {
var rel, href, typ string
for _, a := range node.Attr {
switch a.Key {
case "rel":
rel = a.Val
case "href":
href = a.Val
case "type":
typ = a.Val
}
}
if rel == "alternate" && isFeedType(typ) {
if strings.HasPrefix(href, "/") {
u, err := url.Parse(page)
if err != nil {
return "", err
}
u.Path = href
return u.String(), nil
}
return href, nil
}
}
return "", errors.New("no feed found on page")
}
var contentTypes = []*regexp.Regexp{
regexp.MustCompile("^application/rss\\+xml"),
regexp.MustCompile("^application/atom\\+xml"),
regexp.MustCompile("^application/xml"),
regexp.MustCompile("^text/xml"),
}
func isFeedType(contentType string) bool {
for _, pat := range contentTypes {
if pat.Match([]byte(contentType)) {
return true
}
}
return false
}
<file_sep>/README.md
# riviera-admin
An admin panel for [riviera][].
- Lists feeds subscribed to
- Provides a bookmarklet to subscribe to the current page's feed
- Can unsubscribe from existing feeds
``` bash
$ go get hawx.me/code/riviera-admin
$ riviera-admin subscriptions.xml
...
```
Then visit <http://localhost:8081> and login.
See `riviera-admin --help` for the other options that will be required when
running properly.
[riviera]: https://github.com/hawx/riviera
<file_sep>/admin.go
package main
import (
"flag"
"fmt"
"log"
"net/http"
"github.com/BurntSushi/toml"
"hawx.me/code/indieauth"
"hawx.me/code/indieauth/sessions"
"hawx.me/code/mux"
"hawx.me/code/riviera-admin/handlers"
"hawx.me/code/serve"
)
const help = `Usage: riviera-admin [options] FILE
An admin panel for riviera.
--port <num> # Port to bind to (default: 8081)
--socket <path> # Serve using a unix socket instead
--settings <path> # Path to settings (default: ./settings.toml)
--help # Display help message
`
type Conf struct {
Secret string
URL string
PathPrefix string
Me string
}
func Log(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s", r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
func main() {
var (
settingsPath = flag.String("settings", "./settings.toml", "")
port = flag.String("port", "8081", "")
socket = flag.String("socket", "", "")
)
flag.Usage = func() { fmt.Println(help) }
flag.Parse()
if flag.NArg() == 0 {
fmt.Println(help)
return
}
opmlPath := flag.Arg(0)
var conf *Conf
if _, err := toml.DecodeFile(*settingsPath, &conf); err != nil {
log.Fatal("toml: ", err)
}
auth, err := indieauth.Authentication(conf.URL, conf.URL+"/callback")
if err != nil {
log.Fatal(err)
}
session, err := sessions.New(conf.Me, conf.Secret, auth)
if err != nil {
log.Fatal(err)
}
session.Root = conf.PathPrefix
http.Handle("/", mux.Method{
"GET": session.Choose(
handlers.List(opmlPath, conf.URL),
handlers.Login(conf.URL),
),
})
http.Handle("/subscribe", session.Shield(mux.Method{
"GET": handlers.Subscribe(opmlPath, conf.PathPrefix),
}))
http.Handle("/unsubscribe", session.Shield(mux.Method{
"GET": handlers.Unsubscribe(opmlPath, conf.PathPrefix),
}))
http.Handle("/sign-in", session.SignIn())
http.Handle("/callback", session.Callback())
http.Handle("/sign-out", session.SignOut())
serve.Serve(*port, *socket, Log(http.DefaultServeMux))
}
<file_sep>/handlers/unsubscribe.go
package handlers
import (
"log"
"net/http"
"hawx.me/code/riviera-admin/actions"
)
func Unsubscribe(opmlPath, pathPrefix string) http.Handler {
return &unsubscribeHandler{opmlPath, pathPrefix}
}
type unsubscribeHandler struct {
opmlPath string
pathPrefix string
}
func (h *unsubscribeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err := actions.Unsubscribe(h.opmlPath, r.FormValue("url"))
if err != nil {
log.Println(err)
return
}
http.Redirect(w, r, h.pathPrefix+"/", 301)
}
<file_sep>/handlers/login.go
package handlers
import (
"net/http"
"hawx.me/code/riviera-admin/views"
)
func Login(url string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "text/html")
views.Login.Execute(w, struct {
Url string
}{url})
})
}
<file_sep>/actions/unsubscribe.go
package actions
import (
"os"
"hawx.me/code/riviera/subscriptions/opml"
)
func Unsubscribe(opmlPath, page string) error {
outline, err := opml.Load(opmlPath)
if err != nil {
return err
}
idx := -1
for i, o := range outline.Body.Outline {
if o.XMLURL == page {
idx = i
break
}
}
if idx >= 0 {
outline.Body.Outline = append(outline.Body.Outline[:idx], outline.Body.Outline[idx+1:]...)
}
file, err := os.OpenFile(opmlPath, os.O_WRONLY|os.O_TRUNC, 0)
if err != nil {
return err
}
defer file.Close()
return outline.WriteTo(file)
}
<file_sep>/go.mod
module hawx.me/code/riviera-admin
require (
github.com/BurntSushi/toml v0.3.1 // indirect
github.com/PuerkitoBio/goquery v1.5.0
github.com/gorilla/sessions v1.1.3 // indirect
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd
hawx.me/code/indieauth v0.0.0-20190302165148-d51e58d05695 // indirect
hawx.me/code/mux v0.0.0-20171229202905-76b5c781b7be // indirect
hawx.me/code/riviera v0.0.0-20190302164641-eea832f851c3
)
<file_sep>/views/styles.go
package views
const styles = `
html, body {
margin: 0;
padding: 0;
}
body {
font: 100%/1.3 Verdana, sans-serif;
overflow-y: scroll;
}
.container {
max-width: 40rem;
margin: 1rem;
}
aside {
max-width: 40rem;
margin: 1rem 1.5rem;
}
.container:before, .container:after {
clear: both;
content: " ";
display: table;
}
a {
color: hsl(220, 51%, 44%);
}
a:hover {
color: hsl(208, 56%, 38%);
}
header {
margin: 0 1rem;
font-size: 1rem;
border-bottom: 1px solid #ddd;
}
header h1, header > a {
margin: 0;
padding: 1.3rem;
height: 1.3rem;
line-height: 1.3rem;
display: inline-block;
}
header h1 {
font-size: 1.5rem;
padding-left: 0;
margin-left: .5rem;
font-weight: bold;
align-self: flex-start;
}
header h1 a {
color: #000;
text-decoration: none;
}
.feeds {
width: auto;
list-style: none;
padding: 0;
margin: 0;
}
.feeds li {
border-bottom: 1px dotted #ddd;
width: auto;
}
.feeds li:last-child {
border-bottom: none;
}
li {
margin: 1.3rem 0;
padding: 0 .5rem;
position: relative;
}
li h1 {
font-size: 1.2rem;
}
li h1 a {
text-decoration: none;
}
li .buttons {
float: right;
position: relative;
top: -2.3rem;
opacity: 0;
background: white;
}
li:hover .buttons {
opacity: 1;
}
`
<file_sep>/handlers/subscribe.go
package handlers
import (
"log"
"net/http"
"hawx.me/code/riviera-admin/actions"
)
func Subscribe(opmlPath, pathPrefix string) http.Handler {
return &subscribeHandler{opmlPath, pathPrefix}
}
type subscribeHandler struct {
opmlPath string
pathPrefix string
}
func (h *subscribeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
url := r.FormValue("url")
err := actions.Subscribe(h.opmlPath, url)
if err != nil {
log.Println("subscribe:", err)
w.WriteHeader(500)
return
}
if r.FormValue("redirect") == "origin" {
http.Redirect(w, r, url, 301)
return
}
http.Redirect(w, r, h.pathPrefix+"/", 301)
}
<file_sep>/views/login.go
package views
import "html/template"
var Login, _ = template.New("login").Parse(login)
const login = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Riviera Admin</title>
<style>
body {
font: 16px/1.3em Helvetica;
width: 100%;
margin: 0;
padding: 0;
}
#cover {
top: 0;
left: 0;
z-index: 1000;
position: absolute;
height: 100%;
width: 100%;
background: rgba(0, 255, 255, .7);
display: block
padding: 0;
margin: 0;
}
#cover a {
position: relative;
display: block;
left: 50%;
top: 50%;
text-align: center;
width: 100px;
margin-left: -50px;
height: 50px;
line-height: 50px;
margin-top: -25px;
font-size: 16px;
font-weight: bold;
border: 1px solid;
}
</style>
</head>
<body>
<div id="cover">
<a href="{{.Url}}/sign-in" title="Sign-in">Sign-in</a>
</div>
</body>
</html>
`
<file_sep>/views/index.go
package views
import (
"html/template"
)
var Index, _ = template.New("index").Parse(index)
const index = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Riviera Admin</title>
<style>
` + styles + `
</style>
</head>
<body>
<header>
<h1>riviera-admin</h1>
<a href="javascript:location.href='{{.Url}}/subscribe?url='+encodeURIComponent(location.href)+'&redirect=origin;'">bookmarklet</a>
<a href="{{.Url}}/sign-out">sign-out</a>
</header>
<div class="container">
<ul class="feeds">
{{range .Feeds}}
<li>
<h1><a href="{{.WebsiteUrl}}">{{.FeedTitle}}</a></h1>
<p>{{.FeedDescription}}</p>
<div class="buttons">
<a href="{{.FeedUrl}}">feed</a>
<a href="{{$.Url}}/unsubscribe?url={{.FeedUrl}}">unsubscribe</a>
</div>
</li>
{{end}}
</ul>
</div>
</body>
</html>
`
<file_sep>/handlers/list.go
package handlers
import (
"log"
"net/http"
"sort"
"strings"
"hawx.me/code/riviera-admin/views"
"hawx.me/code/riviera/subscriptions/opml"
)
func List(opmlPath, url string) http.Handler {
return &listHandler{opmlPath, url}
}
type listHandler struct {
opmlPath string
url string
}
func (h *listHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
outline, err := opml.Load(h.opmlPath)
if err != nil {
log.Println("list", err)
w.WriteHeader(500)
return
}
var list feeds
for _, line := range outline.Body.Outline {
if line.Type == "rss" {
f := feed{
FeedUrl: line.XMLURL,
WebsiteUrl: line.HTMLURL,
FeedTitle: line.Title,
FeedDescription: line.Description,
}
if f.FeedTitle == "" {
f.FeedTitle = f.FeedUrl
}
list = append(list, f)
}
}
sort.Sort(list)
w.Header().Add("Content-Type", "text/html")
views.Index.Execute(w, struct {
Url string
Feeds []feed
}{h.url, list})
}
type feed struct {
FeedUrl string
WebsiteUrl string
FeedTitle string
FeedDescription string
}
type feeds []feed
func (fs feeds) Len() int { return len(fs) }
func (fs feeds) Swap(i, j int) { fs[i], fs[j] = fs[j], fs[i] }
func (fs feeds) Less(i, j int) bool {
return strings.ToLower(fs[i].FeedTitle) < strings.ToLower(fs[j].FeedTitle)
}
| 88cd4d7d5ec25c240ea5cf3f2a27b4c951931926 | [
"Markdown",
"Go Module",
"Go"
] | 12 | Go | hawx/riviera-admin | 638df4f640a7ab25922cc2290bcdc6f1305cfc63 | 66d7a8ae04de711f7945b3aaf29a569e795cb593 |
refs/heads/master | <repo_name>xiaoBiao/test<file_sep>/html/request.js
$(document).ready(function(){
$('#addParam').on('click',addParam);
$('#sendBtn').on('click',requestServer);
$('#paramList').on({click:deleteTR},'button');
});
function addParam(){
var tr = $('<tr><td><input type="text" ></td><td><input type="text" ></td><td><button>删除</button></td></tr>');
$('#paramList').append(tr);
};
function deleteTR(){
$(this).parent().parent().remove();
}
function requestServer(){
var param = {};
$('#paramList tr:gt(0)').each(function(index){
var inputArr = $(this).find('input');
param[inputArr[0].value] = inputArr[1].value;
});
var type = $('#requestType').val();
var url = $('#serverPath').val();
var xhr = new XMLHttpRequest();
xhr.open(type, url, true);
xhr.nreadystatechange = showResult;
xhr.send(param);
}
function showResult(){
if(this.readyState == 4){
console.log(this.responseText)
$('#result').text(this.responseText);
}
}<file_sep>/NodeJs/test.js
//test.js
var fs = require('fs');
fs.readFile('1.txt',function(err,data){
if(err){
console.log(err);
}else{
console.log(data);
}
});
console.log('End');/*
var EventEmitter = require('events').EventEmitter;
var event = new EventEmitter();
event.on('some_event', function() {
console.log('some_event occured.');
});
setTimeout(function() {
event.emit('some_event');
}, 1000);
var testM = require('./testM');
testM.setName('梁宏远');
testM.sayHello();
var a = 1;
var b = "World";
var c = function(x){
console.log("Hello"+x+a);
}
c(b);
process.stdin.resume();
process.stdin.on('data',function(data){
process.stdout.write('read from console: '+data.toString());
});
function doSomething(msg,callback){
process.nextTick(callback);
console.log('执行doSomething');
next(msg);
}
function next(msg){
console.log('我是next函数我输出了:'+msg);
}
doSomething('测试process.nextTick',function(){
console.log('我是callback');
console.log('process.platform = '+process.platform)
});*/
var util = require('util');
function Base(){
this.name = 'base';
this.base = 1991;
this.sayHello = function() {
console.log('Hello ' + this.name);
};
}
Base.prototype.showName = function(){
console.log(this.name);
}
function Sub() {
this.name = 'sub';
}
util.inherits(Sub, Base);
var objBase = new Base();
objBase.showName();
objBase.sayHello();
console.log(objBase);
for(var temp in objBase){
console.log(temp);
}
console.log('******util.inspect开始输出******');
console.log(util.inspect(objBase,true,null,true));
console.log('******util.inspect结束输出******');
var objSub = new Sub();
objSub.showName();
//objSub.sayHello();
console.log(objSub);<file_sep>/NodeJs/caculate.js
var tz_input1 = 500000; //目标金额
var tz_input2 = 1; //投资年限
var tz_input3 = 0.04; //每年通胀率
var tz_input4 = 0.03; //预期每年储蓄回报率
var tz_input5 = 450000; //现在储蓄
var tz_input6 = 2000; //每月储蓄
var tz_result1 = Math.pow(1 + tz_input3, tz_input2) * tz_input1; //预期目标金额
console.log('预期目标金额:' + tz_result1);
var tz_result2 = tz_input5 * Math.pow(1 + tz_input4, tz_input2) + tz_input6 * (1 - Math.pow((1 + tz_input4 / 12), 12 * tz_input2)) / (-tz_input4 / 12); //预期储蓄价值
tz_result2 = Math.round(tz_result2);
console.log('预期储蓄价值:' + tz_result2);
var tz_result3 = tz_result1 - tz_result2;
console.log(tz_result3);
//每月仍需多少
var tz_result4 = (tz_result1 - tz_input5 * Math.pow(1 + tz_input4, tz_input2)) * (-tz_input4 / 12) / (1 - Math.pow((1 + tz_input4 / 12), 12 * tz_input2));
tz_result4 = Math.round(tz_result4);
console.log(tz_result4 - tz_input6);
//教育储蓄相关
var jy_input1 = 16; //子女现在年龄
var jy_input2 = 18; //子女上大学年龄
var jy_input3 = 27; //完成大学年龄
var jy_input4 = 42000; //每年学费
var jy_input5 = 60000; //每年生活费
var jy_input6 = 0.04; //通货膨胀率
var jy_input7 = 0.01; //预期回报率
var jy_input8 = 450000; //现在储蓄
var jy_input9 = 2000; //每月储蓄
var temp = jy_input4 + jy_input5; //每年花费
var A1 = Math.pow(1 + jy_input6, jy_input3 - jy_input2) * (1 - Math.pow(jy_input6, jy_input3 - jy_input1)) / (1 - jy_input6);
//所需教育储备
var jy_result1 = temp*Math.pow(1 + jy_input6, jy_input2 - jy_input1) * (1 - Math.pow(1 + jy_input6, jy_input3 - jy_input2)) / (-jy_input6);
jy_result1 = Math.round(jy_result1);
console.log('******************************');
console.log('所需教育储备:' + jy_result1);
//预期教育储蓄
var jy_result2 = jy_input8 * Math.pow(1 + jy_input7, jy_input2 - jy_input1) + jy_input9 * (1 - Math.pow((1 + jy_input7 / 12), 12 * (jy_input2 - jy_input1))) / (-jy_input7 / 12); //预期教育储蓄
jy_result2 = Math.round(jy_result2);
console.log('预期教育储蓄:' + jy_result2);
console.log(jy_result1 - jy_result2);
var jy_result3 = (jy_result1 - jy_input8 * Math.pow(1 + jy_input7, jy_input2 - jy_input1)) * (-jy_input7 / 12) / (1 - Math.pow((1 + jy_input7 / 12), 12 * (jy_input2 - jy_input1)));
jy_result3 = Math.round(jy_result3 - jy_input9);
//jy_result3 = Math.pow(1 + jy_input7, jy_input2 - jy_input1) * jy_result3;
console.log('每月仍需:' + jy_result3);
//退休相关
var tx_input1 = 52; //当前年龄
var tx_input2 = 53; //预计退休年龄
var tx_input3 = 68; //终老年龄
var tx_input4 = 50000; //退休后每年支出
var tx_input5 = 0.052; //退休后回报率
var tx_input6 = 0.04; //通货膨胀率
var tx_input7 = 0.1; //预期回报率
var tx_input8 = 10000; //现在储蓄
var tx_input9 = 1000; //每月储蓄
var tx_result1 = Math.pow(1 + tx_input6, tx_input2 - tx_input1) * tx_input4;
tx_result1 = Math.round(tx_result1);
console.log('*******************以下为退休相关数据******************');
console.log('退休后每年支出:' + tx_result1);
var tx_result2 = tx_result1 * Math.pow(1 + tx_input6, tx_input3 - tx_input2) * (1 - Math.pow((1 + tx_input5) / (1 + tx_input6), tx_input3 - tx_input2)) / ((tx_input6 - tx_input5) * Math.pow(1 + tx_input5, tx_input3 - tx_input2 - 1));
tx_result2 = Math.round(tx_result2);
console.log('所需退休金额:' + tx_result2);
var tx_result3 = tx_result1*(1+tx_input5)*(1 - Math.pow((1+tx_input6)/(1+tx_input5),tx_input3 - tx_input2) )/ (tx_input5 - tx_input6)
console.log(tx_result3);<file_sep>/python/autoSign.py
#! /usr/bin/python3
import urllib.request
import http.cookiejar
import PyV8
account = [
{'usr':'','pwd':''},
]
#模拟的UA字符串
UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
jsfun = 'function callback1(data){if(data.code == 0) return 1;else return 0;}'
def getReq(url):
req = urllib.request.Request(url)
req.add_header('Referer',url)
req.add_header('User-Agent',UA)
req.add_header('Pragma','no-cache')
req.add_header('Accept','*/*')
return req
def checkLogin(resdata):
v8 = PyV8.JSContext()
v8.enter()
v8.eval(jsfun)
print(resdata)
print(v8.eval(resdata))
for data in account:
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
urllib.request.install_opener(opener)
url = 'http://my.37.com/api/login.php?callback=callback1&action=login&login_account='+data['usr']+'&password='+data['pwd']+'&ajax=0&remember_me=0&save_state=1<ype=1&_=1422949639949'
print('**************************************')
req = getReq(url)
res = urllib.request.urlopen(req)
resdata = res.read().decode('utf-8')
print(resdata)
url = 'http://shop.37.com/sign/index.php?action=get_my_sign&r=0.8673140476372918&callback=callback2&_=1422952518491'
req = getReq(url)
res = urllib.request.urlopen(req)
resdata = res.read().decode('utf-8')
print(resdata)
url = 'http://shop.37.com/sign/index.php?action=sign&r=0.12115631320202436&callback=callback3&_=1422952876821'
req = getReq(url)
res = urllib.request.urlopen(req)
resdata = res.read().decode('utf-8')
print(resdata)
print('**************************************')
#print(resdata)
<file_sep>/NodeJs/search.js
function search(arr,number,lower,upper){
if(lower == upper){
console.log('序号为:'+upper)
return upper
}else{
var middle = Math.floor((lower+upper)/2)
console.log('下限为:'+lower+'****中间数为:'+middle+'****上限为:'+upper)
if(number > arr[middle]){
return search(arr, number, middle+1, upper);
}else{
return search(arr, number, lower, middle)
}
}
}
var arr1 = [3,5,7,9,23,59,67]
search(arr1, 59, 0, 6)<file_sep>/NodeJs/request.js
var http = require('http');
var queryString = require('querystring');
var requestOps = {
host:'127.0.0.1',
port:'8080',
method:'post',
path:'/xintaisug/servlet/TestPayServlet',
headers:{
'Content-Type': 'application/json; charset=utf-8',
}
};
var message = '{'+queryString.stringify({
method : 'ST000025',
queryType : '04',
prtNum : '1a521eec-3ebf-4c23-a5f3-6e2b13f4ea52',
}) + '}';
console.log(message);
var req = http.request(requestOps,function(res){
res.setEncoding('utf8');
res.on('data', function (data) {
console.log(data);
});
});
req.on('error',function(e){
console.log(e);
});
req.write('{"queryType":"04","method":"ST000025","prtNum":"1a521eec-3ebf-4c23-a5f3-6e2b13f4ea52"}');
req.end();
console.log('我已经发送请求');<file_sep>/NodeJs/PushServer/app.js
var http = require('http');
var apn = require('apn');
var url = require('url');
var os = require('os');
var myPad = '';//保存pad的id
//创建服务端 以便接受设备id
var server = http.createServer(function(req,res){
//获取到的get数据
var getData = util.inspect(url.parse(req.url, true));
myPad = getData.id;
console.log(req.method,req.url);
console.log('接收到的GET数据:');
console.log(getData);
console.log('设备的id为:'+myPad);
res.writeHead('200',{'Content-Type':'text/html'});
res.end('{flag:1,des:"我已成功获取ID"}');
}).listen(7568);
console.log('IP信息:');
console.log(os.networkInterfaces());
console.log('获取id服务已经启动监听端口为:');
console.log(server.address());
//以下为发送推送
var device = new apn.Device(myPad);
var note = new apn.Notification();
note.badge = 1;
//note.sound = "notification-beep.wav";
note.alert = 'testPushCert';
note.device = device;
var callback = function(errorNum,notification){
console.log('错误编号为:'+errorNum);
console.log('错误信息为:'+notification);
}
var options = {
getway:'gateway.sandbox.push.apple.com',
errorCallback:callback,
cert:'testPushCert.pem',
key:'testPushKey.pem',
passphrase:'<PASSWORD>',
port:2195,
enhanced:true,
cacheLength:100
}
var apnConnection = new apn.Connection(options);
apnConnection.sendNotification(note);
<file_sep>/python/test.py
<<<<<<< HEAD
# name = input('enter')
# print('my name is :梁宏远')
# string = '你好,我是梁宏远'
# print('你' in string)
# name = input('enter')
# print('my name is :梁宏远')
# string = '你好,我是梁宏远'
# print('你' in string)
def test1_():
a = 'abcdef\
sdfsd'
print('sda' in a)
test1_()
if 10>1 :
a = 10
print(a)
def listTest_():
a = [1,2,3]
a[:1] = [4,5,6]
print (a)
listTest_()
def printtest():
s = 'test1\
sfdsfdsfdsfdsfsd\
'
print('Hello\
world')
print(s)
printtest()
def testFor() :
for i in range(0,10):
if i == 5 :
print('发现了数字',i)
break
else :
print('循环结束了,没有中途中断')
testFor()
def testfun(*a):
print(a)
testfun(1,2,3,4,5)
def testfun1(**a):
print(a)
testfun1(a=10,b=20,c=30)
def testfun2(a,b,c,d):
print(a,b,c,d)
args = (1,2,3,4)
testfun2(*args)
args = {'a':1,'c':2,'b':3,'d':4}
testfun2(**args)
def test1():
a = 'abcdef\
sdfsd'
print('sda' in a)
test1()
if 10>1 :
a = 10
print(a)
def sortfun(a,b):
return a-b
def listTest():
a = [3,20,1,6]
#a[1:1] = [4,5,6]
#b = ['ss','www','rrr']
#print(b.index('aaa'))
#a.sort()
print(a)
listTest()
def story(**keds):
return 'Once upon a time, there was a '\
'%(job)s called %(name)s.' % keds
def power(x,y,*others):
if others:
print('接收到了其他的参数:',others)
return pow(x,y)
<file_sep>/python/zipUpdatePackage.py
textFile = open('../../../2.txt');
str = textFile.read();
print(str);
textFile.close();<file_sep>/NodeJs/testM.js
var name;
exports.setName = function(name){
this.name = name;
}
exports.sayHello = function(){
console.log('Hello'+name);
}<file_sep>/python/pythonPath.py
import win32api,win32con
subkeys = ["Python.CompiledFile\\shell\\open\\command",
"Python.File\\shell\\Edit with IDLE\\command",
"Python.File\\shell\\open\\command",
"Python.File\\shell\\Run in interactive mode\\command",
"Python.NoConFile\\shell\\Edit with IDLE\\command",
"Python.NoConFile\\shell\\open\\command",
"Python.NoConFile\\shell\\Run in interactive mode\\command"]
key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT,
subkeys[0], 0, win32con.KEY_READ)
for key in subkeys :
print(win32api.RegQueryValue(win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT,
key, 0, win32con.KEY_READ), ""))
| 71cf731f80221789b330dd5b62ebe28e780dc7f7 | [
"JavaScript",
"Python"
] | 11 | JavaScript | xiaoBiao/test | afc970dee0097eb74c71eefda830506c646fc9f0 | 73595a39d061d374921e2d42beeeedaf1e6f0aac |
refs/heads/master | <file_sep># hangman-Csharp
The classic letter guessing game called Hangman using Asp.Net C#
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Linq;
namespace Hungman_Game__HW2
{
public partial class Hungman_WebForm : System.Web.UI.Page
{
string word;
string secret;
string maskedWord;
int attemptCount = 5;
protected void Page_Load(object sender, EventArgs e)
{
/* Submitting the ASP.NET page to the server for processing*/
if (!IsPostBack)
{
Hungman();
}
/*Perform the actions that are common to all requests, database query */
else
{
word = (string)ViewState["word"];
secret = (string)ViewState["secret"];
maskedWord = (string)ViewState["maskedWord"];
attemptCount = (int)ViewState["attemptCount"];
}
}
/* Perform any updates before the output is rendered. */
protected void Page_PreRender(Object sender, EventArgs e)
{
ViewState["word"] = word;
ViewState["secret"] = secret;
ViewState["maskedWord"] = maskedWord;
ViewState["attemptCount"] = attemptCount;
}
/*The class to run the game*/
protected void Hungman()
{
A.Enabled = true; B.Enabled = true; C.Enabled = true; D.Enabled = true; E.Enabled = true;
F.Enabled = true; G.Enabled = true; H.Enabled = true; I.Enabled = true; J.Enabled = true;
K.Enabled = true; L.Enabled = true; M.Enabled = true; N.Enabled = true; O.Enabled = true;
P.Enabled = true; Q.Enabled = true; R.Enabled = true; S.Enabled = true; T.Enabled = true;
U.Enabled = true; V.Enabled = true; W.Enabled = true; X.Enabled = true; Y.Enabled = true;
Z.Enabled = true; btnPlay.Enabled = false;
attemptCount =6;
image1.ImageUrl = "~/images/0.jpg";
/* Creating Array List where to store the name and the hint attributes*/
ArrayList secret_words = new ArrayList();
ArrayList explained_words = new ArrayList();
Random random = new Random();
/*By using exeption handeling, load the Xml file and display in specific labels the attributes name and hint of the element phrase*/
try
{
XmlDocument xDocument = new XmlDocument();
xDocument.Load(Server.MapPath("DataSet.xml"));
XmlNodeList xNode = xDocument.SelectNodes("Phrases/phrase");
foreach (XmlNode dataline in xNode)
{
secret_words.Add(dataline.Attributes["name"].Value.ToString());
explained_words.Add(dataline.Attributes["hint"].Value.ToString());
}
/*Storing into a string the secret and explained words*/
string[] findss = secret_words.ToArray(typeof(string)) as string[];
string[] hintss = explained_words.ToArray(typeof(string)) as string[];
int _random = random.Next(findss.Length);
secret = hintss[_random];
lblHint.Text = secret;
word = findss[_random];
maskedWord = word;
/*Using regular expression to mask the word*/
maskedWord = Regex.Replace(word, "[A-z]", "-");
lblWord.Text = maskedWord;
lblMessage.Text = "Lives left: ";
lblAttemps.Text = attemptCount.ToString();
lblResult.Text = "";
}
catch (Exception ex)
{
lblWord.Text = "Cannot read the file " + ex;
}
}
protected void LetterGuessed(object sender, EventArgs e)
{
if (attemptCount != 0 && (lblResult.Text.Equals("")))
{
string letter = ((Control)sender).ID.ToString().ToLower();
Button btn = (Button)sender;
btn.Enabled = false;
int startPosition = word.IndexOf(letter);
/*When the letter is guessed right*/
if (!(startPosition == -1))
{
do
{
maskedWord = maskedWord.Remove(startPosition, 1).Insert(startPosition, letter);
lblWord.Text = maskedWord;
startPosition = word.IndexOf(letter, startPosition + 1);
}
while (startPosition != -1);
}
/*If the letter is guessed wrong the parts of the pictures are drawn*/
else
{
attemptCount--;
if (attemptCount == 5)
{
image1.ImageUrl = "~/images/1.jpg";
}
if (attemptCount == 4)
{
image1.ImageUrl = "~/images/2.jpg";
}
if (attemptCount == 3)
{
image1.ImageUrl = "~/images/3.jpg";
}
if (attemptCount == 2)
{
image1.ImageUrl = "~/images/4.jpg";
}
if (attemptCount == 1)
{
image1.ImageUrl = "~/images/5.jpg";
}
if (attemptCount == 0)
{
image1.ImageUrl = "~/images/6.jpg";
}
lblAttemps.Text = attemptCount.ToString();
}
/*If the word is guessed correct*/
if (maskedWord.Equals(word))
{
btnPlay.Enabled = true;
lblWord.Text = word;
lblResult.Text = "You Won";
lblMessage.Text = "PLAY AGAIN";
lblAttemps.Text = "";
}
/*If the word is not guessed right and if the number of lives is 0*/
if (attemptCount == 0 && !(maskedWord.Equals(word)))
{
lblResult.Text ="TRY AGAIN!";
lblWord.Text = word;
btnPlay.Enabled = true;
lblMessage.Text = "DEAD :(";
lblAttemps.Text = "";
}
}
else
{
//Do nothing on letter button click
}
}
/*Button when clicking the Play Button*/
protected void btnPlay_Click(object sender, EventArgs e)
{
Hungman();
}
/*Button when Adding a new word*/
protected void btnAdd_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/DataSet.xml"));
XmlElement ParentElement = doc.CreateElement("phrase");
XmlAttribute Name = doc.CreateAttribute("name");
Name.InnerText = txtName.Text;
doc.DocumentElement.SetAttributeNode(Name);
XmlAttribute Hint= doc.CreateAttribute("hint");
Hint.InnerText = txtHint.Text;
doc.DocumentElement.SetAttributeNode(Hint);
doc.Save(Server.MapPath("~/DataSet.xml"));
}
protected void btnRemove_Click(object sender, EventArgs e)
{
}
}
} | c8a8772d0605b33dd22c08ee10ba390e0b600e5f | [
"Markdown",
"C#"
] | 2 | Markdown | Zaurelaa1/hangman-Csharp | ee1c90e17b6506bd96dc77afc3d0118884af4341 | 7da90cf31a6f3495a20c0dc97f7bfdc53ca388c1 |
refs/heads/main | <repo_name>Ammar-id/AI-matrace<file_sep>/backend/matrace/matserver/migrations/0002_carrier_article.py
# Generated by Django 3.2.3 on 2021-05-24 11:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('matserver', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='carrier',
name='article',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='matserver.article'),
),
]
<file_sep>/backend/matrace/matserver/api/urls.py
from django.conf.urls import url
from django.urls import path, include
from .views import (
ArticleListApiView,
CarrierListApiView,
)
urlpatterns = [
path('articles', ArticleListApiView.as_view()),
path('carriers', CarrierListApiView.as_view()),
]<file_sep>/backend/matrace/matserver/api/serializers.py
from rest_framework import serializers
from matserver.models import *
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ["number", "description","manufacturer", "provider", "user"]
class CarrierSerializer(serializers.ModelSerializer):
article = ArticleSerializer(read_only=False)
class Meta:
model = Carrier
fields = ["uid", "description", "article"]<file_sep>/backend/matrace/matserver/models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Article(models.Model):
number = models.CharField(max_length = 50)
description = models.CharField(max_length = 250, blank=True, null=True)
manufacturer = models.CharField(max_length = 50, blank=True, null=True)
provider = models.CharField(max_length = 50, blank=True, null=True)
user = models.ForeignKey(User, on_delete = models.CASCADE, blank = True, null = True)
def __str__(self):
return self.number
class Carrier(models.Model):
uid = models.CharField(max_length = 50)
description = models.CharField(max_length = 250, blank=True, null=True)
article = models.ForeignKey(Article, on_delete = models.CASCADE, blank = True, null = True)
def __str__(self):
return self.description<file_sep>/backend/matrace/matserver/api/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import permissions
from matserver.models import *
from .serializers import *
class ArticleListApiView(APIView):
# add permission to check if user is authenticated
#permission_classes = [permissions.IsAuthenticated]
# 1. List all
def get(self, request, *args, **kwargs):
'''
List all the todo items for given requested user
'''
#articles = Article.objects.filter(user = request.user.id)
articles = Article.objects.all()
serializer = ArticleSerializer(articles, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
# 2. Create
def post(self, request, *args, **kwargs):
'''
Create the Todo with given todo data
'''
data = {
'number': request.data.get('number'),
'description': request.data.get('description'),
'manufacturer': request.data.get('manufacturer'),
'provider': request.data.get('provider'),
'user': request.user.id
}
serializer = ArticleSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class CarrierListApiView(APIView):
# add permission to check if user is authenticated
#permission_classes = [permissions.IsAuthenticated]
# 1. List all
def get(self, request, *args, **kwargs):
'''
List all the todo items for given requested user
'''
carriers = Carrier.objects.all()
serializer = CarrierSerializer(carriers, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
# 2. Create
def post(self, request, *args, **kwargs):
'''
Create the Todo with given todo data
'''
data = {
'uid': request.data.get('uid'),
'description': request.data.get('description'),
'article': request.data.get('article'),
}
serializer = CarrierSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) | 75f3ad5f304e1c75746a1b7b0097e7f0d934249b | [
"Python"
] | 5 | Python | Ammar-id/AI-matrace | f5f11281da6140622e9b2c5781fee2a9f51c0730 | fdd494ea67ccb4758c0829004b0559c581683ae4 |
refs/heads/master | <repo_name>rbm4/p2<file_sep>/src/main/java/p2/aula_dia_11/T2.java
package p2.aula_dia_11;
public class T2 extends A implements Interface {
@Override
public void template() {
// TODO Auto-generated method stub
}
public void sort() {
// TODO Auto-generated method stub
}
}
| 1b58493274dfc9631edfc7b4b967e8c6ba08ec05 | [
"Java"
] | 1 | Java | rbm4/p2 | 471c3c691f267cd389dfd5b86db1d7f570362ece | 93472f8d3091b7d95535391178a81c1785f38401 |
refs/heads/master | <repo_name>tye-shutty/elocker<file_sep>/Sources/locker_module/hardware_layer/gpio.h
/*
File: gpio.h
Authors: <NAME> and <NAME>
This module is responsible to initialize the GPIO pins
PTC11, PTC10, PTB11 and PTB10 as input pins, and PTC9,
PTC0, PTC7 and PTC5 as outputs to be used by a 4x4 matrix
keypad. It also initializes PTC2 and PTC3 as output pins
to control the solenoid locks. The module permits pins
in port B and port C to be read, set or cleared, by providing
the pin number as input.
*/
#ifndef SOURCES_LOCKER_MODULE_HARDWARE_LAYER_GPIO_H_
#define SOURCES_LOCKER_MODULE_HARDWARE_LAYER_GPIO_H_
void gpio_init();
void set_portb_output(int pin);
void set_portc_output(int pin);
void clear_portb_output(int pin);
void clear_portc_output(int pin);
int get_portb_input(int pin);
int get_portc_input(int pin);
#endif /* SOURCES_LOCKER_MODULE_HARDWARE_LAYER_GPIO_H_ */
<file_sep>/Sources/admin_manager.h
/*
File: admin_manager.h
Authors: <NAME> and <NAME>
The admin manager module handles the instructions in
admin mode. The module dispatches the commands for
opening a locker or changing a password providing
the administrator previleges.
*/
#ifndef SOURCES_ADMIN_MANAGER_H_
#define SOURCES_ADMIN_MANAGER_H_
void handle_admin(locker_t* admin);
#endif /* SOURCES_ADMIN_MANAGER_H_ */
<file_sep>/Sources/locker_module/keypad.c
/*
File: keypad.c
Authors: <NAME> and <NAME>
Implementation of the keypad.h header file
*/
#include "keypad.h"
static keypad_t* this = 0;
void init_keypad() {
gpio_init();
int row[] = {5, 7, 0, 9};
for(int i = 0; i < 4; i++) {
set_portc_output(row[i]);
}
}
char get_char(int row, int col) {
switch(row) {
case 0:
if (col == 0) {
return '1';
} else if (col == 1) {
return '2';
} else if (col == 2) {
return '3';
} else if (col == 3) {
return 'A';
} else {
return 0;
}
case 1:
if (col == 0) {
return '4';
} else if (col == 1) {
return '5';
} else if (col == 2) {
return '6';
} else if (col == 3) {
return 'B';
} else {
return 0;
}
case 2:
if (col == 0) {
return '7';
} else if (col == 1) {
return '8';
} else if (col == 2) {
return '9';
} else if (col == 3) {
return 'C';
} else {
return 0;
}
case 3:
if (col == 0) {
return '0';
} else if (col == 1) {
return 'F';
} else if (col == 2) {
return 'E';
} else if (col == 3) {
return 'D';
} else {
return 0;
}
default:
return 0;
}
}
char get_key() {
int row[] = {5, 7, 0, 9};
int col[] = {10, 11, 11, 10};
for(int i = 0; i < 4; i++) {
set_portc_output(row[i]);
}
int selCol = -1;
int selRow = -1;
for(int i = 0; i < 4; i++) {
clear_portc_output(row[i]);
for(int j = 0; j < 4; j++) {
int input;
if (j < 2) {
input = get_portb_input(col[j]);
} else {
input = get_portc_input(col[j]);
}
if (!input) {
selRow = i;
selCol = j;
}
}
set_portc_output(row[i]);
}
return get_char(selRow, selCol);
}
char get_debounced_key() {
char input = get_key();
// wait for key press
while (input == 0) {
input = get_key();
};
// key press detected
int counter = 500;
int temp = input;
while(counter) {
temp = input;
input = get_key();
if (temp == input) {
counter--;
}
}
return input;
}
keypad_t* get_keypad() {
if(this == 0) {
init_keypad();
this = (keypad_t*) malloc(sizeof(keypad_t));
this -> get_key = &get_key;
this -> get_debounced_key = &get_debounced_key;
}
return this;
}
<file_sep>/Sources/locker_module/keypad.h
/*
File: keypad.h
Authors: <NAME> and <NAME>
This module is an abstraction for the keypad. The module
implements a method get the key that was pressedand it
debounces the input. The module ensures that only a single
instance of the keypad is created.
*/
#ifndef SOURCES_LOCKER_MODULE_KEYPAD_H_
#define SOURCES_LOCKER_MODULE_KEYPAD_H_
#include <stdlib.h>
#include "hardware_layer/gpio.h"
typedef struct keypad_struct {
char (*get_key) ();
char (*get_debounced_key) ();
} keypad_t;
keypad_t* get_keypad();
#endif /* SOURCES_LOCKER_MODULE_KEYPAD_H_ */
<file_sep>/Sources/locker_module/hardware_layer/gpio.c
/*
File: gpio.c
Authors: <NAME> and <NAME>
Implementation of the gpio.h header file
*/
#include "gpio.h"
#include "fsl_device_registers.h"
void gpio_init() {
SIM_SCGC5 |= SIM_SCGC5_PORTC(1);
SIM_SCGC5 |= SIM_SCGC5_PORTB(1);
// Solenoid pints
PORTC_PCR3 |= PORT_PCR_MUX(1);
GPIOC_PDDR |= 0x01 << 3;
PORTC_PCR2 |= PORT_PCR_MUX(1);
GPIOC_PDDR |= 0x01 << 2;
// Keypad pins
// Inputs
PORTC_PCR11 |= PORT_PCR_MUX(1);
PORTC_PCR10 |= PORT_PCR_MUX(1);
PORTB_PCR11 |= PORT_PCR_MUX(1);
PORTB_PCR10 |= PORT_PCR_MUX(1);
//Outputs
PORTC_PCR9 |= PORT_PCR_MUX(1);
PORTC_PCR0 |= PORT_PCR_MUX(1);
PORTC_PCR7 |= PORT_PCR_MUX(1);
PORTC_PCR5 |= PORT_PCR_MUX(1);
GPIOC_PDDR |= 0x01 << 9;
GPIOC_PDDR |= 0x01 << 0;
GPIOC_PDDR |= 0x01 << 7;
GPIOC_PDDR |= 0x01 << 5;
};
void set_portb_output(int pin) {
GPIOB_PSOR |= 0x01 << pin;
};
void set_portc_output(int pin) {
GPIOC_PSOR |= 0x01 << pin;
};
void clear_portb_output(int pin) {
GPIOB_PCOR |= 0x01 << pin;
};
void clear_portc_output(int pin) {
GPIOC_PCOR |= 0x01 << pin;
};
int get_portb_input(int pin) {
return GPIOB_PDIR & (1 << pin);
}
int get_portc_input(int pin) {
return GPIOC_PDIR & (1 << pin);
}
<file_sep>/Sources/locker_module/hardware_layer/dac.h
/*
File: dac.h
Authors: <NAME> and <NAME>
This module is responsible to initialize the DAC0 at the
DAC0_OUT pin, and the periodic timer interrupt (PIT0).
The PIT and the DAC are used together to generate a sine
wave that can be used to generate a tone in a speaker device.
The module permits the control over the frequency and duration
of the sine wave. The DAC outputs 12-bit values, and is
configured with buffer disabled.
*/
#ifndef SOURCES_LOCKER_MODULE_HARDWARE_LAYER_DAC_H_
#define SOURCES_LOCKER_MODULE_HARDWARE_LAYER_DAC_H_
#include <stdint.h>
uint16_t dac_data[1024] = {
0x800,0x80c,0x819,0x825,0x832,0x83e,0x84b,0x858,0x864,0x871,
0x87d,0x88a,0x896,0x8a3,0x8af,0x8bc,0x8c8,0x8d5,0x8e1,0x8ee,
0x8fa,0x907,0x913,0x920,0x92c,0x939,0x945,0x951,0x95e,0x96a,
0x977,0x983,0x98f,0x99c,0x9a8,0x9b4,0x9c1,0x9cd,0x9d9,0x9e5,
0x9f1,0x9fe,0xa0a,0xa16,0xa22,0xa2e,0xa3a,0xa46,0xa52,0xa5e,
0xa6a,0xa76,0xa82,0xa8e,0xa9a,0xaa6,0xab2,0xabe,0xaca,0xad5,
0xae1,0xaed,0xaf8,0xb04,0xb10,0xb1b,0xb27,0xb32,0xb3e,0xb49,
0xb55,0xb60,0xb6c,0xb77,0xb82,0xb8e,0xb99,0xba4,0xbaf,0xbba,
0xbc6,0xbd1,0xbdc,0xbe7,0xbf2,0xbfd,0xc07,0xc12,0xc1d,0xc28,
0xc33,0xc3d,0xc48,0xc52,0xc5d,0xc68,0xc72,0xc7c,0xc87,0xc91,
0xc9b,0xca6,0xcb0,0xcba,0xcc4,0xcce,0xcd8,0xce2,0xcec,0xcf6,
0xd00,0xd0a,0xd13,0xd1d,0xd27,0xd30,0xd3a,0xd43,0xd4d,0xd56,
0xd60,0xd69,0xd72,0xd7b,0xd84,0xd8e,0xd97,0xd9f,0xda8,0xdb1,
0xdba,0xdc3,0xdcc,0xdd4,0xddd,0xde5,0xdee,0xdf6,0xdfe,0xe07,
0xe0f,0xe17,0xe1f,0xe27,0xe2f,0xe37,0xe3f,0xe47,0xe4f,0xe56,
0xe5e,0xe66,0xe6d,0xe75,0xe7c,0xe83,0xe8b,0xe92,0xe99,0xea0,
0xea7,0xeae,0xeb5,0xebc,0xec2,0xec9,0xed0,0xed6,0xedd,0xee3,
0xeea,0xef0,0xef6,0xefc,0xf02,0xf08,0xf0e,0xf14,0xf1a,0xf20,
0xf25,0xf2b,0xf31,0xf36,0xf3b,0xf41,0xf46,0xf4b,0xf50,0xf55,
0xf5a,0xf5f,0xf64,0xf69,0xf6d,0xf72,0xf77,0xf7b,0xf80,0xf84,
0xf88,0xf8c,0xf90,0xf94,0xf98,0xf9c,0xfa0,0xfa4,0xfa8,0xfab,
0xfaf,0xfb2,0xfb6,0xfb9,0xfbc,0xfbf,0xfc2,0xfc5,0xfc8,0xfcb,
0xfce,0xfd1,0xfd3,0xfd6,0xfd8,0xfdb,0xfdd,0xfdf,0xfe1,0xfe3,
0xfe5,0xfe7,0xfe9,0xfeb,0xfed,0xfee,0xff0,0xff1,0xff3,0xff4,
0xff5,0xff7,0xff8,0xff9,0xffa,0xffb,0xffb,0xffc,0xffd,0xffd,
0xffe,0xffe,0xffe,0xfff,0xfff,0xfff,0xfff,0xfff,0xfff,0xfff,
0xffe,0xffe,0xffd,0xffd,0xffc,0xffc,0xffb,0xffa,0xff9,0xff8,
0xff7,0xff6,0xff5,0xff4,0xff2,0xff1,0xfef,0xfee,0xfec,0xfea,
0xfe8,0xfe6,0xfe4,0xfe2,0xfe0,0xfde,0xfdc,0xfd9,0xfd7,0xfd4,
0xfd2,0xfcf,0xfcc,0xfca,0xfc7,0xfc4,0xfc1,0xfbe,0xfba,0xfb7,
0xfb4,0xfb0,0xfad,0xfa9,0xfa6,0xfa2,0xf9e,0xf9a,0xf96,0xf92,
0xf8e,0xf8a,0xf86,0xf82,0xf7d,0xf79,0xf74,0xf70,0xf6b,0xf66,
0xf62,0xf5d,0xf58,0xf53,0xf4e,0xf49,0xf43,0xf3e,0xf39,0xf33,
0xf2e,0xf28,0xf23,0xf1d,0xf17,0xf11,0xf0b,0xf05,0xeff,0xef9,
0xef3,0xeed,0xee6,0xee0,0xeda,0xed3,0xecc,0xec6,0xebf,0xeb8,
0xeb1,0xeab,0xea4,0xe9c,0xe95,0xe8e,0xe87,0xe80,0xe78,0xe71,
0xe69,0xe62,0xe5a,0xe53,0xe4b,0xe43,0xe3b,0xe33,0xe2b,0xe23,
0xe1b,0xe13,0xe0b,0xe03,0xdfa,0xdf2,0xde9,0xde1,0xdd8,0xdd0,
0xdc7,0xdbe,0xdb6,0xdad,0xda4,0xd9b,0xd92,0xd89,0xd80,0xd77,
0xd6e,0xd64,0xd5b,0xd52,0xd48,0xd3f,0xd35,0xd2c,0xd22,0xd18,
0xd0f,0xd05,0xcfb,0xcf1,0xce7,0xcdd,0xcd3,0xcc9,0xcbf,0xcb5,
0xcab,0xca1,0xc96,0xc8c,0xc82,0xc77,0xc6d,0xc62,0xc58,0xc4d,
0xc43,0xc38,0xc2d,0xc22,0xc18,0xc0d,0xc02,0xbf7,0xbec,0xbe1,
0xbd6,0xbcb,0xbc0,0xbb5,0xbaa,0xb9f,0xb93,0xb88,0xb7d,0xb71,
0xb66,0xb5b,0xb4f,0xb44,0xb38,0xb2d,0xb21,0xb16,0xb0a,0xafe,
0xaf3,0xae7,0xadb,0xacf,0xac4,0xab8,0xaac,0xaa0,0xa94,0xa88,
0xa7c,0xa70,0xa64,0xa58,0xa4c,0xa40,0xa34,0xa28,0xa1c,0xa10,
0xa04,0x9f8,0x9eb,0x9df,0x9d3,0x9c7,0x9ba,0x9ae,0x9a2,0x995,
0x989,0x97d,0x970,0x964,0x958,0x94b,0x93f,0x932,0x926,0x91a,
0x90d,0x901,0x8f4,0x8e8,0x8db,0x8cf,0x8c2,0x8b6,0x8a9,0x89d,
0x890,0x883,0x877,0x86a,0x85e,0x851,0x845,0x838,0x82c,0x81f,
0x812,0x806,0x7f9,0x7ed,0x7e0,0x7d3,0x7c7,0x7ba,0x7ae,0x7a1,
0x795,0x788,0x77c,0x76f,0x762,0x756,0x749,0x73d,0x730,0x724,
0x717,0x70b,0x6fe,0x6f2,0x6e5,0x6d9,0x6cd,0x6c0,0x6b4,0x6a7,
0x69b,0x68f,0x682,0x676,0x66a,0x65d,0x651,0x645,0x638,0x62c,
0x620,0x614,0x607,0x5fb,0x5ef,0x5e3,0x5d7,0x5cb,0x5bf,0x5b3,
0x5a7,0x59b,0x58f,0x583,0x577,0x56b,0x55f,0x553,0x547,0x53b,
0x530,0x524,0x518,0x50c,0x501,0x4f5,0x4e9,0x4de,0x4d2,0x4c7,
0x4bb,0x4b0,0x4a4,0x499,0x48e,0x482,0x477,0x46c,0x460,0x455,
0x44a,0x43f,0x434,0x429,0x41e,0x413,0x408,0x3fd,0x3f2,0x3e7,
0x3dd,0x3d2,0x3c7,0x3bc,0x3b2,0x3a7,0x39d,0x392,0x388,0x37d,
0x373,0x369,0x35e,0x354,0x34a,0x340,0x336,0x32c,0x322,0x318,
0x30e,0x304,0x2fa,0x2f0,0x2e7,0x2dd,0x2d3,0x2ca,0x2c0,0x2b7,
0x2ad,0x2a4,0x29b,0x291,0x288,0x27f,0x276,0x26d,0x264,0x25b,
0x252,0x249,0x241,0x238,0x22f,0x227,0x21e,0x216,0x20d,0x205,
0x1fc,0x1f4,0x1ec,0x1e4,0x1dc,0x1d4,0x1cc,0x1c4,0x1bc,0x1b4,
0x1ac,0x1a5,0x19d,0x196,0x18e,0x187,0x17f,0x178,0x171,0x16a,
0x163,0x15b,0x154,0x14e,0x147,0x140,0x139,0x133,0x12c,0x125,
0x11f,0x119,0x112,0x10c,0x106,0x100,0xfa,0xf4,0xee,0xe8,
0xe2,0xdc,0xd7,0xd1,0xcc,0xc6,0xc1,0xbc,0xb6,0xb1,
0xac,0xa7,0xa2,0x9d,0x99,0x94,0x8f,0x8b,0x86,0x82,
0x7d,0x79,0x75,0x71,0x6d,0x69,0x65,0x61,0x5d,0x59,
0x56,0x52,0x4f,0x4b,0x48,0x45,0x41,0x3e,0x3b,0x38,
0x35,0x33,0x30,0x2d,0x2b,0x28,0x26,0x23,0x21,0x1f,
0x1d,0x1b,0x19,0x17,0x15,0x13,0x11,0x10,0xe,0xd,
0xb,0xa,0x9,0x8,0x7,0x6,0x5,0x4,0x3,0x3,
0x2,0x2,0x1,0x1,0x0,0x0,0x0,0x0,0x0,0x0,
0x0,0x1,0x1,0x1,0x2,0x2,0x3,0x4,0x4,0x5,
0x6,0x7,0x8,0xa,0xb,0xc,0xe,0xf,0x11,0x12,
0x14,0x16,0x18,0x1a,0x1c,0x1e,0x20,0x22,0x24,0x27,
0x29,0x2c,0x2e,0x31,0x34,0x37,0x3a,0x3d,0x40,0x43,
0x46,0x49,0x4d,0x50,0x54,0x57,0x5b,0x5f,0x63,0x67,
0x6b,0x6f,0x73,0x77,0x7b,0x7f,0x84,0x88,0x8d,0x92,
0x96,0x9b,0xa0,0xa5,0xaa,0xaf,0xb4,0xb9,0xbe,0xc4,
0xc9,0xce,0xd4,0xda,0xdf,0xe5,0xeb,0xf1,0xf7,0xfd,
0x103,0x109,0x10f,0x115,0x11c,0x122,0x129,0x12f,0x136,0x13d,
0x143,0x14a,0x151,0x158,0x15f,0x166,0x16d,0x174,0x17c,0x183,
0x18a,0x192,0x199,0x1a1,0x1a9,0x1b0,0x1b8,0x1c0,0x1c8,0x1d0,
0x1d8,0x1e0,0x1e8,0x1f0,0x1f8,0x201,0x209,0x211,0x21a,0x222,
0x22b,0x233,0x23c,0x245,0x24e,0x257,0x260,0x268,0x271,0x27b,
0x284,0x28d,0x296,0x29f,0x2a9,0x2b2,0x2bc,0x2c5,0x2cf,0x2d8,
0x2e2,0x2ec,0x2f5,0x2ff,0x309,0x313,0x31d,0x327,0x331,0x33b,
0x345,0x34f,0x359,0x364,0x36e,0x378,0x383,0x38d,0x397,0x3a2,
0x3ad,0x3b7,0x3c2,0x3cc,0x3d7,0x3e2,0x3ed,0x3f8,0x402,0x40d,
0x418,0x423,0x42e,0x439,0x445,0x450,0x45b,0x466,0x471,0x47d,
0x488,0x493,0x49f,0x4aa,0x4b6,0x4c1,0x4cd,0x4d8,0x4e4,0x4ef,
0x4fb,0x507,0x512,0x51e,0x52a,0x535,0x541,0x54d,0x559,0x565,
0x571,0x57d,0x589,0x595,0x5a1,0x5ad,0x5b9,0x5c5,0x5d1,0x5dd,
0x5e9,0x5f5,0x601,0x60e,0x61a,0x626,0x632,0x63e,0x64b,0x657,
0x663,0x670,0x67c,0x688,0x695,0x6a1,0x6ae,0x6ba,0x6c6,0x6d3,
0x6df,0x6ec,0x6f8,0x705,0x711,0x71e,0x72a,0x737,0x743,0x750,
0x75c,0x769,0x775,0x782,0x78e,0x79b,0x7a7,0x7b4,0x7c1,0x7cd,
0x7da,0x7e6,0x7f3,0x800};
void dac_init();
void dac_out(int frequency, float time);
#endif /* SOURCES_LOCKER_MODULE_HARDWARE_LAYER_DAC_H_ */
<file_sep>/Sources/main.c
/*
File: main.c
Authors: <NAME> and <NAME>
This is the entry point of the system. The module is
responsible for dispatching instructions for all
manager modules based on the input of the user.
*/
#include "locker_module/keypad.h"
#include "locker_module/putty.h"
#include "locker.h"
#include "messages.h"
#include "user_manager.h"
#include "admin_manager.h"
#include "access_manager.h"
int main(void)
{
keypad_t* keypad = get_keypad();
putty_t* putty = get_putty();
locker_t* locker_1 = get_locker(1);
locker_t* locker_2 = get_locker(2);
locker_t* admin = get_locker(0);
while(1) {
putty -> print_line(welcomeMsg);
char keyPressed = keypad -> get_debounced_key();
if (keyPressed == '1') {
handle_user(locker_1);
} else if (keyPressed == '2') {
handle_user(locker_2);
} else if (keyPressed == 'A') {
handle_admin(admin);
} else if (keyPressed == 'B') {
handle_password_change(-1);
}
putty -> print_line(clearDisplay);
}
return 0;
}
<file_sep>/Sources/locker_module/speaker.h
/*
File: speaker.h
Authors: <NAME> and <NAME>
This module implement the speaker function play. Two types
of sounds are programmed: success and fail. The success sound
is a single beep at 261Hz, while the fail sound is a double beep
at 698 Hz. The module ensures that only a single instance of
the speaker is created.
*/
#ifndef SOURCES_LOCKER_MODULE_SPEAKER_H_
#define SOURCES_LOCKER_MODULE_SPEAKER_H_
#include <stdint.h>
#include "hardware_layer/dac.h"
#define FAIL 0
#define SUCCESS 1
typedef struct speaker_struct {
void (*play) (int condition);
} speaker_t;
speaker_t* get_speaker();
#endif /* SOURCES_LOCKER_MODULE_SPEAKER_H_ */
<file_sep>/Sources/uart_lcd.c
//author: <NAME>
//To enter the RS-232 mode, both R1 and R2 jumpers should be open (default).
//The RS-232 signal must be 5V TTL compatible
//Communication format is 8-bit data, 1 Stop bit, no parity, no handshaking.
//Default BAUD rate is 9600
//All delays must take 3 to 5 volt logic converter into account (maximum 18ns
//between -55 C and 125 C)
#include "fsl_device_registers.h"
#include "MK64F12.h"
#include "display_timer.h"
//0.1 ms Display Character Write execution time
//0x20 to 0x7F displays the standard set of characters
void uart0_putstring(char* start){
while(*start != NULL){
while(!(UART0_S1 & 1<<7)); //Transmit Data Register Empty Flag
UART0_D = *start;
delay(1);
start++;
}
}
//1.5 ms execution time
void cursor_home(){
char temp[] = {0xFE, 0x46, 0};
uart0_putstring(temp);
}
//0.1 ms execution time
void move_cursor_right(){
char temp[] = {0xFE, 0x4A, 0};
uart0_putstring(temp);
}
//1.5 ms execution time
void clear_screen(){
char temp[] = {0xFE, 0x51, 0};
uart0_putstring(temp);
}
//Each message must be less than 33 characters (not including null)
//and null terminated.
//0.1 ms Display Character Write execution time
//0x20 to 0x7F displays the standard set of characters
void lcd_print_string(char *char_ptr){
clear_screen();
delay(2);
cursor_home();
delay(2);
while(*char_ptr != NULL){
while(!(UART0_S1 & 1<<7)); //Transmit Data Register Empty Flag
UART0_D = *char_ptr;
char_ptr++;
delay(1);
while(!(UART0_S1 & 1<<7));
move_cursor_right();
delay(1);
}
}
void lcd_uart0_interface_init(){
SIM_SCGC5 |= SIM_SCGC5_PORTB_MASK | SIM_SCGC5_PORTA_MASK;
SIM_SCGC4 |= SIM_SCGC4_UART0_MASK; //Enable UART0 clock
PORTA_PCR2 |= PORT_PCR_MUX(2); //Enable UART0 TX: A2 has a pin header
UART0_C2 &= ~(UART_C2_TE_MASK | UART_C2_RE_MASK); //disable I/O
UART0_BDH = 0x00;
UART0_BDL = 0x88; //9600 Baud
UART0_C2 |= UART_C2_TE_MASK; //enable Output
char temp[] = {0xFE, 0x41, 0}; //lcd on
uart0_putstring(temp);
char temp2[] = "Initializing...";
lcd_print_string(temp2);
}
<file_sep>/Sources/locker_module/hardware_layer/uart.c
/*
File: uart.c
Authors: <NAME>
Implementation of the uart.h header file
*/
#include "MK64F12.h"
#include "fsl_device_registers.h"
void uart_init() {
// Enabling clock for the UART
SIM_SCGC4 |= SIM_SCGC4_UART0(1);
// Enabling port B
SIM_SCGC5 |= SIM_SCGC5_PORTB(1);
// Configuring port E pins to UART alternate
PORTB_PCR16 |= PORT_PCR_MUX(3); // Setting pin16 of PortB to UART0_TX
PORTB_PCR17 |= PORT_PCR_MUX(3); // Setting pin17 of PortB to UART0_RX
// Setting BAUD rate to 9600 bauds
UART0_BDH = 0;
UART0_BDL = 0x88;
// Enabling transmit and receive
UART0_C2 |= UART_C2_TE(1);
}
void uart_put_char(char c) {
// Write the char to the UART0 data register
while(!(UART0_S1 & UART_S1_TDRE_MASK));
UART0_D = c;
while(!(UART0_S1 & UART_S1_TDRE_MASK));
}
char uart_get_char() {
// Wait until all bits are received
while(!(UART0_S1 & UART_S1_RDRF_MASK)); //Receive Data Register Full Flag
return UART0_D;
}
void uart_put_string(char * string) {
char * currentChar = string;
// Send one char at a time to the UART
while(*currentChar){
uart_put_char(*currentChar);
currentChar++;
}
}
<file_sep>/Sources/locker_module/hardware_layer/adc.c
/*
File: adc.c
Authors: <NAME> and <NAME>
Implementation of the adc.h header file
*/
#include "adc.h"
#include "fsl_device_registers.h"
void adc_init() {
SIM_SCGC6 |= SIM_SCGC6_ADC0_MASK;
SIM_SCGC5 |= SIM_SCGC5_PORTE(1);
PORTE_PCR24 |= PORT_PCR_MUX(0);
}
uint8_t adc_read() {
ADC0_SC1A &= ADC_SC1_ADCH(17);
while(!(ADC0_SC1A & ADC_SC1_COCO_MASK));
return ADC0_RA;
}
<file_sep>/Sources/locker_module/hardware_layer/adc.h
/*
File: adc.h
Authors: <NAME> and <NAME>
This module is responsible to initialize the ADC0 at PTE24
on channel 17 and enable calls to read the value in the ADC.
The ADC is configured to operate in the single-ended 8-bit mode
*/
#include <stdint.h>
#ifndef SOURCES_LOCKER_MODULE_HARDWARE_LAYER_ADC_H_
#define SOURCES_LOCKER_MODULE_HARDWARE_LAYER_ADC_H_
void adc_init();
uint8_t adc_read();
#endif /* SOURCES_LOCKER_MODULE_HARDWARE_LAYER_ADC_H_ */
<file_sep>/Sources/locker_module/speaker.c
/*
File: speaker.c
Authors: <NAME> and <NAME>
Implementation of the speaker.h header file
*/
#include "speaker.h"
#include "display_timer.h"
#include <stdlib.h>
static speaker_t* this = 0;
void init_speaker() {
dac_init();
}
void successSound() {
dac_out(261, 250000.00f);
}
void failSound() {
timer_t* timer = get_timer();
dac_out(698, 250000.00f);
timer -> delay(250);
dac_out(698, 250000.00f);
}
void play (int condition) {
if (condition == SUCCESS) {
successSound();
} else {
failSound();
}
};
speaker_t* get_speaker() {
if(this == 0) {
init_speaker();
this = (speaker_t*) malloc(sizeof(speaker_t));
this -> play = &play;
}
return this;
}
<file_sep>/Sources/user_manager.h
/*
File: user_manager.h
Authors: <NAME> and <NAME>
The user manager module is responsible for getting
authorization to unlock a locker and give the correct
feedback to the user.
*/
#ifndef SOURCES_USER_MANAGER_H_
#define SOURCES_USER_MANAGER_H_
#include "locker.h"
void handle_user(locker_t* locker);
#endif /* SOURCES_USER_MANAGER_H_ */
<file_sep>/Sources/messages.h
/*
File: messages.h
Authors: <NAME> and <NAME>
Collection of all messages displayed by the system
*/
char welcomeMsg[] = " Welcome ";
char enterPasswordMsg[] = "Enter password";
char enterNewPasswordMsg[] = "New password";
char tooManyAttemptsMsg[] = "Locker blocked";
char invalidMsg[] = "Invalid password";
char validMsg[] = " Valid password";
char adminAccess[] = " Admin Access";
char adminLogoutMsg[] = "Admin logged out";
char openMsg[] = " Locker open";
char changeTargetMsg1[] = "Change Password";
char changeTargetMsg2[] = " Select target ";
char passChangedMsg[] = "Password changed";
char centralize[] = " ";
char clearDisplay[] = "\033[2J";
<file_sep>/Sources/locker_module/potentiometer.c
/*
File: potentiometer.c
Authors: <NAME> and <NAME>
Implementation of the potentiometer.h header file
*/
#include "potentiometer.h"
static pot_t* this = 0;
void init_potentiometer() {
adc_init();
}
uint8_t read_value() {
return adc_read();
}
pot_t* get_pot() {
if(this == 0) {
init_potentiometer();
this = (pot_t*) malloc(sizeof(pot_t));
this -> read_value = &read_value;
}
return this;
}
<file_sep>/Sources/locker_module/solenoid_lock.h
/*
File: solenoid_lock.h
Authors: <NAME> and <NAME>
This module is an abstraction for the solenoids.
The module implements two functions: open and close, to
indicate the action required by the lock. It uses the
gpio module, and only two instances are allowed to be
created: one for the locker 1 and one for the locker 2.
*/
#ifndef SOURCES_LOCKER_MODULE_SOLENOID_LOCK_H_
#define SOURCES_LOCKER_MODULE_SOLENOID_LOCK_H_
#include "hardware_layer/gpio.h"
typedef struct lock_struct {
void (*open) ();
void (*close) ();
} lock_t;
lock_t* get_solenoid_lock(int lock_number);
#endif /* SOURCES_LOCKER_MODULE_SOLENOID_LOCK_H_ */
<file_sep>/Sources/access_manager.c
/*
File: access_manager.c
Authors: <NAME> and <NAME>
Implementation of the access_manager.h header file
*/
#include "locker_module/potentiometer.h"
#include "locker_module/speaker.h"
#include "locker_module/keypad.h"
#include "locker_module/display_timer.h"
#include "messages.h"
#include "access_manager.h"
int check_password(locker_t* locker, putty_t* putty) {
pot_t* potentiometer = get_pot();
int* combination = (int*) malloc(sizeof(int) * 3);
combination[0] = 0;
combination[1] = 0;
combination[2] = 0;
timer_t* timer = get_timer();
putty -> print_line(enterPasswordMsg);
putty -> print_string(centralize);
for (int i = 0; i < 3; i++) {
int elapsedTime = 0;
while(elapsedTime < 4000){
if ((potentiometer -> read_value()) / 8 == combination[i]) {
timer -> delay(1);
elapsedTime++;
} else {
combination[i] = (potentiometer -> read_value()) / 8;
char digit1 = (combination[i] / 10) + '0';
char digit2 = (combination[i] % 10) + '0';
putty -> put_char(digit1);
putty -> put_char(digit2);
putty -> put_char(8);
putty -> put_char(8);
elapsedTime = 0;
}
}
char digit1 = (combination[i] / 10) + '0';
char digit2 = (combination[i] % 10) + '0';
putty -> put_char(digit1);
putty -> put_char(digit2);
putty -> put_char(' ');
}
int check = 3;
for (int i = 0; i < 3; i++) {
if(combination[i] == locker -> password[i]) {
check--;
}
}
putty -> print_line(clearDisplay);
return check;
}
int authenticate_user(locker_t* locker) {
putty_t* putty = get_lcd();
speaker_t* speaker = get_speaker();
timer_t* timer = get_timer();
int isPassWrong = check_password(locker, putty);
if (isPassWrong) {
speaker -> play(FAIL);
putty -> print_line(invalidMsg);
timer -> delay(2000);
return -1;
} else {
speaker -> play(SUCCESS);
putty -> print_line(validMsg);
timer -> delay(2000);
return 0;
}
}
void change_password(locker_t* locker, putty_t* putty, int isAdmin) {
int isAuthenticated = authenticate_user(locker);
if (isAuthenticated == 0 || isAdmin == 0) {
pot_t* potentiometer = get_pot();
int* combination = (int*) malloc(sizeof(int) * 3);
combination[0] = 0;
combination[1] = 0;
combination[2] = 0;
timer_t* timer = get_timer();
putty -> print_line(enterNewPasswordMsg);
putty -> print_string(centralize);
for (int i = 0; i < 3; i++) {
int elapsedTime = 0;
while(elapsedTime < 4000){
if ((potentiometer -> read_value()) / 8 == combination[i]) {
timer -> delay(1);
elapsedTime++;
} else {
combination[i] = (potentiometer -> read_value()) / 8;
char digit1 = (combination[i] / 10) + '0';
char digit2 = (combination[i] % 10) + '0';
putty -> put_char(digit1);
putty -> put_char(digit2);
putty -> put_char(8);
putty -> put_char(8);
elapsedTime = 0;
}
}
char digit1 = (combination[i] / 10) + '0';
char digit2 = (combination[i] % 10) + '0';
putty -> put_char(digit1);
putty -> put_char(digit2);
putty -> put_char(' ');
}
locker -> password = <PASSWORD>;
putty -> print_line(clearDisplay);
}
}
void handle_password_change(int isAdmin) {
locker_t* locker_1 = get_locker(1);
locker_t* locker_2 = get_locker(2);
locker_t* admin = get_locker(0);
putty_t* putty = get_lcd();
putty -> print_line(changeTargetMsg1);
putty -> print_string(changeTargetMsg2);
timer_t* timer = get_timer();
timer -> delay(2000);
keypad_t* keypad = get_keypad();
char keyPressed = keypad -> get_debounced_key();
if (keyPressed == '1') {
change_password(locker_1, putty, isAdmin);
putty -> print_string(passChangedMsg);
} else if (keyPressed == '2') {
change_password(locker_2, putty, isAdmin);
putty -> print_string(passChangedMsg);
} else if (keyPressed == 'A') {
change_password(admin, putty, isAdmin);
putty -> print_string(passChangedMsg);
}
timer -> delay(2000);
}
<file_sep>/Sources/locker_module/solenoid_lock.c
/*
File: solenoid_lock.c
Authors: <NAME> and <NAME>
Implementation of the solenoid_lock.h header file
*/
#include "solenoid_lock.h"
#include <stdlib.h>
static lock_t* lock1 = 0;
static lock_t* lock2 = 0;
void open1() {
set_portc_output(3);
}
void close1() {
clear_portc_output(3);
}
void open2() {
set_portc_output(2);
}
void close2() {
clear_portc_output(2);
}
lock_t* get_solenoid_lock(int number) {
if (number == 1) {
if(lock1 == 0) {
lock1 = (lock_t*) malloc(sizeof(lock_t));
lock1 -> open = &open1;
lock1 -> close = &close1;
}
return lock1;
} else {
if(lock2 == 0) {
lock2 = (lock_t*) malloc(sizeof(lock_t));
lock2 -> open = &open2;
lock2 -> close = &close2;
}
return lock2;
}
}
<file_sep>/Sources/locker_module/putty.h
/*
File: putty.h
Authors: <NAME> and <NAME>
This module is an abstraction for the putty terminal.
The module utilizes the uart module to call the functions
to print strings and chars. The module ensures that only
a single instance of the putty is created.
*/
#ifndef SOURCES_LOCKER_MODULE_PUTTY_H_
#define SOURCES_LOCKER_MODULE_PUTTY_H_
#include <stdlib.h>
#include "hardware_layer/uart.h"
typedef struct putty_struct {
void (*put_char) (char character);
void (*print_line) (char* string);
void (*print_string) (char* string);
} putty_t;
putty_t* get_putty();
#endif /* SOURCES_LOCKER_MODULE_PUTTY_H_ */
<file_sep>/Sources/locker_module/hardware_layer/uart.h
/*
File: uart.h
Authors: <NAME>
This module is responsible to initialize the UART0 at
pins PTB16 and PTB17. The UART transmission rate is set to
9600 BAUD in a 8-bit data format with start + stop bit. No
parity bit is configured. Transmission and reception of
data is controlled by checks on the respective flags.
The module permits a single char or a full string to be
transmitted via the UART.
*/
#ifndef SOURCES_LOCKER_MODULE_HARDWARE_LAYER_UART_H_
#define SOURCES_LOCKER_MODULE_HARDWARE_LAYER_UART_H_
void uart_init();
void uart_put_char(char c);
char uart_get_char();
void uart_put_string(char * string);
#endif /* SOURCES_LOCKER_MODULE_HARDWARE_LAYER_UART_H_ */
<file_sep>/Sources/admin_manager.c
/*
File: admin_manager.c
Authors: <NAME> and <NAME>
Implementation of the admin_manager.h header file
*/
#include "locker_module/display_timer.h"
#include "locker_module/solenoid_lock.h"
#include "locker_module/keypad.h"
#include "locker_module/putty.h"
#include "messages.h"
#include "user_manager.h"
#include "access_manager.h"
void handle_admin(locker_t* admin) {
putty_t* putty = get_putty();
timer_t* timer = get_timer();
int isAuthenticated = authenticate_user(admin);
if (isAuthenticated == 0) {
keypad_t* keypad = get_keypad();
while(1) {
putty -> print_line(adminAccess);
char keyPressed = keypad -> get_debounced_key();
if (keyPressed == '1') {
putty -> print_line(openMsg);
lock_t* lock = get_solenoid_lock(1);
lock -> open();
timer -> delay(5000);
lock -> close();
} else if (keyPressed == '2') {
putty -> print_line(openMsg);
lock_t* lock = get_solenoid_lock(2);
lock -> open();
timer -> delay(5000);
lock -> close();
} else if (keyPressed == 'A') {
putty -> print_line(adminLogoutMsg);
timer -> delay(2000);
return;
} else if (keyPressed == 'B') {
handle_password_change(0);
}
putty -> print_line(clearDisplay);
}
}
}
<file_sep>/Sources/user_manager.c
/*
File: user_manager.c
Authors: <NAME> and <NAME>
Implementation of the user_manager.h header file
*/
#include "locker_module/display_timer.h"
#include "locker_module/solenoid_lock.h"
#include "locker_module/putty.h"
#include "user_manager.h"
#include "messages.h"
#include "access_manager.h"
void handle_user(locker_t* locker) {
putty_t* putty = get_putty();
int isAuthenticated = authenticate_user(locker);
if (isAuthenticated == 0) {
putty -> print_line(openMsg);
lock_t* lock = get_solenoid_lock(locker -> number);
lock -> open();
timer_t* timer = get_timer();
timer -> delay(10000);
lock -> close();
}
}
<file_sep>/Sources/locker_module/display_timer.h
/*
File: display_timer.h
Authors: <NAME> and <NAME>
This module is an abstraction for the flextimer module
and is used to represent a delay timer to be used by the
system. Delay times are given in milliseconds. The
module ensures that only a single instance of the timer
is created.
*/
#ifndef SOURCES_ABSTRACTION_LAYER_DISPLAY_TIMER_H_
#define SOURCES_ABSTRACTION_LAYER_DISPLAY_TIMER_H_
#include <stdint.h>
typedef struct timer_struct {
void (*delay) (int time);
} timer_t;
timer_t* get_timer();
#endif /* SOURCES_ABSTRACTION_LAYER_DISPLAY_TIMER_H_ */
<file_sep>/Sources/access_manager.h
/*
File: access_manager.h
Authors: <NAME> and <NAME>
The access manager module is responsible for getting
the combination from the user or admin and verifying
if the combination is correct. The module dispatches
commands to the speaker, and putty to provide feedback
to the user. The module also implements the logic to
change the password.
*/
#ifndef SOURCES_ACCESS_MANAGER_H_
#define SOURCES_ACCESS_MANAGER_H_
#include "locker_module/putty.h"
#include "locker.h"
int check_password(locker_t* locker, putty_t* putty);
int authenticate_user(locker_t* locker);
void change_password(locker_t* locker, putty_t* putty);
void handle_password_change();
#endif /* SOURCES_ACCESS_MANAGER_H_ */
<file_sep>/Sources/locker.c
/*
File: locker.c
Authors: <NAME> and <NAME>
Implementation of the locker.h header file
*/
#include "locker.h"
#include <stdlib.h>
static locker_t* locker1 = 0;
static locker_t* locker2 = 0;
static locker_t* admin = 0;
static int password1[3] = {<PASSWORD>};
static int password2[3] = {<PASSWORD>};
static int passworda[3] = {7, 18, 26};
int* get_password(int number) {
if (number == 1) {
return password1;
} else if (number == 2) {
return password2;
} else {
return passworda;
}
}
locker_t* get_locker(int number) {
if (number == 1) {
if(locker1 == 0) {
locker1 = (locker_t*) malloc(sizeof(locker_t));
locker1 -> number = number;
locker1 -> password = get_password(number);
}
return locker1;
} else if (number == 2){
if(locker2 == 0) {
locker2 = (locker_t*) malloc(sizeof(locker_t));
locker2 -> number = number;
locker2 -> password = get_password(number);
}
return locker2;
} else {
if(admin == 0) {
admin = (locker_t*) malloc(sizeof(locker_t));
admin -> number = number;
admin -> password = get_password(number);
}
return admin;
}
}
<file_sep>/Sources/locker_module/hardware_layer/flexTimer.h
/*
File: flexTimer.h
Author: <NAME>
This module is responsible to initialize the Flex Timer
FTM3 and use it to create a software delay.
The module permits the time in milliseconds to be entered
to configure the delay time.
*/
#ifndef SOURCES_LOCKER_MODULE_HARDWARE_LAYER_FLEXTIMER_H_
#define SOURCES_LOCKER_MODULE_HARDWARE_LAYER_FLEXTIMER_H_
void FTM0_OutComp_init();
void FTM0_OutComp_disable();
void FTM0_wait();
void FTM3_OutComp_init();
void FTM3_OutComp_disable();
void my_delay(int time);
#endif /* SOURCES_LOCKER_MODULE_HARDWARE_LAYER_FLEXTIMER_H_ */
<file_sep>/Sources/locker_module/display_timer.c
/*
File: display_timer.c
Authors: <NAME> and <NAME>
Implementation of the display_timer.h header file
*/
#include <stdlib.h>
#include "display_timer.h"
#include "hardware_layer/flexTimer.h"
static timer_t* this = 0;
void delay(int time) {
return my_delay(time);
}
timer_t* get_timer() {
if(this == 0) {
this = (timer_t*) malloc(sizeof(timer_t));
this -> delay = &delay;
}
return this;
}
<file_sep>/Sources/locker.h
/*
File: admin_manager.h
Authors: <NAME> and <NAME>
The locker module is a data structure that represent each
locker. The structure holds the reference for the password
and locker number. The administrator is also implemented
as a locker, but it is not assigned any specific locker
number.
*/
#ifndef SOURCES_LOCKER_H_
#define SOURCES_LOCKER_H_
typedef struct locker_struct {
int number;
int* password;
} locker_t;
locker_t* get_locker(int number);
#endif /* SOURCES_LOCKER_H_ */
<file_sep>/README.md
# elocker
a combination lock but it's a potentiometer.
<file_sep>/Sources/locker_module/hardware_layer/dac.c
/*
File: dac.c
Authors: <NAME> and <NAME>
Implementation of the dac.h header file
*/
#include "dac.h"
#include "MK64F12.h"
float sysClock = 20971520.00f;
/*
* This module initializes the DAC0 and the PIT0
*/
void dac_init() {
SIM_SCGC2 |= SIM_SCGC2_DAC0_MASK;
SIM_SCGC6 |= SIM_SCGC6_PIT_MASK;
DAC0_C0 |= DAC_C0_DACEN_MASK;
DAC0_C0 |= DAC_C0_DACRFS_MASK;
}
/*
* The combined DAC and PIT generates a sine wave at the
* frequency passed in Hz that lasts for the passed in time
* in microseconds.
*/
void dac_out(int frequency, float time) {
uint16_t index = 0;
PIT_MCR= 0x00;
float delay = (1000000.00f / frequency) / 1024.00f;
float clockPeriod = 1000000000.00f / sysClock;
PIT_LDVAL0 = (delay * 1000.00f) / clockPeriod - 1;
PIT_TCTRL0 |= PIT_TCTRL_TIE_MASK;
PIT_TCTRL0 |= PIT_TCTRL_TEN_MASK;
while(time > 0) {
while(PIT_TFLG(0) == 0); // wait for the interrupt
DAC0_DATL(0) = 0xFF & dac_data[index];
DAC0_DATH(0) = dac_data[index] >> 8;
index++;
if(index == 1024) index = 0;
time = time - delay;
PIT_TFLG0 |= PIT_TFLG_TIF_MASK; // clear interrupt flag
};
PIT_TCTRL0 ^= PIT_TCTRL_TEN_MASK; // disable the timer
}
<file_sep>/Sources/locker_module/hardware_layer/flexTimer.c
/*
File: flexTimer.c
Authors: <NAME> and <NAME>
Implementation of the flexTimer.h header file
*/
#include "MK64F12.h"
float SYSTEM_CLOCK = 20971520.00f;
/*
* Creates an output compare timer.
*/
void FTM3_OutComp_init() {
// Clock Enable for FTM3
SIM_SCGC3 |= SIM_SCGC3_FTM3_MASK;
// Port and Pin Configuration - PTD0
SIM_SCGC5 |= SIM_SCGC5_PORTD(1);
PORTD_PCR0 |= PORT_PCR_MUX(4);
float frequency = 1000.0f;
int mod = SYSTEM_CLOCK / frequency;
FTM3_MOD = mod;
FTM3_CNTIN = 0x0;
// Timer Configuration
FTM3_SC |= 0x0008 ; // Use system clock prescaled by 1
FTM3_C0SC |= (FTM_CnSC_ELSA(1) | FTM_CnSC_MSA(1));
}
void FTM3_OutComp_disable() {
FTM3_CNT = 0;
FTM3_SC |= FTM_SC_CLKS(0); // Disables clock
}
/*
* Creates a delay by time in milliseconds
*/
void my_delay(int time) {
// Create Timer
FTM3_OutComp_init();
int counter = time;
while (counter > 0) {
// Wait for clock overflow.
while(!(FTM3_SC & FTM_SC_TOF_MASK));
counter--;
int sc = FTM3_SC;
FTM3_SC ^= FTM_SC_TOF_MASK;
}
FTM3_OutComp_disable();
return;
}
<file_sep>/Sources/locker_module/putty.c
/*
File: putty.c
Authors: <NAME> and <NAME>
Implementation of the putty.h header file
*/
#include "putty.h"
static putty_t* this = 0;
void init_putty() {
uart_init();
}
void put_char(char character) {
uart_put_char(character);
}
void print_line(char* string) {
uart_put_string(string);
// Sends the new line character
uart_put_char('\r');
uart_put_char('\n');
}
void print_string(char* string) {
uart_put_string(string);
}
putty_t* get_putty() {
if(this == 0) {
init_putty();
this = (putty_t*) malloc(sizeof(putty_t));
this -> put_char = &put_char;
this -> print_line = &print_line;
this -> print_string = &print_string;
}
return this;
}
<file_sep>/Sources/locker_module/potentiometer.h
/*
File: potentiometer.h
Authors: <NAME> and <NAME>
This module is an abstraction for the potentiometer. The module
utilizes the adc module to retrieve the current value of
the potentiometer.The module ensures that only a single
instance of the potentiometer is created.
*/
#ifndef SOURCES_LOCKER_MODULE_POTENTIOMETER_H_
#define SOURCES_LOCKER_MODULE_POTENTIOMETER_H_
#include <stdlib.h>
#include "hardware_layer/adc.h"
typedef struct pot_struct {
uint8_t (*read_value) ();
} pot_t;
pot_t* get_pot();
#endif /* SOURCES_LOCKER_MODULE_POTENTIOMETER_H_ */
| 448fe2f411b5fa1d5c4b82a291dc9ab2ac2d2fdc | [
"Markdown",
"C"
] | 34 | C | tye-shutty/elocker | c1f5909f7d9116d8ce678c8bb7c1a40a9e96d24e | a6648df04dc77a3514eb8361aa91dada977efd14 |
refs/heads/master | <file_sep>#class definition for Dog class
class Dog
end
#create three dogs in local variables
fido = Dog.new
snoopy = Dog.new
lassie = Dog.new
| c53d0d58ae9aa66c275d163858a3afbe1e1ecb19 | [
"Ruby"
] | 1 | Ruby | machen2/classes-and-instances-lab-ruby-v-000 | dc0c702b7dec6f5c7ab36190f8d55e9e3d325407 | c23279633df98adb694a7ab72534bfbc712a3fb9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.