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 metaheuristics.generators; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import factory_method.FactoryGenerator; import metaheurictics.strategy.Strategy; import problem.definition.Problem.ProblemType; import problem.definition.State; public class MultiGenerator extends Generator { private GeneratorType Generatortype; private static Generator[] listGenerators = new Generator[GeneratorType.values().length]; public static List<State> listGeneratedPP = new ArrayList<State> (); public static Generator activeGenerator; public static List<State> listStateReference = new ArrayList<State>(); public void setGeneratortype(GeneratorType generatortype) { Generatortype = generatortype; } public MultiGenerator(){ super(); this.Generatortype = GeneratorType.MultiGenerator; } public static void destroyMultiGenerator(){ listGeneratedPP.clear(); //listGenerators.clear(); listStateReference.clear(); activeGenerator = null; listGenerators = null; } public static void initializeListGenerator()throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { listGenerators = new Generator[4]; Generator generator1 = new HillClimbing(); Generator generator2 = new EvolutionStrategies(); Generator generator3 = new LimitThreshold(); Generator generator4 = new GeneticAlgorithm(); listGenerators[0] = generator1; listGenerators[1] = generator2; listGenerators[2] = generator3; listGenerators[3] = generator4; } public static void initializeGenerators() throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { // Strategy.getStrategy().initializeGenerators(); initializeListGenerator(); State stateREF = new State(Strategy.getStrategy().getProblem().getState()); listStateReference.add(stateREF); for (int i = 0; i < listGenerators.length; i++) { if ((listGenerators[i].getType().equals(GeneratorType.HillClimbing)) || (listGenerators[i].getType().equals(GeneratorType.RandomSearch)) || (listGenerators[i].getType().equals(GeneratorType.TabuSearch)) || (listGenerators[i].getType().equals(GeneratorType.SimulatedAnnealing) || (listGenerators[i].getType().equals(GeneratorType.LimitThreshold)))){ listGenerators[i].setInitialReference(stateREF); } } createInstanceGeneratorsBPP(); Strategy.getStrategy().listStates = MultiGenerator.getListGeneratedPP(); FactoryGenerator ifFactoryGeneratorEE = new FactoryGenerator(); Generator generatorEE = ifFactoryGeneratorEE.createGenerator(GeneratorType.EvolutionStrategies); FactoryGenerator ifFactoryGeneratorGA = new FactoryGenerator(); Generator generatorGA = ifFactoryGeneratorGA.createGenerator(GeneratorType.GeneticAlgorithm); FactoryGenerator ifFactoryGeneratorEDA = new FactoryGenerator(); Generator generatorEDA = ifFactoryGeneratorEDA.createGenerator(GeneratorType.DistributionEstimationAlgorithm); for (int i = 0; i < MultiGenerator.getListGenerators().length; i++) { if(MultiGenerator.getListGenerators()[i].getType().equals(GeneratorType.EvolutionStrategies)){ MultiGenerator.getListGenerators()[i] = generatorEE; } if(MultiGenerator.getListGenerators()[i].getType().equals(GeneratorType.GeneticAlgorithm)){ MultiGenerator.getListGenerators()[i] = generatorGA; } if(MultiGenerator.getListGenerators()[i].getType().equals(GeneratorType.DistributionEstimationAlgorithm)){ MultiGenerator.getListGenerators()[i] = generatorEDA; } } /*InstanceGA instanceGA = new InstanceGA(); Thread threadGA = new Thread(instanceGA); InstanceEE instanceEE = new InstanceEE(); Thread threadEE = new Thread(instanceEE); InstanceDE instanceDE = new InstanceDE(); Thread threadDE = new Thread(instanceDE); threadGA.start(); threadEE.start(); threadDE.start(); boolean stop = false; while (stop == false){ if(instanceEE.isTerminate() == true && instanceGA.isTerminate() == true && instanceDE.isTerminate() == true) stop = true; }*/ } public static void createInstanceGeneratorsBPP() { // int i = 0; // boolean find = false; Generator generator = new RandomSearch(); // while (find == false) { // if (listGenerators[i].getType().equals(GeneratorType.RandomSearch)) { // generator = listGenerators[i]; // find = true; // } // else i++; // } int j = 0; while (j < EvolutionStrategies.countRef){ State stateCandidate; try { stateCandidate = generator.generate(1); Strategy.getStrategy().getProblem().Evaluate(stateCandidate); //stateCandidate.setEvaluation(stateCandidate.getEvaluation()); //stateCandidate = generator.generate(1); //Double evaluation = Strategy.getStrategy().getProblem().getFunction().get(0).Evaluation(stateCandidate); //stateCandidate.getEvaluation().set(0, evaluation); stateCandidate.setNumber(j); stateCandidate.setTypeGenerator(generator.getType()); listGeneratedPP.add(stateCandidate); } catch (Exception e) { e.printStackTrace(); } j++; } } private static ArrayList<State> getListGeneratedPP() { return (ArrayList<State>) listGeneratedPP; } public static Generator[] getListGenerators() { return listGenerators; } public static void setListGenerators(Generator[] listGenerators) { MultiGenerator.listGenerators = listGenerators; } public static Generator getActiveGenerator() { return activeGenerator; } public static void setActiveGenerator(Generator activeGenerator) { MultiGenerator.activeGenerator = activeGenerator; } public static void setListGeneratedPP(List<State> listGeneratedPP) { MultiGenerator.listGeneratedPP = listGeneratedPP; } @Override public State generate(Integer operatornumber) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { // TODO Auto-generated method stub Strategy.getStrategy().generator = roulette(); activeGenerator = Strategy.getStrategy().generator; activeGenerator.countGender++; State state = Strategy.getStrategy().generator.generate(1); return state; } @Override public State getReference() { // TODO Auto-generated method stub return null; } @Override public List<State> getReferenceList() { // TODO Auto-generated method stub return listStateReference; } @Override public List<State> getSonList() { // TODO Auto-generated method stub return null; } @Override public GeneratorType getType() { return this.Generatortype; } @Override public void setInitialReference(State stateInitialRef) { // TODO Auto-generated method stub } @Override public void updateReference(State stateCandidate, Integer countIterationsCurrent) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { // TODO Auto-generated method stub updateWeight(stateCandidate); tournament(stateCandidate, countIterationsCurrent); /*if(Strategy.getStrategy().getProblem().getTypeProblem().equals(ProblemType.Maximizar)){ if((stateCandidate.getEvaluation() > listStateReference.get(listStateReference.size() - 1).getEvaluation())) listStateReference.add(stateCandidate); else listStateReference.add(listStateReference.get(listStateReference.size() - 1)); } else{ if((Strategy.getStrategy().getProblem().getTypeProblem().equals(ProblemType.Minimizar)) && (stateCandidate.getEvaluation() < listStateReference.get(listStateReference.size() - 1).getEvaluation())) listStateReference.add(stateCandidate); else listStateReference.add(listStateReference.get(listStateReference.size() - 1)); } */ } public void updateWeight(State stateCandidate) { boolean search = searchState(stateCandidate);//premio por calidad. if(search == false) updateAwardImp(); else updateAwardSC(); } public boolean searchState(State stateCandidate) { if(Strategy.getStrategy().getProblem().getTypeProblem().equals(ProblemType.Maximizar)){ if(stateCandidate.getEvaluation().get(0) > Strategy.getStrategy().getBestState().getEvaluation().get(0)){ if(stateCandidate.getEvaluation().get(0) > Strategy.getStrategy().getBestState().getEvaluation().get(0)) activeGenerator.countBetterGender++; // System.out.println(activeGenerator.getType().toString() + activeGenerator.countBetterGender); // System.out.println(activeGenerator.countBetterGender); return true; } else return false; } else { if(stateCandidate.getEvaluation().get(0) < Strategy.getStrategy().getBestState().getEvaluation().get(0)){ if(stateCandidate.getEvaluation().get(0) < Strategy.getStrategy().getBestState().getEvaluation().get(0)) activeGenerator.countBetterGender++; // System.out.println(activeGenerator.getType().toString() + activeGenerator.countBetterGender); // System.out.println(activeGenerator.countBetterGender); return true; } else return false; } } @Override public float getWeight() { // TODO Auto-generated method stub return 0; } public Generator roulette() { float totalWeight = 0; for (int i = 0; i < listGenerators.length; i++) { totalWeight = listGenerators[i].getWeight() + totalWeight; } List<Float> listProb = new ArrayList<Float>(); for (int i = 0; i < listGenerators.length; i++) { float probF = listGenerators[i].getWeight() / totalWeight; listProb.add(probF); } List<LimitRoulette> listLimit = new ArrayList<LimitRoulette>(); float limitHigh = 0; float limitLow = 0; for (int i = 0; i < listProb.size(); i++) { LimitRoulette limitRoulette = new LimitRoulette(); limitHigh = listProb.get(i) + limitHigh; limitRoulette.setLimitHigh(limitHigh); limitRoulette.setLimitLow(limitLow); limitLow = limitHigh; limitRoulette.setGenerator(listGenerators[i]); listLimit.add(limitRoulette); } float numbAleatory = (float) (Math.random() * (double)(1)); boolean find = false; int i = 0; while ((find == false) && (i < listLimit.size())){ if((listLimit.get(i).getLimitLow() <= numbAleatory) && (numbAleatory <= listLimit.get(i).getLimitHigh())){ find = true; } else i++; } if (find) { return listLimit.get(i).getGenerator(); } else return listLimit.get(listLimit.size() - 1).getGenerator(); } @Override public boolean awardUpdateREF(State stateCandidate) { // TODO Auto-generated method stub return false; } @SuppressWarnings("static-access") public void updateAwardSC() { float weightLast = activeGenerator.getWeight(); float weightUpdate = (float) (weightLast * (1 - 0.1) + 10); activeGenerator.setWeight(weightUpdate); // activeGenerator.getTrace()getTrace().add(weightUpdate); for (int i = 0; i < listGenerators.length; i++) { if(listGenerators[i].equals(activeGenerator)) activeGenerator.getTrace()[Strategy.getStrategy().getCountCurrent()] = weightUpdate; else{ if(!listGenerators[i].getType().equals(Generatortype.MultiGenerator)){ float trace = listGenerators[i].getWeight(); listGenerators[i].getTrace() [Strategy.getStrategy().getCountCurrent()] = trace; } } } } @SuppressWarnings("static-access") public void updateAwardImp() { float weightLast = activeGenerator.getWeight(); float weightUpdate = (float) (weightLast * (1 - 0.1)); activeGenerator.setWeight(weightUpdate); // activeGenerator.getTrace().add(weightUpdate); for (int i = 0; i < listGenerators.length; i++) { if(listGenerators[i].equals(activeGenerator)) activeGenerator.getTrace()[Strategy.getStrategy().getCountCurrent()] = weightUpdate; else{ if(!listGenerators[i].getType().equals(Generatortype.MultiGenerator)){ float trace = listGenerators[i].getWeight(); listGenerators[i].getTrace() [Strategy.getStrategy().getCountCurrent()] = trace; } } } } @Override public void setWeight(float weight) { // TODO Auto-generated method stub } @Override public float[] getTrace() { // TODO Auto-generated method stub return null; } @SuppressWarnings("static-access") public void tournament(State stateCandidate,Integer countIterationsCurrent) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { State stateTem = new State(stateCandidate); for (int i = 0; i < MultiGenerator.getListGenerators().length; i++) { if(!listGenerators[i].getType().equals(Generatortype.MultiGenerator)) MultiGenerator.getListGenerators()[i].updateReference(stateTem, countIterationsCurrent); } } public Object clone(){ return this; } @Override public int[] getListCountBetterGender() { // TODO Auto-generated method stub return null; } @Override public int[] getListCountGender() { // TODO Auto-generated method stub return null; } } <file_sep>package factory_interface; import java.lang.reflect.InvocationTargetException; import metaheuristics.generators.Generator; import metaheuristics.generators.GeneratorType; public interface IFFactoryGenerator { Generator createGenerator(GeneratorType Generatortype)throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException ; } <file_sep>package factory_method; import java.lang.reflect.InvocationTargetException; public class FactoryLoader { public static Object getInstance(String className) throws ClassNotFoundException, IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{ @SuppressWarnings("rawtypes") Class c = null; try { c = Class.forName(className); } catch (ClassNotFoundException e) { System.out.println("El nombre de la clase no existe en el classpath"); e.printStackTrace(); } Object o = null; try { o = c.newInstance(); } catch (InstantiationException e) { System.out.println("Ha ocurrido un error al invocar el constructor de la clase"); e.printStackTrace(); } catch (IllegalAccessException e) { System.out.println("Esta clase no tiene constructores disponibles"); e.printStackTrace(); } return o; } } <file_sep>package factory_method; import java.lang.reflect.InvocationTargetException; import evolutionary_algorithms.complement.Crossover; import evolutionary_algorithms.complement.CrossoverType; import factory_interface.IFFactoryCrossover; public class FactoryCrossover implements IFFactoryCrossover { private Crossover crossing; public Crossover createCrossover(CrossoverType Crossovertype) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { String className = "evolutionary_algorithms.complement." + Crossovertype.toString(); crossing = (Crossover) FactoryLoader.getInstance(className); return crossing; } } <file_sep>package evolutionary_algorithms.complement; import java.util.List; import problem.definition.State; public abstract class Sampling { public abstract List<State> sampling (List<State> fathers, int countInd); } <file_sep>package local_search.acceptation_type; import metaheuristics.generators.*; import metaheurictics.strategy.*; import java.util.List; import java.util.Random; import problem.definition.State; public class AcceptMulticase extends AcceptableCandidate { @Override public Boolean acceptCandidate(State stateCurrent, State stateCandidate) { // TODO Auto-generated method stub Boolean accept = false; List<State> list = Strategy.getStrategy().listRefPoblacFinal; if(list.size() == 0){ list.add(stateCurrent.clone()); } Double T = MultiCaseSimulatedAnnealing.tinitial; double pAccept = 0; Random rdm = new Random(); Dominance dominance= new Dominance(); //Verificando si la solución candidata domina a la solución actual //Si la solución candidata domina a la solución actual if(dominance.dominance(stateCandidate, stateCurrent) == true){ //Se asigna como solución actual la solución candidata con probabilidad 1 pAccept = 1; } else if(dominance.dominance(stateCandidate, stateCurrent)== false){ if(DominanceCounter(stateCandidate, list) > 0){ pAccept = 1; } else if(DominanceRank(stateCandidate, list) == 0){ pAccept = 1; } else if(DominanceRank(stateCandidate, list) < DominanceRank(stateCurrent, list)){ pAccept = 1; } else if(DominanceRank(stateCandidate, list) == DominanceRank(stateCurrent, list)){ //Calculando la probabilidad de aceptación List<Double> evaluations = stateCurrent.getEvaluation(); double total = 0; for (int i = 0; i < evaluations.size()-1; i++) { Double evalA = evaluations.get(i); Double evalB = stateCandidate.getEvaluation().get(i); if (evalA != 0 && evalB != 0) { total += (evalA - evalB)/((evalA + evalB)/2); } } pAccept = Math.exp(-(1-total)/T); } else if (DominanceRank(stateCandidate, list) > DominanceRank(stateCurrent, list) && DominanceRank(stateCurrent, list)!= 0){ float value = DominanceRank(stateCandidate, list)/DominanceRank(stateCurrent, list); pAccept = Math.exp(-(value+1)/T); } else{ //Calculando la probabilidad de aceptación List<Double> evaluations = stateCurrent.getEvaluation(); double total = 0; for (int i = 0; i < evaluations.size()-1; i++) { Double evalA = evaluations.get(i); Double evalB = stateCandidate.getEvaluation().get(i); if (evalA != 0 && evalB != 0) { total += (evalA - evalB)/((evalA + evalB)/2); } } pAccept = Math.exp(-(1-total)/T); } } //Generar un número aleatorio if((rdm.nextFloat()) < pAccept){ stateCurrent = stateCandidate.clone(); //Verificando que la solución candidata domina a alguna de las soluciones accept = dominance.ListDominance(stateCandidate, list); } return accept; } private int DominanceCounter(State stateCandidate, List<State> list) { //chequea el número de soluciones de Pareto que son dominados por la nueva solución int counter = 0; for (int i = 0; i < list.size(); i++) { State solution = list.get(i); Dominance dominance = new Dominance(); if(dominance.dominance(stateCandidate, solution) == true) counter++; } return counter; } private int DominanceRank(State stateCandidate, List<State> list) { //calculando el número de soluciones en el conjunto de Pareto que dominan a la solución int rank = 0; for (int i = 0; i < list.size(); i++) { State solution = list.get(i); Dominance dominance = new Dominance(); if(dominance.dominance(solution, stateCandidate) == true){ rank++; } } return rank; } } <file_sep>package factory_interface; import java.lang.reflect.InvocationTargetException; import evolutionary_algorithms.complement.FatherSelection; import evolutionary_algorithms.complement.SelectionType; public interface IFFactoryFatherSelection { FatherSelection createSelectFather(SelectionType selectionType)throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException ; } <file_sep>package evolutionary_algorithms.complement; public class Range { private Probability data; private float max; private float min; public Probability getData() { return data; } public void setData(Probability data) { this.data = data; } public float getMax() { return max; } public void setMax(float max) { this.max = max; } public float getMin() { return min; } public void setMin(float min) { this.min = min; } } <file_sep>package metaheuristics.generators; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import local_search.acceptation_type.AcceptType; import local_search.acceptation_type.AcceptableCandidate; import local_search.candidate_type.CandidateType; import local_search.candidate_type.CandidateValue; import local_search.complement.StrategyType; import metaheurictics.strategy.Strategy; import problem.definition.State; import factory_interface.IFFactoryAcceptCandidate; import factory_method.FactoryAcceptCandidate; public class RandomSearch extends Generator { private CandidateValue candidatevalue; private AcceptType typeAcceptation; private StrategyType strategy; private CandidateType typeCandidate; private State stateReferenceRS; private IFFactoryAcceptCandidate ifacceptCandidate; private GeneratorType typeGenerator; private float weight; //para acceder desde los algoritmos basados en poblaciones de puntos public static List<State> listStateReference = new ArrayList<State>(); //problemas dinamicos public static int countGender = 0; public static int countBetterGender = 0; private int[] listCountBetterGender = new int[10]; private int[] listCountGender = new int[10]; private float[] listTrace = new float[1200000]; public RandomSearch() { super(); this.typeAcceptation = AcceptType.AcceptBest; this.strategy = StrategyType.NORMAL; this.typeCandidate = CandidateType.RandomCandidate; this.candidatevalue = new CandidateValue(); this.typeGenerator = GeneratorType.RandomSearch; this.weight = 50; listTrace[0] = this.weight; listCountBetterGender[0] = 0; listCountGender[0] = 0; listStateReference = new ArrayList<State>(); } @Override public State generate(Integer operatornumber) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { //ArrayList<State>list =new ArrayList<State>(); List<State> neighborhood = new ArrayList<State>(); neighborhood = Strategy.getStrategy().getProblem().getOperator().generateRandomState(operatornumber); State statecandidate = candidatevalue.stateCandidate(stateReferenceRS, typeCandidate, strategy, operatornumber, neighborhood); if(GeneticAlgorithm.countRef != 0 || EvolutionStrategies.countRef != 0 || DistributionEstimationAlgorithm.countRef != 0 || ParticleSwarmOptimization.countRef != 0) listStateReference.add(statecandidate); return statecandidate; } @Override public State getReference() { return stateReferenceRS; } @Override public void setInitialReference(State stateInitialRef) { this.stateReferenceRS = stateInitialRef; } @Override public void updateReference(State stateCandidate, Integer countIterationsCurrent) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { ifacceptCandidate = new FactoryAcceptCandidate(); AcceptableCandidate candidate = ifacceptCandidate.createAcceptCandidate(typeAcceptation); Boolean accept = candidate.acceptCandidate(stateReferenceRS, stateCandidate); if(accept.equals(true)) stateReferenceRS = stateCandidate; // getReferenceList(); } @Override public GeneratorType getType() { return this.typeGenerator; } public GeneratorType getTypeGenerator() { return typeGenerator; } public void setTypeGenerator(GeneratorType typeGenerator) { this.typeGenerator = typeGenerator; } @Override public List<State> getReferenceList() { listStateReference.add(stateReferenceRS); return listStateReference; } @Override public List<State> getSonList() { // TODO Auto-generated method stub return null; } @Override public boolean awardUpdateREF(State stateCandidate) { // TODO Auto-generated method stub return false; } @Override public float getWeight() { // TODO Auto-generated method stub return this.weight; } @Override public void setWeight(float weight) { // TODO Auto-generated method stub this.weight = weight; } @Override public int[] getListCountBetterGender() { // TODO Auto-generated method stub return this.listCountBetterGender; } @Override public int[] getListCountGender() { // TODO Auto-generated method stub return this.listCountGender; } @Override public float[] getTrace() { // TODO Auto-generated method stub return this.listTrace; } } <file_sep>package evolutionary_algorithms.complement; public class Probability { private Object key; private Object value; private float probability; public float getProbability() { return probability; } public void setProbability(float probability) { this.probability = probability; } public Object getKey() { return key; } public void setKey(Object key) { this.key = key; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } } <file_sep>package metaheuristics.generators; import factory_method.FactoryGenerator; public class InstanceEE implements Runnable { private boolean terminate = false; public void run() { FactoryGenerator ifFactoryGenerator = new FactoryGenerator(); Generator generatorEE = null; try { generatorEE = ifFactoryGenerator.createGenerator(GeneratorType.EvolutionStrategies); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } boolean find = false; int i = 0; while (find == false) { if(MultiGenerator.getListGenerators()[i].getType().equals(GeneratorType.EvolutionStrategies)){ MultiGenerator.getListGenerators()[i] = generatorEE; find = true; } else i++; } terminate = true; } public boolean isTerminate() { return terminate; } public void setTerminate(boolean terminate) { this.terminate = terminate; } } <file_sep>package evolutionary_algorithms.complement; import java.util.List; import problem.definition.State; public abstract class FatherSelection { public abstract List<State> selection(List<State> listState, int truncation); } <file_sep>package metaheuristics.generators; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import factory_interface.IFFactoryAcceptCandidate; import factory_method.FactoryAcceptCandidate; import problem.definition.State; import local_search.acceptation_type.AcceptType; import local_search.acceptation_type.AcceptableCandidate; import local_search.candidate_type.CandidateType; import local_search.candidate_type.CandidateValue; import local_search.complement.StrategyType; import metaheurictics.strategy.Strategy; public class MultiobjectiveHillClimbingRestart extends Generator{ protected CandidateValue candidatevalue; protected AcceptType typeAcceptation; protected StrategyType strategy; protected CandidateType typeCandidate; protected State stateReferenceHC; protected IFFactoryAcceptCandidate ifacceptCandidate; protected GeneratorType Generatortype; protected List<State> listStateReference = new ArrayList<State>(); protected float weight; protected List<Float> listTrace = new ArrayList<Float>(); private List<State> visitedState = new ArrayList<State>(); public static int sizeNeighbors; public MultiobjectiveHillClimbingRestart() { super(); this.typeAcceptation = AcceptType.AcceptNotDominated; this.strategy = StrategyType.NORMAL; //Problem problem = Strategy.getStrategy().getProblem(); this.typeCandidate = CandidateType.NotDominatedCandidate; this.candidatevalue = new CandidateValue(); this.Generatortype = GeneratorType.MultiobjectiveHillClimbingRestart; this.weight = 50; listTrace.add(weight); } @Override public State generate(Integer operatornumber) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { List<State> neighborhood = new ArrayList<State>(); neighborhood = Strategy.getStrategy().getProblem().getOperator().generatedNewState(stateReferenceHC, operatornumber); State statecandidate = candidatevalue.stateCandidate(stateReferenceHC, typeCandidate, strategy, operatornumber, neighborhood); return statecandidate; } @Override public void updateReference(State stateCandidate, Integer countIterationsCurrent) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { //Agregando la primera solución a la lista de soluciones no dominadas if(Strategy.getStrategy().listRefPoblacFinal.size() == 0){ Strategy.getStrategy().listRefPoblacFinal.add(stateReferenceHC.clone()); } ifacceptCandidate = new FactoryAcceptCandidate(); AcceptableCandidate candidate = ifacceptCandidate.createAcceptCandidate(typeAcceptation); State lastState = Strategy.getStrategy().listRefPoblacFinal.get(Strategy.getStrategy().listRefPoblacFinal.size()-1); List<State> neighborhood = new ArrayList<State>(); neighborhood = Strategy.getStrategy().getProblem().getOperator().generatedNewState(stateReferenceHC, sizeNeighbors); int i= 0; Boolean accept = candidate.acceptCandidate(lastState, stateCandidate.clone()); if(accept.equals(true)){ stateReferenceHC = stateCandidate.clone(); visitedState = new ArrayList<State>(); lastState = stateCandidate.clone(); //tomar xc q pertenesca a la vecindad de xa } else{ boolean stop = false; while (i < neighborhood.size()&& stop==false) { if (Contain(neighborhood.get(i))==false) { stateCandidate = neighborhood.get(i); Strategy.getStrategy().getProblem().Evaluate(stateCandidate); visitedState.add(stateCandidate); accept = candidate.acceptCandidate(lastState, stateCandidate.clone()); stop=true; } i++; } while (stop == false) { stateCandidate = Strategy.getStrategy().getProblem().getOperator().generateRandomState(1).get(0); if (Contain(stateCandidate)==false) { Strategy.getStrategy().getProblem().Evaluate(stateCandidate); stop=true; accept = candidate.acceptCandidate(lastState, stateCandidate.clone()); } } if(accept.equals(true)){ stateReferenceHC = stateCandidate.clone(); visitedState = new ArrayList<State>(); lastState = stateCandidate.clone(); //tomar xc q pertenesca a la vecindad de xa } } getReferenceList(); } @Override public List<State> getReferenceList() { listStateReference.add(stateReferenceHC.clone()); return listStateReference; } @Override public State getReference() { return stateReferenceHC; } public void setStateRef(State stateRef) { this.stateReferenceHC = stateRef; } @Override public void setInitialReference(State stateInitialRef) { this.stateReferenceHC = stateInitialRef; } public GeneratorType getGeneratorType() { return Generatortype; } public void setGeneratorType(GeneratorType Generatortype) { this.Generatortype = Generatortype; } @Override public GeneratorType getType() { return this.Generatortype; } @Override public List<State> getSonList() { // TODO Auto-generated method stub return null; } private boolean Contain(State state){ boolean found = false; for (Iterator<State> iter = visitedState.iterator(); iter.hasNext();) { State element = (State) iter.next(); if(element.Comparator(state)==true){ found = true; } } return found; } @Override public boolean awardUpdateREF(State stateCandidate) { // TODO Auto-generated method stub return false; } @Override public float getWeight() { // TODO Auto-generated method stub return 0; } @Override public void setWeight(float weight) { // TODO Auto-generated method stub } @Override public float[] getTrace() { // TODO Auto-generated method stub return null; } @Override public int[] getListCountBetterGender() { // TODO Auto-generated method stub return null; } @Override public int[] getListCountGender() { // TODO Auto-generated method stub return null; } } <file_sep>package factory_interface; import java.lang.reflect.InvocationTargetException; import problem.extension.SolutionMethod; import problem.extension.TypeSolutionMethod; public interface IFFactorySolutionMethod { SolutionMethod createdSolutionMethod(TypeSolutionMethod method) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException ; } <file_sep>package metaheuristics.generators; import java.lang.reflect.InvocationTargetException; import java.util.List; import problem.definition.State; public abstract class Generator { public abstract State generate(Integer operatornumber) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException; public abstract void updateReference(State stateCandidate, Integer countIterationsCurrent) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException; public abstract State getReference(); public abstract void setInitialReference (State stateInitialRef); public abstract GeneratorType getType (); public abstract List<State> getReferenceList(); public abstract List<State> getSonList (); public abstract boolean awardUpdateREF(State stateCandidate); public abstract void setWeight(float weight); public abstract float getWeight(); public abstract float[] getTrace(); public int countGender; public int countBetterGender; public abstract int[] getListCountBetterGender(); public abstract int[] getListCountGender(); public int[] listCountBetterGender; // arreglo con las mejoras de cada generador en un periodo de 10, acumulativo } <file_sep>package problem.definition; import java.util.ArrayList; import metaheuristics.generators.GeneratorType; public class State { protected GeneratorType typeGenerator; protected ArrayList<Double> evaluation; protected int number; protected ArrayList<Object> code; public State(State ps) { typeGenerator = ps.getTypeGenerator(); evaluation = ps.getEvaluation(); number = ps.getNumber(); code = new ArrayList<Object>(ps.getCode()); } public State(ArrayList<Object> code) { super(); this.code = code; } public State() { code=new ArrayList<Object>(); } public ArrayList<Object> getCode() { return code; } public void setCode(ArrayList<Object> listCode) { this.code = listCode; } public GeneratorType getTypeGenerator() { return typeGenerator; } public void setTypeGenerator(GeneratorType typeGenerator) { this.typeGenerator = typeGenerator; } public ArrayList<Double> getEvaluation() { return evaluation; } public void setEvaluation(ArrayList<Double> evaluation) { this.evaluation = evaluation; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public State clone(){ return this; } public Object getCopy(){ return new State(this.getCode()); } public boolean Comparator(State state){ boolean result=false; if(state.getCode().equals(getCode())){ result=true; } return result; } public double Distance(State state){ double distancia = 0; for (int i = 0; i < state.getCode().size(); i++) { if (!(state.getCode().get(i).equals(this.getCode().get(i)))) { distancia++; } } return distancia; } } <file_sep>/** * @(#) FactoryAcceptCandidate.java */ package factory_method; import java.lang.reflect.InvocationTargetException; import local_search.acceptation_type.AcceptType; import local_search.acceptation_type.AcceptableCandidate; import factory_interface.IFFactoryAcceptCandidate; public class FactoryAcceptCandidate implements IFFactoryAcceptCandidate{ private AcceptableCandidate acceptCandidate; public AcceptableCandidate createAcceptCandidate( AcceptType typeacceptation ) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{ String className = "local_search.acceptation_type." + typeacceptation.toString(); acceptCandidate = (AcceptableCandidate) FactoryLoader.getInstance(className); return acceptCandidate; } } <file_sep>package local_search.acceptation_type; import java.lang.reflect.InvocationTargetException; import problem.definition.State; public abstract class AcceptableCandidate { public abstract Boolean acceptCandidate(State stateCurrent, State stateCandidate) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException ; } <file_sep>package evolutionary_algorithms.complement; public enum MutationType { TowPointsMutation, OnePointMutation, AIOMutation; } <file_sep>package evolutionary_algorithms.complement; import java.util.ArrayList; import java.util.List; import metaheuristics.generators.LimitRoulette; import problem.definition.State; public class RouletteSelection extends FatherSelection { @Override public List<State> selection(List<State> listState, int truncation) {/* List<State> fatherList = new ArrayList<State>(); double total = 0; double sum = 0; for (int i = 0; i < listState.size(); i++) { total = total + listState.get(i).getEvaluation().get(0); } double number = (double) Math.random() * (double)(total); for (int i = 0; i < listState.size(); i++) { sum = sum + listState.get(i).getEvaluation().get(0); if(sum >= number) fatherList.add(listState.get(i)); } return fatherList; */ float totalWeight = 0; for (int i = 0; i < listState.size(); i++) { totalWeight = (float) (listState.get(i).getEvaluation().get(0) + totalWeight); } List<Float> listProb = new ArrayList<Float>(); for (int i = 0; i < listState.size(); i++) { float probF = (float) (listState.get(i).getEvaluation().get(0) / totalWeight); listProb.add(probF); } List<LimitRoulette> listLimit = new ArrayList<LimitRoulette>(); float limitHigh = 0; float limitLow = 0; for (int i = 0; i < listProb.size(); i++) { LimitRoulette limitRoulette = new LimitRoulette(); limitHigh = listProb.get(i) + limitHigh; limitRoulette.setLimitHigh(limitHigh); limitRoulette.setLimitLow(limitLow); limitLow = limitHigh; // limitRoulette.setGenerator(listGenerators.get(i)); listLimit.add(limitRoulette); } List<State> fatherList = new ArrayList<State>(); for (int j = 0; j < listState.size(); j++) { float numbAleatory = (float) (Math.random() * (double)(1)); boolean find = false; int i = 0; while ((find == false) && (i < listLimit.size())){ if((listLimit.get(i).getLimitLow() <= numbAleatory) && (numbAleatory <= listLimit.get(i).getLimitHigh())){ find = true; fatherList.add(listState.get(i)); } else i++; } } return fatherList; } } <file_sep>package metaheuristics.generators; public enum GeneratorType { HillClimbing, TabuSearch, SimulatedAnnealing, RandomSearch, LimitThreshold, HillClimbingRestart, //un punto GeneticAlgorithm, EvolutionStrategies, DistributionEstimationAlgorithm, ParticleSwarmOptimization, //poblaciones de puntos MultiGenerator, MultiobjectiveTabuSearch, MultiobjectiveStochasticHillClimbing,MultiCaseSimulatedAnnealing, MultiobjectiveHillClimbingRestart, MultiobjectiveHillClimbingDistance; //mutiobjetivos } <file_sep>package metaheuristics.generators; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import factory_interface.IFFactoryAcceptCandidate; import factory_method.FactoryAcceptCandidate; import local_search.acceptation_type.AcceptType; import local_search.acceptation_type.AcceptableCandidate; import local_search.candidate_type.CandidateType; import local_search.candidate_type.CandidateValue; import local_search.complement.StrategyType; import metaheurictics.strategy.Strategy; import problem.definition.State; import problem.definition.Problem.ProblemType; public class HillClimbingRestart extends Generator{ public static int count; public static int countCurrent; private List<State> listRef = new ArrayList<State>(); protected CandidateValue candidatevalue; protected AcceptType typeAcceptation; protected StrategyType strategy; protected CandidateType typeCandidate; protected State stateReferenceHC; protected IFFactoryAcceptCandidate ifacceptCandidate; protected GeneratorType Generatortype; protected List<State> listStateReference = new ArrayList<State>(); protected float weight; //problemas dinamicos public static int countGender = 0; public static int countBetterGender = 0; private int[] listCountBetterGender = new int[10]; private int[] listCountGender = new int[10]; private float[] listTrace = new float[1200000]; public HillClimbingRestart() { super(); // countIterations = Strategy.getStrategy().getCountCurrent(); // countSame = 1; countCurrent = count; this.typeAcceptation = AcceptType.AcceptBest; this.strategy = StrategyType.NORMAL; if(Strategy.getStrategy().getProblem().getTypeProblem().equals(ProblemType.Maximizar)) { this.typeCandidate = CandidateType.GreaterCandidate; } else{ this.typeCandidate = CandidateType.SmallerCandidate; } this.candidatevalue = new CandidateValue(); this.Generatortype = GeneratorType.HillClimbing; this.weight = 50; listTrace[0] = this.weight; listCountBetterGender[0] = 0; listCountGender[0] = 0; } public State generate (Integer operatornumber) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { //ArrayList<State>list=new ArrayList<State>(); State statecandidate = new State(); if(count == Strategy.getStrategy().getCountCurrent()){ State stateR = new State(stateReferenceHC); listRef.add(stateR); stateReferenceHC = Strategy.getStrategy().getProblem().getOperator().generateRandomState(1).get(0); Strategy.getStrategy().getProblem().Evaluate(stateReferenceHC); count = count + countCurrent; } List<State> neighborhood = Strategy.getStrategy().getProblem().getOperator().generatedNewState(stateReferenceHC, operatornumber); statecandidate = candidatevalue.stateCandidate(stateReferenceHC, typeCandidate, strategy, operatornumber, neighborhood); //list.add(statecandidate); return statecandidate; } @Override public void updateReference(State stateCandidate, Integer countIterationsCurrent) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { // TODO Auto-generated method stub ifacceptCandidate = new FactoryAcceptCandidate(); AcceptableCandidate candidate = ifacceptCandidate.createAcceptCandidate(typeAcceptation); Boolean accept = candidate.acceptCandidate(stateReferenceHC, stateCandidate); if(accept.equals(true)) stateReferenceHC = stateCandidate; // getReferenceList(); } @Override public List<State> getReferenceList() { listStateReference.add(stateReferenceHC); return listStateReference; } @Override public State getReference() { return stateReferenceHC; } public void setStateRef(State stateRef) { this.stateReferenceHC = stateRef; } @Override public void setInitialReference(State stateInitialRef) { this.stateReferenceHC = stateInitialRef; } public GeneratorType getGeneratorType() { return Generatortype; } public void setGeneratorType(GeneratorType Generatortype) { this.Generatortype = Generatortype; } @Override public GeneratorType getType() { return this.Generatortype; } @Override public List<State> getSonList() { // TODO Auto-generated method stub return null; } public void setTypeCandidate(CandidateType typeCandidate){ this.typeCandidate = typeCandidate; } @Override public boolean awardUpdateREF(State stateCandidate) { // TODO Auto-generated method stub return false; } @Override public float getWeight() { // TODO Auto-generated method stub return 0; } @Override public void setWeight(float weight) { // TODO Auto-generated method stub } /*public State generate2(Integer operatornumber) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { State statecandidate = new State(); countIterations = Strategy.getStrategy().getCountCurrent(); if (countIterations>0){ if(Strategy.getStrategy().Statistics.getbestListStates().get(countIterations)==Strategy.getStrategy().Statistics.getbestListStates().get(countIterations-1)){ countSame++; if(countSame == count-1){ State stateR = new State(stateReferenceHC); listRef.add(stateR); stateReferenceHC = Strategy.getStrategy().getProblem().getOperator().generateRandomState(1).get(0); } } else countSame = 1; } List<State> neighborhood = Strategy.getStrategy().getProblem().getOperator().generatedNewState(stateReferenceHC, operatornumber); statecandidate = candidatevalue.stateCandidate(stateReferenceHC, typeCandidate, strategy, operatornumber, neighborhood); return statecandidate; } */ @Override public int[] getListCountBetterGender() { // TODO Auto-generated method stub return this.listCountBetterGender; } @Override public int[] getListCountGender() { // TODO Auto-generated method stub return this.listCountGender; } @Override public float[] getTrace() { // TODO Auto-generated method stub return this.listTrace; } } <file_sep>package factory_method; import java.lang.reflect.InvocationTargetException; import evolutionary_algorithms.complement.Mutation; import evolutionary_algorithms.complement.MutationType; import factory_interface.IFFactoryMutation; public class FactoryMutation implements IFFactoryMutation { private Mutation mutation; public Mutation createMutation(MutationType typeMutation) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { String className = "evolutionary_algorithms.complement." + typeMutation.toString(); mutation = (Mutation) FactoryLoader.getInstance(className); return mutation; } } <file_sep>/** * @(#) IFFactoryCandidate.java */ package factory_interface; import java.lang.reflect.InvocationTargetException; import local_search.candidate_type.CandidateType; import local_search.candidate_type.SearchCandidate; public interface IFFactoryCandidate { SearchCandidate createSearchCandidate(CandidateType typeCandidate) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException; } <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>BiCIAM</groupId> <artifactId>BiCIAM</artifactId> <version>0.0.1-SNAPSHOT</version> <name>BiCIAM-Maven</name> <description>Java library for metaheuristics</description> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <sonar.exclusions> *.class </sonar.exclusions> </properties> <build> <sourceDirectory>${basedir}</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>windows-1252</encoding> </configuration> </plugin> <plugin> <groupId>org.sonarsource.scanner.maven</groupId> <artifactId>sonar-maven-plugin</artifactId> <version>3.5.0.1254</version> </plugin> </plugins> </build> </project><file_sep>package evolutionary_algorithms.complement; import java.lang.reflect.InvocationTargetException; import java.util.List; import problem.definition.State; public class GenerationalReplace extends Replace { @Override public List<State> replace(State stateCandidate, List<State> listState) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { listState.remove(0); listState.add(stateCandidate); /*List<State> sonList = Strategy.getStrategy().generator.getSonList(); for (int i = 0; i < listState.size(); i++) { listState.set(i, sonList.get(i)); }*/ return listState; } } <file_sep>package evolutionary_algorithms.complement; public enum SamplingType { ProbabilisticSampling; } <file_sep>/** * @(#) Strategy.java */ package local_search.complement; public enum StrategyType { TABU, NORMAL; } <file_sep>/** * @(#) SearchCandidate.java */ package local_search.candidate_type; import java.lang.reflect.InvocationTargetException; import java.util.List; import problem.definition.State; public abstract class SearchCandidate { public abstract State stateSearch(List<State> listNeighborhood) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException ; } <file_sep>package evolutionary_algorithms.complement; import metaheurictics.strategy.Strategy; import problem.definition.State; public class TowPointsMutation extends Mutation { /*@Override public ProblemState mutation(SortedMap<Object, Object> newind, double PM) { int pos1 = (int) (Math.random() * (int)Problem.countvariable); int pos2 = (int) (Math.random() * (int)Problem.countvariable); Object value1 = (Integer)(newind.get("x" + pos1)); Object value2 = (Integer)(newind.get("x" + pos2)); newind.put("x" + pos1, value2); newind.put("x" + pos2, value1); return newind; }*/ @Override public State mutation(State newind, double PM) { Object key1 = Strategy.getStrategy().getProblem().getCodification().getAleatoryKey(); Object key2 = Strategy.getStrategy().getProblem().getCodification().getAleatoryKey(); Object value1 = Strategy.getStrategy().getProblem().getCodification().getVariableAleatoryValue((Integer) key1); Object value2 = Strategy.getStrategy().getProblem().getCodification().getVariableAleatoryValue((Integer) key2); newind.getCode().set((Integer) key1, (Integer)value2); newind.getCode().set((Integer) key2, (Integer)value1); return newind; } } <file_sep>package factory_method; import java.lang.reflect.InvocationTargetException; import evolutionary_algorithms.complement.Replace; import evolutionary_algorithms.complement.ReplaceType; import factory_interface.IFFactoryReplace; public class FactoryReplace implements IFFactoryReplace { private Replace replace; public Replace createReplace( ReplaceType typereplace ) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{ String className = "evolutionary_algorithms.complement." + typereplace.toString(); replace = (Replace) FactoryLoader.getInstance(className); return replace; } } <file_sep>package evolutionary_algorithms.complement; import problem.definition.State; public abstract class Crossover { public abstract State crossover(State father1, State father2, double PC); } <file_sep>package problem.definition; import java.util.List; public abstract class Operator { public abstract List<State> generatedNewState(State stateCurrent, Integer operatornumber); public abstract List<State> generateRandomState (Integer operatornumber); } <file_sep>package metaheuristics.generators; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import local_search.acceptation_type.AcceptType; import local_search.acceptation_type.AcceptableCandidate; import local_search.candidate_type.CandidateType; import local_search.candidate_type.CandidateValue; import local_search.complement.StrategyType; import metaheurictics.strategy.Strategy; import problem.definition.State; import factory_interface.IFFactoryAcceptCandidate; import factory_method.FactoryAcceptCandidate; public class SimulatedAnnealing extends Generator { private CandidateValue candidatevalue; private AcceptType typeAcceptation; private StrategyType strategy; private CandidateType typeCandidate; private State stateReferenceSA; private IFFactoryAcceptCandidate ifacceptCandidate; public static Double alpha; public static Double tinitial; public static Double tfinal; public static int countIterationsT; private int countRept; private GeneratorType typeGenerator; private List<State> listStateReference = new ArrayList<State>(); private float weight; //problemas dinamicos public static int countGender = 0; public static int countBetterGender = 0; private int[] listCountBetterGender = new int[10]; private int[] listCountGender = new int[10]; private float[] listTrace = new float[1200000]; public GeneratorType getTypeGenerator() { return typeGenerator; } public void setTypeGenerator(GeneratorType typeGenerator) { this.typeGenerator = typeGenerator; } public SimulatedAnnealing(){ super(); /*SimulatedAnnealing.alpha = 0.93; SimulatedAnnealing.tinitial = 250.0; SimulatedAnnealing.tfinal = 41.66; SimulatedAnnealing.countIterationsT = 50;*/ this.typeAcceptation = AcceptType.AcceptNotBadT; this.strategy = StrategyType.NORMAL; this.typeCandidate = CandidateType.RandomCandidate; this.candidatevalue = new CandidateValue(); this.typeGenerator = GeneratorType.SimulatedAnnealing; this.weight = 50; listTrace[0] = this.weight; listCountBetterGender[0] = 0; listCountGender[0] = 0; } @Override public State generate(Integer operatornumber) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { //<State>list=new ArrayList<State>(); List<State> neighborhood = new ArrayList<State>(); neighborhood = Strategy.getStrategy().getProblem().getOperator().generatedNewState(stateReferenceSA, operatornumber); State statecandidate = candidatevalue.stateCandidate(stateReferenceSA, typeCandidate, strategy, operatornumber, neighborhood); // list.add(statecandidate); return statecandidate; } @Override public State getReference() { return stateReferenceSA; } public void setStateRef(State stateRef) { this.stateReferenceSA = stateRef; } @Override public void setInitialReference(State stateInitialRef) { this.stateReferenceSA = stateInitialRef; } @Override public void updateReference(State stateCandidate, Integer countIterationsCurrent)throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { countRept = countIterationsT; ifacceptCandidate = new FactoryAcceptCandidate(); AcceptableCandidate candidate = ifacceptCandidate.createAcceptCandidate(typeAcceptation); Boolean accept = candidate.acceptCandidate(stateReferenceSA, stateCandidate); if(accept.equals(true)) stateReferenceSA = stateCandidate; if(countIterationsCurrent.equals(countIterationsT)){ tinitial = tinitial * alpha; countIterationsT = countIterationsT + countRept; } // getReferenceList(); } @Override public GeneratorType getType() { return this.typeGenerator; } @Override public List<State> getReferenceList() { listStateReference.add(stateReferenceSA); return listStateReference; } @Override public List<State> getSonList() { // TODO Auto-generated method stub return null; } @Override public boolean awardUpdateREF(State stateCandidate) { // TODO Auto-generated method stub return false; } @Override public float getWeight() { // TODO Auto-generated method stub return this.weight; } @Override public void setWeight(float weight) { // TODO Auto-generated method stub this.weight = weight; } @Override public int[] getListCountBetterGender() { // TODO Auto-generated method stub return this.listCountBetterGender; } @Override public int[] getListCountGender() { // TODO Auto-generated method stub return this.listCountGender; } @Override public float[] getTrace() { // TODO Auto-generated method stub return this.listTrace; } } <file_sep>package local_search.acceptation_type; import java.util.List; import metaheurictics.strategy.Strategy; import metaheuristics.generators.GeneratorType; import metaheuristics.generators.MultiobjectiveHillClimbingDistance; import problem.definition.Problem.ProblemType; import problem.definition.State; public class Dominance { //---------------------------------Métodos que se utilizan en los algoritmos multiobjetivo-------------------------------------------------------// //Función que determina si la solución X domina a alguna de las soluciones no dominadas de una lista //Devuelve la lista actualizada y true si fue adicionada a la lista o false de lo contrario public boolean ListDominance(State solutionX, List<State> list){ boolean domain = false; for (int i = 0; i < list.size() && domain == false; i++) { //Si la solución X domina a la solución de la lista if(dominance(solutionX, list.get(i)) == true){ //Se elimina el elemento de la lista list.remove(i); if (i!=0) { i--; } if (Strategy.getStrategy().generator.getType().equals(GeneratorType.MultiobjectiveHillClimbingDistance)&&list.size()!=0) { MultiobjectiveHillClimbingDistance.DistanceCalculateAdd(list); } } if (list.size()>0) { if(dominance(list.get(i), solutionX) == true){ domain = true; } } } //Si la solución X no fue dominada if(domain == false){ //Comprobando que la solución no exista boolean found = false; for (int k = 0; k < list.size() && found == false; k++) { State element = list.get(k); found = solutionX.Comparator(element); } //Si la solución no existe if(found == false){ //Se guarda la solución candidata en la lista de soluciones óptimas de Pareto list.add(solutionX.clone()); if (Strategy.getStrategy().generator.getType().equals(GeneratorType.MultiobjectiveHillClimbingDistance)) { MultiobjectiveHillClimbingDistance.DistanceCalculateAdd(list); } return true; } } return false; /*boolean domain = false; List<State> deletedSolution = new ArrayList<State>(); for (int i = 0; i < list.size() && domain == false; i++) { State element = list.get(i); //Si la solución X domina a la solución de la lista if(dominance(solutionX, element) == true){ //Se elimina el elemento de la lista deletedSolution.add(element); } if(dominance(element, solutionX) == true){ domain = true; } } //Si la solución X no fue dominada if(domain == false){ //Comprobando que la solución no exista boolean found = false; for (int k = 0; k < list.size() && found == false; k++) { State element = list.get(k); found = solutionX.Comparator(element); } //Si la solución no existe if(found == false){ //Se eliminan de la lista de soluciones optimas de pareto aquellas que fueron dominadas por la solución candidata list.removeAll(deletedSolution); //Se guarda la solución candidata en la lista de soluciones óptimas de Pareto list.add(solutionX.clone()); if(Strategy.getStrategy().getProblem()!= null){ Strategy.getStrategy().listRefPoblacFinal = list; } return true; } } return false;*/ } //Función que devuelve true si solutionX domina a solutionY public boolean dominance(State solutionX, State solutionY) { boolean dominance = false; int countBest = 0; int countEquals = 0; //Si solutionX domina a solutionY if(Strategy.getStrategy().getProblem().getTypeProblem().equals(ProblemType.Maximizar)) { //Recorriendo las evaluaciones de las funciones objetivo for (int i = 0; i < solutionX.getEvaluation().size(); i++) { if(solutionX.getEvaluation().get(i).floatValue() > solutionY.getEvaluation().get(i).floatValue()){ countBest++; } if(solutionX.getEvaluation().get(i).floatValue() == solutionY.getEvaluation().get(i).floatValue()){ countEquals++; } } } else{ //Recorriendo las evaluaciones de las funciones objetivo for (int i = 0; i < solutionX.getEvaluation().size(); i++) { if(solutionX.getEvaluation().get(i).floatValue() < solutionY.getEvaluation().get(i).floatValue()){ countBest++; } if(solutionX.getEvaluation().get(i).floatValue() == solutionY.getEvaluation().get(i).floatValue()){ countEquals++; } } } if((countBest >= 1) && (countEquals + countBest == solutionX.getEvaluation().size())) { dominance = true; } return dominance; } } <file_sep>/** * @(#) CandidateValue.java */ package local_search.candidate_type; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import problem.definition.State; import local_search.complement.StrategyType; import local_search.complement.TabuSolutions; import metaheurictics.strategy.Strategy; //import ceis.grial.problem.Problem; import factory_interface.IFFactoryCandidate; import factory_method.FactoryCandidate; public class CandidateValue { @SuppressWarnings("unused") private StrategyType strategy; private IFFactoryCandidate ifFactory; @SuppressWarnings("unused") private CandidateType typecand; private TabuSolutions tabusolution; private SearchCandidate searchcandidate; public CandidateValue(){} public CandidateValue(StrategyType strategy, IFFactoryCandidate ifFactory, CandidateType typecand, TabuSolutions tabusolution, SearchCandidate searchcandidate) { //, Strategy executegenerator super(); this.strategy = strategy; this.ifFactory = ifFactory; this.typecand = typecand; this.tabusolution = tabusolution; this.searchcandidate = searchcandidate; } public SearchCandidate newSearchCandidate(CandidateType typecandidate) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { ifFactory = new FactoryCandidate(); searchcandidate = ifFactory.createSearchCandidate(typecandidate); return searchcandidate; } public State stateCandidate(State stateCurrent, CandidateType typeCandidate, StrategyType strategy, Integer operatornumber, List<State> neighborhood) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{ //Problem problem = ExecuteGenerator.getExecuteGenerator().getProblem(); State stateCandidate; List<State> auxList = new ArrayList<State>(); for (int i = 0; i < neighborhood.size(); i++) { auxList.add(neighborhood.get(i)); } this.tabusolution = new TabuSolutions(); if (strategy.equals(StrategyType.TABU)) { try { auxList = this.tabusolution.filterNeighborhood(auxList); } catch (Exception e) { Strategy strategys = Strategy.getStrategy(); if(strategys.getProblem()!=null){ neighborhood = strategys.getProblem().getOperator().generatedNewState(neighborhood.get(0), operatornumber); } return stateCandidate(stateCurrent, typeCandidate, strategy, operatornumber, neighborhood); } } SearchCandidate searchCand = newSearchCandidate(typeCandidate); stateCandidate = searchCand.stateSearch(auxList); return stateCandidate; } public TabuSolutions getTabusolution() { return tabusolution; } public void setTabusolution(TabuSolutions tabusolution) { this.tabusolution = tabusolution; } } <file_sep>package metaheurictics.strategy; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.SortedMap; import java.util.TreeMap; import factory_interface.IFFactoryGenerator; import factory_method.FactoryGenerator; import problem.definition.Problem; import problem.definition.State; import problem.definition.Problem.ProblemType; import local_search.acceptation_type.Dominance; import local_search.complement.StopExecute; import local_search.complement.UpdateParameter; import metaheuristics.generators.DistributionEstimationAlgorithm; import metaheuristics.generators.EvolutionStrategies; import metaheuristics.generators.Generator; import metaheuristics.generators.GeneratorType; import metaheuristics.generators.GeneticAlgorithm; import metaheuristics.generators.MultiGenerator; import metaheuristics.generators.ParticleSwarmOptimization; import metaheuristics.generators.RandomSearch; public class Strategy { private static Strategy strategy = null; private State bestState; private Problem problem; public SortedMap<GeneratorType, Generator> mapGenerators; private StopExecute stopexecute; private UpdateParameter updateparameter; private IFFactoryGenerator ifFactoryGenerator; private int countCurrent; private int countMax; public Generator generator; public double threshold; public ArrayList<State> listStates; //lista de todos los estados generados en cada iteracion public ArrayList<State> listBest; //lista de la mejor solucion en cada iteracion public List<State> listRefPoblacFinal = new ArrayList<State> (); //lista de soluciones no dominadas public Dominance notDominated; public boolean saveListStates; //guardar lista de estados generados public boolean saveListBestStates; // guardar lista con los mejores estados encontrados en cada iteracion public boolean saveFreneParetoMonoObjetivo; //guardar lista de soluciones no dominadas de una ejecución public boolean calculateTime; // calcular tiempo de ejecución de un algoritmo //calculo del Tiempo inicial y final long initialTime; long finalTime; public static long timeExecute; public float[] listOfflineError = new float[100]; // para almacenar la metrica offlinePerformance public int countPeriodChange = 0; // cantidad de iteeraciones antes de un cambio public int countChange = 0; private int countPeriodo; // contador para saber cada cuantas iteraciones tiene que guardar en la lista listCountBetterGender de cada generador private int periodo; //contador para controlar el periodo que esta guardando private Strategy(){ super(); } public static Strategy getStrategy() { if (strategy == null) { strategy = new Strategy(); } return strategy; } public void executeStrategy (int countmaxIterations, int countIterationsChange, int operatornumber, GeneratorType generatorType) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{ // si se quiere calcular el tiempo de ejecucion del un algoritmo if(calculateTime == true){ initialTime = System.currentTimeMillis(); } this.countMax = countmaxIterations; // max cantidad de iteraciones //generar estado inicial de la estrategia Generator randomInitial = new RandomSearch(); State initialState = randomInitial.generate(operatornumber); problem.Evaluate(initialState); //evaluar ese estado initialState.setTypeGenerator(generatorType); getProblem().setState(initialState); //si se va a salvar la lista de estados generados, adicionar el estado if(saveListStates == true){ listStates = new ArrayList<State>(); //list de estados generados listStates.add(initialState); } //si se va a salvar la lista de mejores soluciones encontradas en cada iteracion if(saveListBestStates == true){ listBest = new ArrayList<State>(); // list de mejores estados encontrados listBest.add(initialState); } if(saveFreneParetoMonoObjetivo == true){ notDominated = new Dominance(); } // crear el generador a ejecutar generator = newGenerator(generatorType); generator.setInitialReference(initialState); bestState = initialState; countCurrent = 0; listRefPoblacFinal = new ArrayList<State>(); MultiGenerator multiGenerator = null; countPeriodChange = countIterationsChange; countChange = countIterationsChange; countPeriodo = countIterationsChange / 10; //cantidad de iteraciones de un periodo //verificar que es portafolio e inicializar los generadores del portafolio if(generatorType.equals(GeneratorType.MultiGenerator)){ initializeGenerators(); MultiGenerator.initializeGenerators(); MultiGenerator.listGeneratedPP.clear(); multiGenerator = (MultiGenerator)((MultiGenerator)generator).clone(); } else initialize(); //crea el mapa de generadores update(countCurrent); float sumMax = 0; // suma acumulativa para almacenar la evaluacion de la mejor solucion encotrada y calcular el OfflinePerformance int countOff = 0; // variable par contar los OfflinePerformance que se van salvando en el arreglo //ciclio de ejecución del algoritmo while (!stopexecute.stopIterations(countCurrent, countmaxIterations)){ //si se detecta un cambio if(countCurrent == countChange){ //calcular offlinePerformance calculateOffLinePerformance(sumMax, countOff); countOff++; sumMax = 0; // countIterationsChange = countIterationsChange + countPeriodChange; // actualizar la cantidad de iteraciones //actualizar la referencia luego de un cambio updateRef(generatorType); countChange = countChange + countPeriodChange; //generar un nuevo candidato en la iteracion, dependiendo del generador State stateCandidate = null; if(generatorType.equals(GeneratorType.MultiGenerator)){ if(countPeriodo == countCurrent){ updateCountGender(); countPeriodo = countPeriodo + countPeriodChange / 10; periodo = 0; MultiGenerator.activeGenerator.countBetterGender = 0; } updateWeight();//actualizar el peso de los generadores si se reinician cuando ocurre un cambio //generar el estado candidato de la iteración stateCandidate = multiGenerator.generate(operatornumber); problem.Evaluate(stateCandidate); stateCandidate.setEvaluation(stateCandidate.getEvaluation()); stateCandidate.setNumber(countCurrent); stateCandidate.setTypeGenerator(generatorType); multiGenerator.updateReference(stateCandidate, countCurrent); } else { stateCandidate = generator.generate(operatornumber); problem.Evaluate(stateCandidate); stateCandidate.setEvaluation(stateCandidate.getEvaluation()); stateCandidate.setNumber(countCurrent); stateCandidate.setTypeGenerator(generatorType); generator.updateReference(stateCandidate, countCurrent); if(saveListStates == true){ listStates.add(stateCandidate); } // listStates.add(stateCandidate); } //actualizar el mejor estado encontrado solo tiene sentido para algoritmos monoobjetivos //actualizar el mejor estado encontrado solo tiene sentido para algoritmos monoobjetivos if ((getProblem().getTypeProblem().equals(ProblemType.Maximizar)) && bestState.getEvaluation().get(bestState.getEvaluation().size() - 1) < stateCandidate.getEvaluation().get(bestState.getEvaluation().size() - 1)) { bestState = stateCandidate; } if ((problem.getTypeProblem().equals(ProblemType.Minimizar)) && bestState.getEvaluation().get(bestState.getEvaluation().size() - 1) > stateCandidate.getEvaluation().get(bestState.getEvaluation().size() - 1)) { bestState = stateCandidate; } // System.out.println("Evaluacion: "+ bestState.getEvaluation()); if(saveListBestStates == true){ listBest.add(bestState); } sumMax = (float) (sumMax + bestState.getEvaluation().get(0)); } // no ha ocurrido un cambio else { State stateCandidate = null; if(generatorType.equals(GeneratorType.MultiGenerator)){ if(countPeriodo == countCurrent){ updateCountGender(); countPeriodo = countPeriodo + countPeriodChange / 10; periodo++; MultiGenerator.activeGenerator.countBetterGender = 0; } stateCandidate = multiGenerator.generate(operatornumber); problem.Evaluate(stateCandidate); stateCandidate.setEvaluation(stateCandidate.getEvaluation()); stateCandidate.setNumber(countCurrent); stateCandidate.setTypeGenerator(generatorType); multiGenerator.updateReference(stateCandidate, countCurrent); } else { //generar estado candidato y evaluar si es aceptado o no stateCandidate = generator.generate(operatornumber); problem.Evaluate(stateCandidate); stateCandidate.setEvaluation(stateCandidate.getEvaluation()); stateCandidate.setNumber(countCurrent); stateCandidate.setTypeGenerator(generatorType); generator.updateReference(stateCandidate, countCurrent); // actualizar la referencia del estado if(saveListStates == true){ listStates.add(stateCandidate); } if(saveFreneParetoMonoObjetivo == true){ notDominated.ListDominance(stateCandidate, listRefPoblacFinal); } } countCurrent = UpdateParameter.updateParameter(countCurrent); //actualizar el mejor estado encontrado solo tiene sentido para algoritmos monoobjetivos if ((getProblem().getTypeProblem().equals(ProblemType.Maximizar)) && bestState.getEvaluation().get(bestState.getEvaluation().size() - 1) < stateCandidate.getEvaluation().get(bestState.getEvaluation().size() - 1)) { bestState = stateCandidate; } if ((problem.getTypeProblem().equals(ProblemType.Minimizar)) && bestState.getEvaluation().get(bestState.getEvaluation().size() - 1) > stateCandidate.getEvaluation().get(bestState.getEvaluation().size() - 1)) { bestState = stateCandidate; } // System.out.println("Evaluacion: "+ bestState.getEvaluation()); if(saveListBestStates == true){ listBest.add(bestState); } sumMax = (float) (sumMax + bestState.getEvaluation().get(0)); } // System.out.println("Iteracion: " + countCurrent); } //calcular tiempo final if(calculateTime == true){ finalTime = System.currentTimeMillis(); timeExecute = finalTime - initialTime; System.out.println("El tiempo de ejecucion: " + timeExecute); } if(generatorType.equals(GeneratorType.MultiGenerator)){ listBest = (ArrayList<State>) multiGenerator.getReferenceList(); //calcular offlinePerformance calculateOffLinePerformance(sumMax, countOff); if(countPeriodo == countCurrent){ updateCountGender(); } } else{ listBest = (ArrayList<State>) generator.getReferenceList(); calculateOffLinePerformance(sumMax, countOff); } } public void updateCountGender(){ // actualizar la cantidad de mejoras y cantidad de veces que se uso un generador en un periodo dado for (int i = 0; i < MultiGenerator.getListGenerators().length; i++) { if(!MultiGenerator.getListGenerators()[i].getType().equals(GeneratorType.MultiGenerator) ){/*&& !MultiGenerator.getListGenerators()[i].getType().equals(GeneratorType.MultiCaseSimulatedAnnealing) && !MultiGenerator.getListGenerators()[i].getType().equals(GeneratorType.MultiobjectiveHillClimbingDistance) && !MultiGenerator.getListGenerators()[i].getType().equals(GeneratorType.MultiobjectiveHillClimbingRestart) && !MultiGenerator.getListGenerators()[i].getType().equals(GeneratorType.MultiobjectiveStochasticHillClimbing) && !MultiGenerator.getListGenerators()[i].getType().equals(GeneratorType.MultiobjectiveTabuSearch) && !MultiGenerator.getListGenerators()[i].getType().equals(GeneratorType.ParticleSwarmOptimization)*/ MultiGenerator.getListGenerators()[i].getListCountGender()[periodo] = MultiGenerator.getListGenerators()[i].countGender + MultiGenerator.getListGenerators()[i].getListCountGender()[periodo]; MultiGenerator.getListGenerators()[i].getListCountBetterGender()[periodo] = MultiGenerator.getListGenerators()[i].countBetterGender + MultiGenerator.getListGenerators()[i].getListCountBetterGender()[periodo]; MultiGenerator.getListGenerators()[i].countGender = 0; MultiGenerator.getListGenerators()[i].countBetterGender = 0; } } } public void updateWeight(){ for (int i = 0; i < MultiGenerator.getListGenerators().length; i++) { if(!MultiGenerator.getListGenerators()[i].getType().equals(GeneratorType.MultiGenerator)){ MultiGenerator.getListGenerators()[i].setWeight((float) 50.0); } } } public void update(Integer countIterationsCurrent) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {//HashMap<String, Object> map, // Here update parameter for update and change generator. if(countIterationsCurrent.equals(GeneticAlgorithm.countRef - 1)){ ifFactoryGenerator = new FactoryGenerator(); Strategy.getStrategy().generator = ifFactoryGenerator.createGenerator(GeneratorType.GeneticAlgorithm); } if(countIterationsCurrent.equals(EvolutionStrategies.countRef - 1)){ ifFactoryGenerator = new FactoryGenerator(); Strategy.getStrategy().generator = ifFactoryGenerator.createGenerator(GeneratorType.EvolutionStrategies); } if(countIterationsCurrent.equals(DistributionEstimationAlgorithm.countRef - 1)){ ifFactoryGenerator = new FactoryGenerator(); Strategy.getStrategy().generator = ifFactoryGenerator.createGenerator(GeneratorType.DistributionEstimationAlgorithm); } if(countIterationsCurrent.equals(ParticleSwarmOptimization.countRef - 1)){ ifFactoryGenerator = new FactoryGenerator(); Strategy.getStrategy().generator = ifFactoryGenerator.createGenerator(GeneratorType.ParticleSwarmOptimization); } } public Generator newGenerator(GeneratorType Generatortype) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { ifFactoryGenerator = new FactoryGenerator(); Generator generator = ifFactoryGenerator.createGenerator(Generatortype); return generator; } public State getBestState() { return bestState; } public void setBestState(State besState) { this.bestState = besState; } public StopExecute getStopexecute() { return stopexecute; } public int getCountMax() { return countMax; } public void setCountMax(int countMax) { this.countMax = countMax; } public void setStopexecute(StopExecute stopexecute) { this.stopexecute = stopexecute; } public UpdateParameter getUpdateparameter() { return updateparameter; } public void setUpdateparameter(UpdateParameter updateparameter) { this.updateparameter = updateparameter; } public Problem getProblem() { return problem; } public void setProblem(Problem problem) { this.problem = problem; } public ArrayList<String> getListKey(){ ArrayList<String> listKeys = new ArrayList<String>(); String key = mapGenerators.keySet().toString(); String returnString = key.substring(1, key.length() - 1); returnString = returnString + ", "; int countKey = mapGenerators.size(); for (int i = 0; i < countKey; i++) { String r = returnString.substring(0, returnString.indexOf(',')); returnString = returnString.substring(returnString.indexOf(',') + 2); listKeys.add(r); } return listKeys; } public void initializeGenerators()throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { List<GeneratorType> listType = new ArrayList<GeneratorType>(); this.mapGenerators = new TreeMap<GeneratorType, Generator>(); GeneratorType type[]= GeneratorType.values(); for (GeneratorType generator : type) { listType.add(generator); } for (int i = 0; i < listType.size(); i++) { Generator generator = newGenerator(listType.get(i)); mapGenerators.put(listType.get(i), generator); //ExecuteGeneratorParall.getExecuteGeneratorParall().listGenerators.add(generator); // MultiGenerator.getListGenerators()[i] = generator; } } public void initialize()throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { List<GeneratorType> listType = new ArrayList<GeneratorType>(); this.mapGenerators = new TreeMap<GeneratorType, Generator>(); GeneratorType type[]= GeneratorType.values(); for (GeneratorType generator : type) { listType.add(generator); } for (int i = 0; i < listType.size(); i++) { Generator generator = newGenerator(listType.get(i)); mapGenerators.put(listType.get(i), generator); } } public int getCountCurrent() { return countCurrent; } public void setCountCurrent(int countCurrent) { this.countCurrent = countCurrent; } public static void destroyExecute() { strategy = null; RandomSearch.listStateReference = null; } public double getThreshold() { return threshold; } public void setThreshold(double threshold) { this.threshold = threshold; } public void calculateOffLinePerformance(float sumMax, int countOff){ float off = sumMax / countPeriodChange; listOfflineError[countOff] = off; } public void updateRef(GeneratorType generatorType){ // State ref = problem.getOperator().newRef(problem.getRef()); // problem.setRef(ref); if(generatorType.equals(GeneratorType.MultiGenerator)){ updateRefMultiG(); bestState = MultiGenerator.listStateReference.get( MultiGenerator.listStateReference.size() - 1); } else{ updateRefGenerator(generator); bestState = generator.getReference(); } } public void updateRefMultiG() { for (int i = 0; i < MultiGenerator.getListGenerators().length; i++) { updateRefGenerator(MultiGenerator.getListGenerators()[i]); } } public void updateRefGenerator(Generator generator) { if(generator.getType().equals(GeneratorType.HillClimbing) || generator.getType().equals(GeneratorType.TabuSearch) || generator.getType().equals(GeneratorType.RandomSearch) || generator.getType().equals(GeneratorType.SimulatedAnnealing)){ double evaluation = getProblem().getFunction().get(0).Evaluation(generator.getReference()); generator.getReference().getEvaluation().set(0, evaluation); // State state = new State(); // state.setEvaluation(evaluation); // state.setCode(new ArrayList<Object>(generator.getReference().getCode())); // state.setTypeGenerator(generator.getType()); // generator.setInitialReference(state); /*generator.getReferenceList().remove(generator.getReferenceList().size() - 1); generator.setInitialReference(state); generator.getReferenceList().add(state);*/ } if(generator.getType().equals(GeneratorType.GeneticAlgorithm) || generator.getType().equals(GeneratorType.DistributionEstimationAlgorithm) || generator.getType().equals(GeneratorType.EvolutionStrategies)){ for (int j = 0; j < generator.getReferenceList().size(); j++) { double evaluation = getProblem().getFunction().get(0).Evaluation(generator.getReferenceList().get(j)); generator.getReferenceList().get(j).getEvaluation().set(0, evaluation); } } } } <file_sep>package factory_interface; import java.lang.reflect.InvocationTargetException; import evolutionary_algorithms.complement.Mutation; import evolutionary_algorithms.complement.MutationType; public interface IFFactoryMutation { Mutation createMutation(MutationType typeMutation)throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException ; } <file_sep>package metaheuristics.generators; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import metaheurictics.strategy.Strategy; import problem.definition.Problem.ProblemType; import problem.definition.State; public class ParticleSwarmOptimization extends Generator { private State stateReferencePSO; private List<State> listStateReference = new ArrayList<State>(); private List<Particle> listParticle = new ArrayList<Particle> (); private GeneratorType generatorType; public static int countRef = 0; // CANTIDAD DE PARTICULAS TOTAL = coutSwarm * countParticleSwarm public static int countParticle = 0; // CANTIDAD DE PARTICULAS QUE SE HAN MOVIDO EN CADA CUMULO public static int coutSwarm = 0; //CANTIDAD DE CUMULOS public static int countParticleBySwarm = 0; //CANTIDAD DE PARTICULAS POR CUMULO private float weight = 50; public static double wmax = 0.9; public static double wmin = 0.2; public static int learning1 = 2, learning2 = 2; public static double constriction; public static boolean binary = false; public static State[] lBest; public static State gBest; public static int countCurrentIterPSO; //problemas dinamicos public static int countGender = 0; public static int countBetterGender = 0; private int[] listCountBetterGender = new int[10]; private int[] listCountGender = new int[10]; private float[] listTrace = new float[1200000]; public ParticleSwarmOptimization(){ super(); countRef = coutSwarm * countParticleBySwarm; this.setListParticle(getListStateRef()); // listStateReference = new ArrayList<State>(Strategy.getStrategy().listBest); this.generatorType = GeneratorType.ParticleSwarmOptimization; this.weight = 50; lBest = new State[coutSwarm]; if(!listParticle.isEmpty()){ countCurrentIterPSO = 1; inicialiceLBest(); gBest = gBestInicial(); } countParticle = 0; listTrace[0] = this.weight; listCountBetterGender[0] = 0; listCountGender[0] = 0; } @Override public State generate(Integer operatornumber) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{ //PSO if (countParticle >= countRef) countParticle = 0; // System.out.println("Contador de particulas: " + countParticle + " Contador de iteraciones " + Strategy.getStrategy().getCountCurrent()); listParticle.get(countParticle).generate(1); return listParticle.get(countParticle).getStateActual(); } public void inicialiceLBest (){ for (int j = 0; j < coutSwarm; j++) { State reference = new State(); reference = listParticle.get(countParticle).getStatePBest(); int iterator = countParticleBySwarm + countParticle; if(Strategy.getStrategy().getProblem().getTypeProblem().equals(ProblemType.Maximizar)){ for (int i = countParticle; i < iterator; i++) { if (listParticle.get(i).getStatePBest().getEvaluation().get(0) > reference.getEvaluation().get(0)) reference = listParticle.get(i).getStatePBest(); countParticle++; } } else{ for (int i = countParticle; i < iterator; i++) { if (listParticle.get(i).getStatePBest().getEvaluation().get(0) < reference.getEvaluation().get(0)) reference = listParticle.get(i).getStatePBest(); countParticle++; } } lBest[j] = reference; } } @Override public State getReference() { return null; } private List<Particle> getListStateRef() { Boolean found = false; List<String> key = Strategy.getStrategy().getListKey(); int count = 0; if(RandomSearch.listStateReference.size() == 0){ return this.setListParticle(new ArrayList<Particle>()); } while((found.equals(false)) && (Strategy.getStrategy().mapGenerators.size() > count)){ //recorrer la lista de generadores, hasta que encuentre el PSO if(key.get(count).equals(GeneratorType.ParticleSwarmOptimization.toString())){ //creo el generador PSO, y si su lista de particulas esta vacia entonces es la primera vez que lo estoy creando, y cada estado lo convierto en particulas GeneratorType keyGenerator = GeneratorType.valueOf(String.valueOf(key.get(count))); ParticleSwarmOptimization generator = (ParticleSwarmOptimization) Strategy.getStrategy().mapGenerators.get(keyGenerator); if(generator.getListParticle().isEmpty()){ //convertir los estados en particulas for (int j = 0; j < RandomSearch.listStateReference.size(); j++) { //si el estado es creado con el generator RandomSearch entonces la convierto en particula if(getListParticle().size() != countRef){ ArrayList<Object> velocity = new ArrayList<Object>(); State stateAct = (State) RandomSearch.listStateReference.get(j).getCopy(); stateAct.setCode(new ArrayList<Object>(RandomSearch.listStateReference.get(j).getCode())); stateAct.setEvaluation(RandomSearch.listStateReference.get(j).getEvaluation()); State statePBest = (State) RandomSearch.listStateReference.get(j).getCopy(); statePBest.setCode(new ArrayList<Object>(RandomSearch.listStateReference.get(j).getCode())); statePBest.setEvaluation(RandomSearch.listStateReference.get(j).getEvaluation()); Particle particle = new Particle(stateAct, statePBest, velocity); getListParticle().add(particle); } } } else{ setListParticle(generator.getListStateReference()); } found = true; } count++; } return getListParticle(); } public State getStateReferencePSO() { return stateReferencePSO; } public void setStateReferencePSO(State stateReferencePSO) { this.stateReferencePSO = stateReferencePSO; } public List<Particle> getListStateReference() { return this.getListParticle(); } public void setListStateReference(List<State> listStateReference) { this.listStateReference = listStateReference; } public List<Particle> getListParticle() { return listParticle; } public List<Particle> setListParticle(List<Particle> listParticle) { this.listParticle = listParticle; return listParticle; } public GeneratorType getGeneratorType() { return generatorType; } public void setGeneratorType(GeneratorType generatorType) { this.generatorType = generatorType; } public static int getCountRef() { return countRef; } public static void setCountRef(int countRef) { ParticleSwarmOptimization.countRef = countRef; } //***************************************** @Override public void updateReference(State stateCandidate,Integer countIterationsCurrent) throws IllegalArgumentException,SecurityException, ClassNotFoundException, InstantiationException,IllegalAccessException, InvocationTargetException,NoSuchMethodException { Particle particle = new Particle(); particle = listParticle.get(countParticle); int swarm = countParticle/countParticleBySwarm; if(Strategy.getStrategy().getProblem().getTypeProblem().equals(ProblemType.Maximizar)){ if ((lBest[swarm]).getEvaluation().get(0) < particle.getStatePBest().getEvaluation().get(0)){ lBest[swarm] = particle.getStatePBest(); if(lBest[swarm].getEvaluation().get(0) > getReferenceList().get(getReferenceList().size() - 1).getEvaluation().get(0)){ gBest = new State(); gBest.setCode(new ArrayList<Object>(lBest[swarm].getCode())); gBest.setEvaluation(lBest[swarm].getEvaluation()); gBest.setTypeGenerator(lBest[swarm].getTypeGenerator()); } } } else { particle.updateReference(stateCandidate, countIterationsCurrent); if ((lBest[swarm]).getEvaluation().get(0) > particle.getStatePBest().getEvaluation().get(0)){ lBest[swarm] = particle.getStatePBest(); if(lBest[swarm].getEvaluation().get(0) < getReferenceList().get(getReferenceList().size() - 1).getEvaluation().get(0)){ gBest = new State(); gBest.setCode(new ArrayList<Object>(lBest[swarm].getCode())); gBest.setEvaluation(lBest[swarm].getEvaluation()); gBest.setTypeGenerator(lBest[swarm].getTypeGenerator()); } } } listStateReference.add(gBest); countParticle++; countCurrentIterPSO++; } public State gBestInicial (){ State stateBest = lBest[0]; for (int i = 1; i < lBest.length; i++) { if(Strategy.getStrategy().getProblem().getTypeProblem().equals(ProblemType.Maximizar)){ if (lBest[i].getEvaluation().get(0) > stateBest.getEvaluation().get(0)){ stateBest = lBest[i]; } } else{ if (lBest[i].getEvaluation().get(0) < stateBest.getEvaluation().get(0)){ stateBest = lBest[i]; } } } return stateBest; } @Override public void setInitialReference(State stateInitialRef) { // TODO Auto-generated method stub } @Override public GeneratorType getType() { // TODO Auto-generated method stub return this.generatorType; } @Override public List<State> getReferenceList() { // TODO Auto-generated method stub return this.listStateReference; } @Override public List<State> getSonList() { // TODO Auto-generated method stub return null; } @Override public boolean awardUpdateREF(State stateCandidate) { // TODO Auto-generated method stub return false; } @Override public void setWeight(float weight) { // TODO Auto-generated method stub } @Override public float getWeight() { // TODO Auto-generated method stub return 0; } @Override public int[] getListCountBetterGender() { // TODO Auto-generated method stub return this.listCountBetterGender; } @Override public int[] getListCountGender() { // TODO Auto-generated method stub return this.listCountGender; } @Override public float[] getTrace() { // TODO Auto-generated method stub return this.listTrace; } } <file_sep>/** * @(#) AleatoryCandidate.java */ package local_search.candidate_type; import java.util.List; import problem.definition.State; public class RandomCandidate extends SearchCandidate { @Override public State stateSearch(List<State> listNeighborhood) { int pos = (int)(Math.random() * (double)(listNeighborhood.size() - 1)); State stateAleatory = listNeighborhood.get(pos); return stateAleatory; } } <file_sep>/** * @(#) FactoryCandidate.java */ package factory_method; import java.lang.reflect.InvocationTargetException; import local_search.candidate_type.CandidateType; import local_search.candidate_type.SearchCandidate; import factory_interface.IFFactoryCandidate; public class FactoryCandidate implements IFFactoryCandidate{ private SearchCandidate searchcandidate; public SearchCandidate createSearchCandidate(CandidateType typeCandidate) throws IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { String className = "local_search.candidate_type." + typeCandidate.toString(); searchcandidate = (SearchCandidate) FactoryLoader.getInstance(className); return searchcandidate; } } <file_sep>package local_search.acceptation_type; import java.util.List; import metaheurictics.strategy.Strategy; import problem.definition.State; public class AcceptNotDominatedTabu extends AcceptableCandidate { @Override public Boolean acceptCandidate(State stateCurrent, State stateCandidate) { List<State> list = Strategy.getStrategy().listRefPoblacFinal; Dominance dominance = new Dominance(); if(list.size() == 0){ list.add(stateCurrent.clone()); } //Verificando si la solución candidata domina a alguna de las soluciones de la lista de soluciones no dominadas //De ser así se eliminan de la lista y se adiciona la nueva solución en la lista //De lo contrario no se adiciona la solución candidata a la lista //Si fue insertada en la lista entonces la solucion candidata se convierte en solucion actual dominance.ListDominance(stateCandidate, list); return true; } } <file_sep>package problem_operators; import java.util.ArrayList; import java.util.List; import metaheurictics.strategy.Strategy; import problem.definition.Operator; import problem.definition.State; public class MutationOperator extends Operator { public List<State> generatedNewState(State stateCurrent, Integer operatornumber){ List<State> listNeigborhood = new ArrayList<State>(); for (int i = 0; i < operatornumber; i++){ int key = Strategy.getStrategy().getProblem().getCodification().getAleatoryKey(); Object candidate = Strategy.getStrategy().getProblem().getCodification().getVariableAleatoryValue(key); State state = (State) stateCurrent.getCopy(); state.getCode().set(key, candidate); listNeigborhood.add(state); } return listNeigborhood; } @Override public List<State> generateRandomState(Integer operatornumber) { // TODO Auto-generated method stub return null; } } <file_sep># LABORATORIO DE DESARROLLO Y HERRAMIENTAS ## Práctica 3. Herramientas de Calidad del Producto Software. SonarQube y Maven <file_sep>package evolutionary_algorithms.complement; import java.util.ArrayList; import config.tspDynamic.TSPState; import metaheurictics.strategy.Strategy; import problem.definition.State; public class AIOMutation extends Mutation { public static ArrayList<Object> path = new ArrayList<Object>(); @Override public State mutation(State state, double PM) { // TODO Auto-generated method stub int key = Strategy.getStrategy().getProblem().getCodification().getAleatoryKey(); //seleccionar aleatoriamente una ciudad int key1 = 0; boolean found = false; while (found == false){ key1 = Strategy.getStrategy().getProblem().getCodification().getAleatoryKey(); if(key1 != key) found = true; } sortedPathValue(state); int p1 = 0; int p2 = 0; if(key > key1){ p2 = key; p1 = key1; } else{ p1 = key; p2 = key1; } int length = (p2 - p1) / 2; for (int i = 1; i <= length + 1; i++) { int tempC = ((TSPState) state.getCode().get(p1 + i - 1)).getIdCity(); ((TSPState)state.getCode().get(p1 + i - 1)).setIdCity(((TSPState)state.getCode().get(p2 - i + 1)).getIdCity()); ((TSPState)state.getCode().get(p2 - i + 1)).setIdCity(tempC); } path.clear(); return state; } public void sortedPathValue(State state) { for(int k = 0; k < state.getCode().size(); k++){ path.add( state.getCode().get(k)); } for(int i = 1; i < path.size(); i++){ for(int j = 0; j < i; j++){ Integer data1 = ((TSPState)state.getCode().get(i)).getValue(); Integer data2 = ((TSPState)state.getCode().get(j)).getValue(); if(data1 < data2){ state.getCode().add(j, state.getCode().remove(i)); path.add(j, path.remove(i)); } } } } public static void fillPath() { for(int k = 0; k < Strategy.getStrategy().getProblem().getCodification().getVariableCount(); k++){ path.add(k); } } }
c3f8c38e8e7bcb0f6fd434a5805508748b3e2373
[ "Markdown", "Java", "Maven POM" ]
45
Java
alu0100354782/BiCIAM-Maven
d5861b33eccafdf5d56b0eb6d1c5a986fbdf2cfb
203a7c8670da89c64ea1260d6e0691bf57ba04e0
refs/heads/master
<repo_name>klc7778/GMI-Java<file_sep>/Clark_Kira_Java102/src/ProductReader.java import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ProductReader { String absolutePath; List<Product> products; public ProductReader(String absolutePath) { super(); this.absolutePath = absolutePath; } public List<Product> readFile() throws IOException { File prodFile = null; FileReader fReader = null; BufferedReader reader = null; products = new ArrayList<>(); try { prodFile = new File(absolutePath); File[] files = prodFile.listFiles(); for(File file : files) { fReader = new FileReader(file); reader = new BufferedReader(fReader); CreateProduct cp = new CreateProduct(); products = cp.createProduct(reader); } // end for loop here } // end try catch (FileNotFoundException e) { e.printStackTrace(); } return products; } // end readFile } <file_sep>/Clark_Kira_Java102/src/TestSearch.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class TestSearch { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub String prodName = "Headphones"; List<String> prodList = new ArrayList<>(); /* * Call execute to start up multiple threads in threadpool * -- used if multiple people would like to order at the same time */ ExecutorService execute = Executors.newFixedThreadPool(1); ProductReader pr = new ProductReader("C:\\Users\\kirclark\\Desktop\\Product_SuperStore.txt"); List<Product> pList = pr.readFile(); try { pList = pr.readFile(); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } try { pList = pr.readFile(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } for(int i = 0; i < 1; i++) { Callable search = new Order(prodName); Future futures = execute.submit(search); PrintInfo pi = new PrintInfo(); pi.printInfo(pList, prodName); try { pList = (List<Product>) futures.get(); } // end try catch(InterruptedException e) { e.printStackTrace(); } catch(ExecutionException e) { e.printStackTrace(); } pi.checkProd(pList, prodList); } // end for loop here execute.shutdown(); } } <file_sep>/Kira_Clark_ID101_JEE3/src/repo/GradeData.java package repo; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import connection.Connect; import model.Grades; public class GradeData { static Connection currentConn = null; static ResultSet rs = null; public static Grades login(Grades grade) { Statement stmt = null; String rollno = grade.getRollNo(); String searchQuery = "select * from student where roll='" + rollno + "'"; try { currentConn = Connect.getConnection(); stmt = currentConn.createStatement(); rs = stmt.executeQuery(searchQuery); boolean userExists = rs.next(); if (!userExists) { grade.setValid(false); } else if (userExists) { int percentage = rs.getInt("percentage"); int mark1 = rs.getInt("mark1"); int mark2 = rs.getInt("mark2"); grade.setMark1(mark1); grade.setMark2(mark2); grade.setPercent(percentage); grade.setValid(true); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return grade; } } <file_sep>/Kira_Clark_Java101/src/Management.java import java.util.*; /** * */ public class Management extends Book { static Date rentDate; /** * Default constructor */ public Management() { super(bookName, lateFee); } /** * */ @Override public void returnFine() { // TODO implement here } }
8bd69da2c072e7af1eb646a9f3085012decbb610
[ "Java" ]
4
Java
klc7778/GMI-Java
765621d138e9c22d95dc09f616a8ae96dcc8e033
9eb2f7be380228d8458f6d9104e2f2848c84516c
refs/heads/master
<file_sep>import os import yaml import pystache from loader import Loader dirpath = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(dirpath, "database", "main.yaml"), "r") as f: data = yaml.load(f, Loader) with open(os.path.join(dirpath, "template.html"), "r") as f: parsed_template = pystache.parse(f.read()) html = pystache.render(parsed_template, data) with open("index.html", "w") as f: f.write(html.strip())
3d03d07a3d267f26be06ba0d3b4611018ab4205f
[ "Python" ]
1
Python
guptavaibhav0/vgupta-tech.github.io
aaaad4b093e427c25dadd65282b4a72afc95df49
e366253abc95fd8475813c410eda12d8953a7224
refs/heads/master
<file_sep># -*- coding: utf-8 -*- from scrapy import Spider, Request, http from urllib import parse import logging import re from w3lib.html import remove_tags logger = logging.getLogger(__name__) def go_remove_tag(value): # 移除标签 content = remove_tags(value) # 移除空格 换行 return re.sub(r'[\t\r\n\s]', '', content) class BaiduSpider(Spider): name = 'baidu' count = 5 def start_requests(self): key_word = '经济指标' url = 'https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&tn=baidu&wd=' + parse.quote(key_word) # 注意是https start_urls = [url] yield Request(url, self.parse) # dict1 = {'wd': '百度 翻译'} # url_data = parse.urlencode(dict1) # unlencode()将字典{k1:v1,k2:v2}转化为k1=v1&k2=v2 def parse(self, response): logger.debug("-----------------------------------------------------------") next_urls = [] for x in range(self.count): next_urls.append(response.xpath(f"//*[@id=\"{x + 1}\"]/h3/a/@href").get()) # 获取到百度关键词的前count条网址 for u in next_urls: logger.debug(u) yield Request(url=u, callback=self.get_new_key) logger.debug("-----------------------------------------------------------") def get_new_key(self, response): if response.status is 200: logger.debug(response.url) print(go_remove_tag(response.body.decode(response.encoding))) pass <file_sep>import unittest from urllib import parse class MyTestCase(unittest.TestCase): def test_something(self): self.assertEqual(True, False) def test_parse(self): dict1 = {'wd': '与经济发展相关的指标'} url_data = parse.urlencode(dict1) # unlencode()将字典{k1:v1,k2:v2}转化为k1=v1&k2=v2 url = 'http://www.baidu.com/s?' + url_data print(url) url_data2 = '经济指标' url2 = 'http://www.baidu.com/s?wd=' + parse.quote(url_data2) print(url2) if __name__ == '__main__': unittest.main() <file_sep># Python Reptile This is the code repository for the Python Reptile book--><a href="https://item.jd.com/12610080.html?dist=jd">URL</a> # 说明 书中讲述的scrapy框架是基于1.5版本,如果读者使用1.7以上版本,书中源码在运行过程中出现错误提示,因为新版本删除和修改旧版本的一些方法,具体说明可以查看官网文档:https://doc.scrapy.org/en/latest/news.html (建议读者使用1.5.2版本,可以使用pip install scrapy==1.5.2安装) # Communication QQ群:93314951 <file_sep># # -*- coding:utf-8 -*- # # from scrapy.cmdline import execute # import os # import sys # # # 添加当前项目的绝对地址 # sys.path.append(os.path.dirname(os.path.abspath(__file__))) # # 执行 scrapy 内置的函数方法execute, 使用 crawl 爬取并调试,最后一个参数jobbole 是我的爬虫文件名 # execute(['scrapy', 'crawl', 'baidu']) from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings if __name__ == '__main__': process = CrawlerProcess(get_project_settings()) process.crawl('baidu') # 你需要将此处的spider_name替换为你自己的爬虫名称 process.start()
5061e0ed3f220b9e315335659010cb70aa9a3bee
[ "Markdown", "Python" ]
4
Python
Yunnglin/Keyword-mining
1025babbb5658a0517a91fd2b529b4f3ec824e07
fd0023781a0fea396c0d0abd0e083c84bb68c3a8
refs/heads/master
<repo_name>badabalam1/1_test<file_sep>/routes/index.js const router = require('express').Router(); const auth = require('./auth'); const main = require('./main'); const board = require('./board'); const user = require('./user'); // all user router.get('/', main.main); router.get('/auth/signup', auth.signup); router.post('/auth/signup', auth.signup_process); router.get('/auth/login', auth.login); router.post('/auth/login', auth.login_process.fuck); router.get('/auth/logout', auth.logout); // only member router.get('/board/write', board.write); router.post('/board/write', board.write_process); router.get('/board/:postID', board.showPost); router.post('/board/comment/write', board.writeComment); router.delete('/board/comment/delete/:cID', board.deleteComment); router.put('/board/comment/update/:cID', board.updateComment); // only Author router.get('/board/edit/:postID', board.editPost); router.put('/board/update/:postID', board.updatePost); router.delete('/board/delete/:postID', board.deletePost); // only member router.get('/user/information', user.information); // only Admin router.get('/user/members', user.members); router.put('/user/modify/:userID', user.modifyUser) router.delete('/user/delete/:userID', user.deleteUser) module.exports = router;<file_sep>/routes/main.js const Post = require('../schema/board'); let postCount = 0; exports.main = (req, res) => { Post.find({}) .then((result) => { postCount = result.length; }).catch((err) => { res.json(err); }); let pageID = req.query.page === undefined || req.query.page < 1 ? 1 : req.query.page Post.find({}) .sort('-createAt') .skip( (pageID - 1 ) * 10) .limit(pageID * 10) .then((result) => { res.render('index', { posts: result, pageLength: ((Math.ceil(postCount / 10)) * 10 ) / 10 }); }).catch((err) => { res.json(err); }); console.log(`로그인 여부 : ${res.locals.isAuthenticated}`); }<file_sep>/public/js/showPost.js $('.comment-edit').click(() => { $('.comment-field').remove(); $('.comment-buttons').remove(); let editingForm = ` <form action="/board/comment/write/?postID=<%= post._id %>" method="post"> <div class="form-group"> <textarea name="comment" class="form-control" rows="3"><%= comment.comment %></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form>`; $('.for-editing-comment').html(() => { return editingForm; }); });
1cc18d0b017ba0a820ee908be5ec7059675bdf3f
[ "JavaScript" ]
3
JavaScript
badabalam1/1_test
38ee7a882aeacb1f5a4b76a530b051e9256b9328
0b5accda780be8841d12d6a04603a6b7afa9a45f
refs/heads/master
<file_sep>package com.rk.beans; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan(basePackages ="com.rk") public class Organization { private String organizationName; private Pic picOrg; public void setOrganizationName(String organizationName) { this.organizationName = organizationName; } public void setPicOrg(Pic picOrg) { this.picOrg = picOrg; } @Override public String toString() { return "Organization{" + "organizationName='" + organizationName + '\'' + ", picOrg=" + picOrg + '}'; } } <file_sep>package com.rk.client; import com.rk.beans.Organization; import com.rk.beans.Pic; import com.rk.beansConfig.BeanConfig; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Client { public static void main(String[] args) { ApplicationContext applicationContext=new AnnotationConfigApplicationContext(BeanConfig.class); Pic pic=applicationContext.getBean(Pic.class); Organization organization =applicationContext.getBean(Organization.class); System.out.println(pic); System.out.println(organization); } } <file_sep>package com.rk.beansConfig; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan(basePackages ="com.rk") public class BeanConfig { }
6f8ef827e3ff65d5601a1cf7984e3655732f8fdf
[ "Java" ]
3
Java
rahulkumaryadav/java-spring-6-DI-javaconfiguration
8decf903cc2d55105786811e0e293e92f483849f
01d52e8012f065a66a638940583ab787aba165cd
refs/heads/master
<file_sep># Ant-FS # # Copyright (c) 2012, <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. from __future__ import absolute_import, print_function import array import unittest import datetime from ant.fs.commandpipe import parse, CreateFile, Request, CommandPipe, Time, TimeResponse class CreateFileTest(unittest.TestCase): def runTest(self): # Test create file data = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09] request = CreateFile(len(data), 0x80, [0x04, 0x00, 0x00], [0x00, 0xff, 0xff]) # Test create file response response_data = array.array('B', [2, 0, 0, 0, 4, 0, 0, 0, 128, 4, 123, 0, 103, 0, 0, 0]) response = parse(response_data) self.assertEqual(response.get_request_id(), 0x04) self.assertEqual(response.get_response(), 0x00) self.assertEqual(response.get_data_type(), 0x80) # FIT self.assertEqual(response.get_identifier(), array.array('B', [4, 123, 0])) self.assertEqual(response.get_index(), 103) class TimeTest(unittest.TestCase): def runTest(self): # Test time request request = Request(CommandPipe.Type.TIME) self.assertEqual(request.get(), array.array('B', [0x01, 0x00, 0x00, CommandPipe._sequence, 0x03, 0x00, 0x00, 0x00])) # Test time parse response_data = array.array('B', [0x03, 0x00, 0x00, 0x0f, 0x78, 0xb5, 0xca, 0x25, 0xc8, 0xa0, 0xf4, 0x29, 0x01, 0x00, 0x00, 0x00]) response = parse(response_data) self.assertIsInstance(response, Time) self.assertEqual(response.get_command(), 0x03) self.assertEqual(response.get_sequence(), 0x0f) current_time = (datetime.datetime(2010, 2, 2, 10, 42, 0) - datetime.datetime(1989, 12, 31, 0, 0, 0)).total_seconds() self.assertEqual(response.get_current_time(), current_time) system_time = (datetime.datetime(2012, 4, 20, 23, 10, 0) - datetime.datetime(1989, 12, 31, 0, 0, 0)).total_seconds() self.assertEqual(response.get_system_time(), system_time) self.assertEqual(response.get_time_format(), 1) # Test time create current_time = (datetime.datetime(2015, 1, 4, 21, 23, 30) - datetime.datetime(1989, 12, 31, 0, 0, 0)).total_seconds() system_time = (datetime.datetime(2012, 4, 20, 23, 10, 0) - datetime.datetime(1989, 12, 31, 0, 0, 0)).total_seconds() time = Time(int(current_time), int(system_time), Time.Format.COUNTER) self.assertEqual(time.get(), array.array('B', [0x03, 0x00, 0x00, CommandPipe._sequence, 0x52, 0x63, 0x0c, 0x2f, 0xc8, 0xa0, 0xf4, 0x29, 0x02, 0x00, 0x00, 0x00])) # Test time request response response_data = array.array('B', [0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) response = parse(response_data) self.assertIsInstance(response, TimeResponse) <file_sep>[tox] envlist = py27,py33,py34,py35,py36,pypy [testenv] commands=python setup.py test usedevelop = True
825b538aefa2ed83f79c5ac0719b3fda3f0b4f86
[ "Python", "INI" ]
2
Python
prcoder-1/openant
d88f825d3fac2e8eb251d669a37cf5ecb5347392
493b527cd1b4c80859485583873a67a1c2c0116b
refs/heads/master
<repo_name>yeq71/epics_websocket<file_sep>/README.md # epics_websocket Python EPICS to websocket connector. ## Installation ```bash $ git clone https://github.com/webepics/epics_websocket.git $ cd epics_websocket $ python setup.py install ``` ## Run Server To run on default port, 6064, without debugging logs: ``` $ epicswebsocket ``` Help on command: ``` $ epicswebsocket -h usage: epicswebsocket [-h] [--port PORT] [--debug] Start EPICS/Websocket server. optional arguments: -h, --help show this help message and exit --port PORT, -p PORT Port number for websockets --debug, -d Enable Debugging Log ``` <file_sep>/epics_websocket/server.py import logging from epics_websocket.epics_protocol import EpicsServerProtocol def start_server(port=6064, debug=False): """ Start the Websocket server """ logging.basicConfig(level=logging.DEBUG) epics_server = EpicsServerProtocol(port=port, debug=debug) epics_server.run() if __name__ == '__main__': start_server()<file_sep>/epics_websocket/scripts/start.py import argparse from epics_websocket.server import start_server def start(): parser = argparse.ArgumentParser(description='Start EPICS/Websocket server.') parser.add_argument('--port', '-p', type=int, default=6064, help='Port number for websockets') parser.add_argument('--debug', '-d', action='store_true', help='Enable Debugging Log') args = parser.parse_args() start_server(args.port, args.debug) if __name__ == '__main__': start()<file_sep>/epics_websocket/websocket_server.py #!/usr/bin/env python """ Websocket server """ import json import asyncio import websockets class Message: """ pass """ def __init__(self, message_type, message_data=None, message_global=False): self._type = message_type self._data = message_data self._global = message_global self._binary = isinstance(message_data, bytes) @classmethod def from_json(cls, message): message = json.loads(message) is_global = message['global'] if 'global' in message.keys() else False try: return Message(message['type'], message['data'], message_global=is_global) except KeyError: return Message(message['type'], message_global=is_global) @property def json(self): return json.dumps({'type': self._type, 'data': self._data}) @property def type(self): return self._type @property def data(self): return self._data @property def is_global(self): return self._global @property def is_binary(self): return self._binary class WebsocketServer: """ Pass """ def __init__(self, port=None, debug=False): self.port = port if port is not None else 6064 self._debug = debug self._connected = set() self.recv_queue = asyncio.Queue() self.send_queue = asyncio.Queue() self.reply_task = asyncio.ensure_future(self.reply_consumer()) self.recv_task = asyncio.ensure_future(self.recv_consumer()) async def handler(self, websocket, path): """ Pass """ self._connected.add(websocket) while True: listener_task = asyncio.ensure_future(websocket.recv()) await asyncio.wait([listener_task]) try: message = listener_task.result() except websockets.ConnectionClosed: listener_task.cancel() self._connected.remove(websocket) return await self.recv_queue.put({'websocket': websocket, 'message': message}) async def recv_consumer(self): """ Pass """ while True: recv = await self.recv_queue.get() message = Message.from_json(recv['message']) websocket = recv['websocket'] if message.type[0] == '_': return method = getattr(self, message.type) if method.__qualname__.split('.')[0] == self.__class__.__name__: if message.data is not None: task = asyncio.ensure_future(method(**message.data)) else: task = asyncio.ensure_future(method()) def callback(future): reply = future.result() if reply is not None: self.send_queue.put_nowait({'websocket': websocket, 'message': reply}) task.add_done_callback(callback) async def reply_consumer(self): """ Pass """ while True: reply = await self.send_queue.get() message = reply['message'] websocket = reply['websocket'] if message.is_binary: if message.is_global: _ = [await ws.send(message.data) for ws in self._connected] else: await websocket.send(message.data) else: if message.is_global: _ = [await ws.send(message.json) for ws in self._connected] else: await websocket.send(message.json) def run(self): """ Pass """ start_server = websockets.serve(self.handler, '0.0.0.0', self.port) asyncio.get_event_loop().set_debug(self._debug) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() <file_sep>/setup.py from setuptools import setup, find_packages setup( name="Epics-Websocket", version="0.1.3", packages=find_packages(), install_requires=[ 'websockets', 'caproto' ], entry_points={ 'console_scripts':[ 'epicswebsocket = epics_websocket.scripts.start:start' ] } )<file_sep>/epics_websocket/epics_protocol.py import asyncio from epics_websocket.websocket_server import WebsocketServer, Message from caproto.threading.client import Context from functools import partial class EpicsServerProtocol(WebsocketServer): """ Scatterbrain websocket protocol. """ def __init__(self, port=6064, debug=False): super().__init__(port, debug=debug) self.ctx = Context() self.pvs = {} # self.sub_map = {} self.loop = asyncio.get_event_loop() async def subscribe_pv(self, pv_name): try: self.pvs[pv_name]['count'] += 1 except KeyError: pv_obj, = self.ctx.get_pvs(pv_name) sub = pv_obj.subscribe() self.pvs[pv_name] = { 'pv_obj': pv_obj, 'sub': sub, 'count': 0, 'callback': partial(self.callback, pv_name) } sub.add_callback(self.pvs[pv_name]['callback']) return Message('Subscribe', 'Success') async def unsubscribe_pv(self, pv): try: self.pvs[pv]['count'] -= 1 if self.pvs[pv]['count'] <= 0: del self.pvs[pv] except KeyError: pass async def put_pv(self, pv_name, value): self.pvs[pv_name]['pv_obj'].write(value) def callback(self, pv_name, response): self.loop.call_soon_threadsafe(self.send_queue.put_nowait,{ 'websocket': None, 'message': Message('update_pv', {'pv': pv_name, 'value': response.data[0]}, message_global=True) })
8540592a25cbd90e56b47591ce81a31ea359c08e
[ "Markdown", "Python" ]
6
Markdown
yeq71/epics_websocket
2412e8487ff3d87dc332658621a6df3e55054ebc
4a0b2beed06ee9714ea539b687cf6cb32a08785e
refs/heads/master
<file_sep><?php class ResponsesController extends \BaseController { /** * Display a listing of responses * * @return Response */ public function index() { $responses = Response::all(); return View::make('responses.index', compact('responses')); } /** * Show the form for creating a new response * * @return Response */ public function create() { return View::make('responses.create'); } /** * Store a newly created response in storage. * * @return Response */ public function store() { $validator = Validator::make($data = Input::all(), Response::$rules); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } Response::create($data); return Redirect::route('responses.index'); } /** * Display the specified response. * * @param int $id * @return Response */ public function show($id) { $response = Response::findOrFail($id); return View::make('responses.show', compact('response')); } /** * Show the form for editing the specified response. * * @param int $id * @return Response */ public function edit($id) { $response = Response::find($id); return View::make('responses.edit', compact('response')); } /** * Update the specified response in storage. * * @param int $id * @return Response */ public function update($id) { $response = Response::findOrFail($id); $validator = Validator::make($data = Input::all(), Response::$rules); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } $response->update($data); return Redirect::route('responses.index'); } /** * Remove the specified response from storage. * * @param int $id * @return Response */ public function destroy($id) { Response::destroy($id); return Redirect::route('responses.index'); } } <file_sep><?php class RequestsController extends \BaseController { /** * Display a listing of requests * * @return Response */ public function index() { $requests = Request::all(); return View::make('requests.index', compact('requests')); } /** * Show the form for creating a new request * * @return Response */ public function create() { return View::make('requests.create'); } /** * Store a newly created request in storage. * * @return Response */ public function store() { $validator = Validator::make($data = Input::all(), Request::$rules); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } Request::create($data); return Redirect::route('requests.index'); } /** * Display the specified request. * * @param int $id * @return Response */ public function show($id) { $request = Request::findOrFail($id); return View::make('requests.show', compact('request')); } /** * Show the form for editing the specified request. * * @param int $id * @return Response */ public function edit($id) { $request = Request::find($id); return View::make('requests.edit', compact('request')); } /** * Update the specified request in storage. * * @param int $id * @return Response */ public function update($id) { $request = Request::findOrFail($id); $validator = Validator::make($data = Input::all(), Request::$rules); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } $request->update($data); return Redirect::route('requests.index'); } /** * Remove the specified request from storage. * * @param int $id * @return Response */ public function destroy($id) { Request::destroy($id); return Redirect::route('requests.index'); } }
d1be0dc1d6a3f93d9d025301ef4aac7b25ca3372
[ "PHP" ]
2
PHP
redsh1ftr/jotus_broadside
6bc1a2abd4c30cb5f70625e288c6974cecf4a7c1
ef069a851e5d60671a307da675dc9391e00b8ad1
refs/heads/master
<repo_name>Rakeshpatel87p/front_end_challenge<file_sep>/app/config/routes.js import React from 'react'; import {BrowserRouter as Router, Route} from 'react-router-dom'; import TopViceHeader from '../components/TopViceHeader'; import ShowCard from '../components/Showcard'; const App = () => ( <Router> <div> <Route exact path="/" component={TopViceHeader} /> <Route exact path="/shows" component={ShowCard} /> <Route path="/shows/:id" render={({match}) => ( <h1> {match.params.id} </h1> )} /> </div> </Router> ); export default App; // import React from 'react'; // import {Router, Route, browserHistory} from 'react-router'; // import TopViceHeader from '../components/TopViceHeader'; // import ShowCard from '../components/Showcard'; // const routes = ( // <Router history={browserHistory}> // <Route path='/' component={TopViceHeader}> // <Route path='/shows' component={ShowCard} /> // <Route path='/shows/:id' component={ShowCard}/> // </Route> // </Router> // ) // export default routes; // import TopViceHeader from '../components/TopViceHeader'; // import Header from '../components/Header'; // import ShowCard from '../components/Showcard'; // import Shows from '../shows'; // import React from 'react'; // import { // BrowserRouter as Router, // Switch, // Route, // Link, // } from 'react-router-dom'; // class ModalSwitch extends React.Component{ // previousLocation = this.props.location, // componentWillUpdate(nextProps) { // const { location } = this.props // // set previousLocation if props.location is not modal // if ( // nextProps.history.action !== 'POP' && // (!location.state || !location.state.modal) // ) { // previousLocation = this.props.location // } // }, // render() { // const { location } = this.props // const isModal = !!( // location.state && // location.state.modal && // previousLocation !== location // not initial render // ) // return ( // <div> // <Switch location={isModal ? previousLocation : location}> // <Route exact path='/' component={TopViceHeader}/> // <Route path='/shows' component={ShowCard}/> // <Route path='/shows/:id' component={ImageView}/> // </Switch> // {isModal ? <Route path='/img/:id' component={Modal} /> : null} // </div> // ) // } // }; // const ImageView = ({ match }) => { // const show = Shows[parseInt(match.params.id, 10)] // if (!image) { // return <div>Image not found</div> // } // return ( // <div> // <h1>{show.title}</h1> // </div> // ) // } // const Modal = ({ match, history }) => { // const show = Shows[parseInt(match.params.id, 10)] // if (!image) { // return null // } // const back = (e) => { // e.stopPropagation() // history.goBack() // } // return ( // <div // onClick={back} // style={{ // position: 'absolute', // top: 0, // left: 0, // bottom: 0, // right: 0, // background: 'rgba(0, 0, 0, 0.15)' // }} // > // <div className='modal' style={{ // position: 'absolute', // background: '#fff', // top: 25, // left: '10%', // right: '10%', // padding: 15, // border: '2px solid #444' // }}> // <h1>{show.title}</h1> // <button type='button' onClick={back}> // Close // </button> // </div> // </div> // ) // } // const ModalGallery = () => ( // <Router> // <Route component={ModalSwitch} /> // </Router> // ) // export default ModalGallery
6b9efd38261a36088eec7fb738ea63ccfb439c93
[ "JavaScript" ]
1
JavaScript
Rakeshpatel87p/front_end_challenge
ae0eaefdb31cd96db95aec662b953101e207d606
84bf1f861e09f3f0036eb1590777fb60a991b2b7
refs/heads/master
<file_sep>package com.dgfip.jmarzin; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.parser.PdfTextExtractor; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator; public class LecteurPdfParLigne implements Iterator { private PdfReader lecteurPdf; private String[] lignes = new String[1]; private int page = 0; private int ligne = 1; private FileOutputStream fout; private ProgressMonitor progressMonitor; void ecrit(String s) { try { fout.write(s.getBytes()); } catch (IOException e) { e.printStackTrace(); } } void close() { try { fout.close(); } catch (IOException e) { e.printStackTrace(); } lecteurPdf.close(); progressMonitor.close(); } private String getChaine(int page) { String chaine = ""; try { chaine = PdfTextExtractor.getTextFromPage(this.lecteurPdf, page); } catch (IOException e) { e.printStackTrace(); } return chaine; } LecteurPdfParLigne() { FileNameExtensionFilter filter = new FileNameExtensionFilter("Fichier RAREFU", "pdf"); final JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileFilter(filter); fileChooser.setDialogTitle("Sélectionner le fichier RAREFU à traiter"); int returnVal = fileChooser.showOpenDialog(null); if(returnVal != JFileChooser.APPROVE_OPTION) { System.exit(0); } String path = fileChooser.getSelectedFile().getAbsolutePath(); try { lecteurPdf = new PdfReader(path); this.fout = new FileOutputStream(path.replaceAll("\\.pdf", ".csv")); ecrit("ROLE|MER|SOLDE|COMPTE|NOM|EXERCICE|ETAT|POSTE|PAGE|NOTES POSTE|NOTES DIRECTION\n"); } catch (IOException e) { e.printStackTrace(); } progressMonitor = new ProgressMonitor(null, "Traitement du fichier " + fileChooser.getSelectedFile().getName(), "", 0, 100); } @Override public boolean hasNext() { return !(ligne >= lignes.length && page >= this.lecteurPdf.getNumberOfPages()); } @Override public String next() { if (ligne >= lignes.length) { if (page >= this.lecteurPdf.getNumberOfPages()) { return null; } else { this.lignes = getChaine(++page).split("\n"); progressMonitor.setProgress(page * 100 / lecteurPdf.getNumberOfPages()); ligne = 0; } } return lignes[ligne++]; } @Override public void remove() { } } <file_sep>package com.dgfip.jmarzin; import java.util.Dictionary; import java.util.Hashtable; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Rarefu { private static Dictionary<String, String> dictionnaire = new Hashtable <>(); private static String lignePrecedente = ""; private static LecteurPdfParLigne lecteurPdfParLigne; private static String abbrev(String etat) { if (etat.contains("PRESCRITES")) { return "PRESCRITES"; } else if (etat.contains("COMPROMIS")) { return "COMPROMIS"; } else { return "PROC COLL"; } } private static boolean majDictionnaire(Pattern pattern, String ligne, boolean flush, String[] items) { Matcher matcher = pattern.matcher(ligne); if(matcher.matches()) { int i = 1; for (String item: items) { dictionnaire.put(item, matcher.group(i++)); } if (flush) { String ligneAEcrire = dictionnaire.get("role") + "|" + dictionnaire.get("mer") + "|" + dictionnaire.get("solde") + "|" + dictionnaire.get("compte") + "|" + dictionnaire.get("nom") + "|" + dictionnaire.get("exercice") + "|" + abbrev(dictionnaire.get("etat")) + "|" + dictionnaire.get("poste"); if (!ligneAEcrire.equals(lignePrecedente)) { lecteurPdfParLigne.ecrit(ligneAEcrire + "|" + dictionnaire.get("page") + "\n"); lignePrecedente = ligneAEcrire; } } return true; } else { return false; } } public static void main(String[] args) { lecteurPdfParLigne = new LecteurPdfParLigne(); dictionnaire.put("poste",""); dictionnaire.put("page", ""); dictionnaire.put("etat", ""); dictionnaire.put("exercice",""); dictionnaire.put("compte", ""); dictionnaire.put("nom", ""); dictionnaire.put("role", ""); dictionnaire.put("mer", ""); dictionnaire.put("solde", ""); Pattern[] patterns = {Pattern.compile(".*POSTE : (\\d{6}) +PAGE : (\\d+).*"), Pattern.compile(".*(COTES APPAREMMENT PRESCRITES|COTES DONT LE RECOUVREMENT PARAIT COMPROMIS|PROCEDURES {2}COLLECTIVES {2}EN COURS).*"), Pattern.compile(".*EXERCICE (\\d{4}).*"), Pattern.compile(".*NUMERO COMPTE : (\\d+) +NOM : (.*?) {2}.*"), Pattern.compile(" *(\\d+) +(\\d\\d/\\d\\d/\\d{4}) .*?(\\d+,\\d\\d).*")}; String[][]items = {{"poste","page"},{"etat"},{"exercice"},{"compte","nom"},{"role","mer","solde"}}; while (lecteurPdfParLigne.hasNext()) { String ligne = lecteurPdfParLigne.next(); int iitem = 0; for (Pattern pattern : patterns) { if (majDictionnaire(pattern, ligne, iitem == items.length - 1, items[iitem++])) { break; } } } lecteurPdfParLigne.close(); } }
c8419183f4fc8b88c16ab92e963fa68b8ee093ae
[ "Java" ]
2
Java
jmarzin/rarefu2
7267e38346567b2253f0bdea3abedacda9fe4606
01ceaaf4eec5b2841519ffecaa5f130b2d044c4c
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyShip : MonoBehaviour { public float turnSpeed = 1.0f;//Variable for the rotation of the object public float movementSpeed = 1.0f;//Moving forward public Transform target; // Start is called before the first frame update void Start() { //Adding to enemy list GameManager.instance.enemiesList.Add(this.gameObject); } //Updating movement void Update() { MoveFoward(); RotateTowards(target, false); } //Destroying gameObject public void Die() { GameManager.instance.enemiesList.Remove(this.gameObject); Destroy(this.gameObject); } //Always moving forward public void MoveFoward() { transform.Translate(new Vector3(0, movementSpeed * Time.deltaTime, 0)); } // Adjust rotation every update with heatseeking behavior protected void RotateTowards(Transform target, bool isInstant) {//Tracking position of player Vector3 direction = target.position - transform.position; direction.Normalize(); float zAngle = (Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg - 90); if (!isInstant) { Quaternion targetLocation = Quaternion.Euler(0, 0, zAngle); transform.rotation = Quaternion.RotateTowards(transform.rotation, targetLocation, turnSpeed * Time.deltaTime); } else {//Editing rotation based on location transform.rotation = Quaternion.Euler(0, 0, zAngle); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Asteroids : MonoBehaviour { public float turnSpeed = 1.0f; public float movementSpeed = 1.0f; public Transform target; // Start is called before the first frame update void Start() {//adding gameObject GameManager.instance.enemiesList.Add(this.gameObject); target = GameManager.instance.Player.transform; //Aim at the player at the start RotateTowards(target, true); } // Update is called once per frame void Update() { //Always moving MoveFoward(); } public void OnCollisionEnter2D(Collision2D otherObject)//Colliding with an object { if (otherObject.gameObject.name == "Parachute") { Destroy(otherObject.gameObject); Destroy(this.gameObject); } } //Destroy the gameObject void Die() { GameManager.instance.enemiesList.Remove(this.gameObject); Destroy(this.gameObject); } public void MoveFoward() { transform.Translate(new Vector3(0, movementSpeed * Time.deltaTime, 0)); } protected void RotateTowards(Transform target, bool isInstant) { Vector3 direction = target.position - transform.position; direction.Normalize(); float zAngle = (Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg - 90); if (!isInstant) { Quaternion targetLocation = Quaternion.Euler(0, 0, zAngle); transform.rotation = Quaternion.RotateTowards(transform.rotation, targetLocation, turnSpeed * Time.deltaTime); } else { transform.rotation = Quaternion.Euler(0, 0, zAngle); } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spawner : MonoBehaviour {//Lists of enemies of spawn and enemies public GameObject[] Enemies; public Transform[] spawnPoint; //Getting randon variables private int rand; private int randPosition; public static Spawner instance; //Spawn between times public float startTimeBtwSpawns = 2.0f; public float timeBtwSpawns = 2.0f; // Start is called before the first frame update void Start() {//Spawning at start timeBtwSpawns = startTimeBtwSpawns; } // Update is called once per frame void Update() {//time between spawning if(timeBtwSpawns <= 0) { rand = Random.Range(0, Enemies.Length); randPosition = Random.Range(0, spawnPoint.Length); Instantiate(Enemies[rand], spawnPoint[randPosition].transform.position, Quaternion.identity); timeBtwSpawns = startTimeBtwSpawns; }//Random spawning else { timeBtwSpawns -= Time.deltaTime; } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { private Transform tf;//Variable for the transform public float turnSpeed = 1.0f;//Variable for the rotation of the object public float movementSpeed = 1.0f; public GameObject bulletPrefab; public Transform FirePoint; // Start is called before the first frame update void Start() { tf = gameObject.GetComponent<Transform>(); //Load transform into the variable } // Update is called once per frame void Update() { if (Input.GetKey(KeyCode.UpArrow))//Move player forward { tf.position += tf.up * movementSpeed * Time.deltaTime; } if (Input.GetKey(KeyCode.RightArrow))//Rotate to the right { tf.Rotate(0, 0, -turnSpeed * Time.deltaTime); } if (Input.GetKey(KeyCode.LeftArrow))//Rotate to the left { tf.Rotate(0, 0, turnSpeed * Time.deltaTime); } if (Input.GetKeyDown(KeyCode.Space))//Shooting bullet gameObject { Shoot(); } } public void Shoot()//Shooting function { Instantiate(original:bulletPrefab, FirePoint.position, FirePoint.rotation); } public void OnCollisionEnter2D(Collision2D otherObject)//Colliding with an object { if (otherObject.gameObject.tag == "Enemy") { Destroy(otherObject.gameObject); Destroy(this.gameObject); } } public void OnCollisionExit2D(Collision2D otherObject)//Leaving the object collision { Debug.Log("The player died, so left the collision"); } //destroying player function void OnDestroy() { //Losing a life on destroy GameManager.instance.lives -= 1; if (GameManager.instance.lives > 0) { GameManager.instance.Respawn(); } else {//Display Game over Debug.Log("Game Over"); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { //Getting player public GameObject playerPrefab; public GameObject Player; public GameObject parachutePrefab; public GameObject EnemyPrefab; //Manager when game start public static GameManager instance; //Track score public int score = 0; public int lives = 3; //Track pause boolean public bool IsPaused = false; public GameObject[] enemyPrefab; //List of enemies in scene public List<GameObject> enemiesList = new List<GameObject>(); public void Awake() { if (instance == null) { instance = this; //Shows THIS of class in int variable } else { Destroy(this.gameObject); //Destroy Game manager attached to component Debug.LogError("Error: Tried to make second Game Manager"); } } public void Update() {//Quiting application if (Input.GetKeyDown(KeyCode.Escape)) { Application.Quit(); } //Respawning player on key press if (Input.GetKeyDown(KeyCode.P)) { // if (Player == null) //{ // Respawn(); //} Instantiate(parachutePrefab); } } public void Respawn()//Respawning the player { Player = Instantiate(playerPrefab); } }
ab6afcac41faf7a1d7052848eb735b5d49a4fdb6
[ "C#" ]
5
C#
KenFrueh/Asteroids
8140b3e4fd5d5077e3ad7ac7ae177f49f405c185
c56898f436f23f9666453eee4d3d9b6ac68c41a1
refs/heads/master
<file_sep>package com.nt; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HomeController extends HttpServlet{ @Override protected void service(HttpServletRequest req, HttpServletResponse res) { String loginCookie = null; try { Cookie[] ck = req.getCookies(); for(Cookie c: ck) { String key = c.getName(); if(key.equals("login")) { loginCookie = c.getValue(); } } } catch (Exception e) { e.printStackTrace(); } try { if(loginCookie != null && !loginCookie.isEmpty()) { RequestDispatcher rd = req.getRequestDispatcher("index.jsp"); rd.forward(req, res); }else{ RequestDispatcher rd = req.getRequestDispatcher("login.html"); rd.forward(req, res); } } catch (Exception e) { e.printStackTrace(); } } }<file_sep>package com.nt; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nt.dao.EmpDao; public class DeleteController extends HttpServlet{ @Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { int id = Integer.parseInt(req.getParameter("id")); boolean isDeleted = EmpDao.delete(id); if(isDeleted) { RequestDispatcher rd = req.getRequestDispatcher("delete.jsp"); req.setAttribute("isDeleted", isDeleted); rd.forward(req, res); } } catch (Exception e) { e.printStackTrace(); } RequestDispatcher rd = req.getRequestDispatcher("delete.jsp"); req.setAttribute("hasError", true); rd.forward(req, res); } } <file_sep>package com.nt; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nt.dao.EmpDao; import com.nt.entity.Employee; public class SelectAllController extends HttpServlet{ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<Employee> e = EmpDao.selectAll(); req.setAttribute("empList", e); RequestDispatcher rd = req.getRequestDispatcher("displayAll.jsp"); rd.forward(req, resp); } } <file_sep>package com.nt.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import com.nt.entity.Employee; import com.nt.utility.ConnectionFactory; public class EmpDao { public static List<Employee> selectAll() { try { Connection con = ConnectionFactory.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT * FROM emp"); ResultSet rs = ps.executeQuery(); List<Employee> emp = new ArrayList<>(); while(rs.next()) { emp.add(new Employee(rs.getInt(1), rs.getString(2), rs.getInt(3))); } return emp; }catch(Exception e) { e.printStackTrace(); } return null; } public static Employee select(int id) { try { Connection con = ConnectionFactory.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT * FROM emp WHERE eid = ?"); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if(rs.next()) { return new Employee(rs.getInt(1), rs.getString(2), rs.getInt(3)); } } catch (Exception e) { e.printStackTrace(); } return null; } public static boolean add(int id, String name, int sal) { try { Connection con = ConnectionFactory.getConnection(); PreparedStatement ps = con.prepareStatement("INSERT INTO employee.emp (eid, ename, esal) VALUES(?,?,?)"); ps.setInt(1, id); ps.setString(2, name); ps.setInt(3, sal); int result = ps.executeUpdate(); if(result > 0) return true; } catch (Exception e) { e.printStackTrace(); } return false; } public static boolean update(int id, int sal) { try { Connection con = ConnectionFactory.getConnection(); PreparedStatement ps = con.prepareStatement("UPDATE emp SET esal=? WHERE eid=?"); ps.setInt(1, sal); ps.setInt(2, id); int result = ps.executeUpdate(); if(result > 0) return true; } catch (Exception e) { e.printStackTrace(); } return false; } public static boolean delete(int id) { try { Connection con = ConnectionFactory.getConnection(); PreparedStatement ps = con.prepareStatement("DELETE from emp WHERE eid=?"); ps.setInt(1, id); int result = ps.executeUpdate(); if(result > 0) { return true; } } catch (Exception e) { e.printStackTrace(); } return false; } } <file_sep>package com.nt; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nt.dao.EmpDao; public class RegisterController extends HttpServlet{ @Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { int id = Integer.parseInt(req.getParameter("id")); String name = req.getParameter("name"); int sal = Integer.parseInt(req.getParameter("sal")); boolean isAdded = EmpDao.add(id, name, sal); if(isAdded) { RequestDispatcher rd = req.getRequestDispatcher("register.jsp"); req.setAttribute("isRegistered", isAdded); rd.forward(req, res); } } catch (Exception e) { System.out.println("Something went wrong: "+e.getMessage()); } RequestDispatcher rd = req.getRequestDispatcher("register.jsp"); req.setAttribute("hasError", true); rd.forward(req, res); } } <file_sep>package com.nt; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nt.dao.EmpDao; public class UpdateController extends HttpServlet{ @Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { int id = Integer.parseInt(req.getParameter("id")); int sal = Integer.parseInt(req.getParameter("sal")); boolean isUpdated = EmpDao.update(id, sal); if(isUpdated) { RequestDispatcher rd = req.getRequestDispatcher("update.jsp"); req.setAttribute("isUpdated", isUpdated); rd.forward(req, res); } } catch (Exception e) { e.printStackTrace(); } RequestDispatcher rd = req.getRequestDispatcher("update.jsp"); req.setAttribute("hasError", true); rd.forward(req, res); } } <file_sep>package com.nt; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nt.dao.EmpDao; import com.nt.entity.Employee; public class SelectController extends HttpServlet{ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { int id = Integer.parseInt(req.getParameter("id")); boolean isFound = false; Employee emp = EmpDao.select(id); if(emp != null) { isFound = true; req.setAttribute("isFound", isFound); req.setAttribute("emp", emp); RequestDispatcher rd = req.getRequestDispatcher("display.jsp"); rd.forward(req, resp); }else { req.setAttribute("isFound", isFound); RequestDispatcher rd = req.getRequestDispatcher("display.jsp"); rd.forward(req, resp); } } catch (Exception e) { e.printStackTrace(); } } } <file_sep># Java-crud-app ![intial screen for Java-crud-app](readme-img/main-page2.png) ## Description This is Java Servlet Web Application that utilizes CRUD operations on sql database in MVC structure. **note: can login using same name and pass. not fully configured. ## Install and Run: To run this app in eclipse EE: - `File` -> Open project from file system - Select the `java-crud-app.zip` - Right Click on project -> `Run As` -> `Run on Server`. - It was tested on `apache tomcat 8.5` ## Functionality This application enables the user to: - Display all the data in table - Register new record in database - Update part of the record - Delete records - Look for particular records - Login page (partial) ## External JAR Used Can be found in pom.xml - Servlet-API - To use servlet app. - MYSQL Driver - To communicate with MYSQL database. - JSTL 1.2 - For jsp expressions. ## Developer Notes ### The default database is created in Connectionfactory.java using the following parameter: ``` DriverManager.getConnection("jdbc:mysql://localhost:3306/employee", "root", "root"); //username and Password are the last two parameters. ``` ### The default database: -employee ### The default table used for implementaion: Table name: emp. | eid | ename | esal | |---|---|----| |101|Sam|1000|| ### Database and table creation(SQL): ``` CREATE SCHEMA `employee` ; ``` ``` CREATE TABLE `emp` ( `eid` int NOT NULL, `ename` varchar(255) DEFAULT NULL, `esal` int DEFAULT NULL, PRIMARY KEY (`eid`) ) ``` ## Feature Completed Since First Iteration - Added CRUD system in MVC structure - Styling and formatting - added card system for form input - added subtle alert system - Added Navigation bar - Added error handling for invalid input - Used Maven to create project. - Added `login` ability. - added login and user management using `session` and cookies. - added `filter` to \home route
62f3ae2bada901b3f99fe1d9b4dab5f938f96cff
[ "Markdown", "Java" ]
8
Java
rival104/java-crud-app
ddcecb9785398fa6d072d4c009ba248360dcdb41
f18e50cbe1e7973c28c2bd3582c3fa99f1092de4
refs/heads/master
<repo_name>sagar2911/os_programs<file_sep>/3_rectangle_perimeter.sh # 3. Write a shell script to calculate area and permiter of a rectangle. It should take the ccalues from command line. echo "Enter length of rectangle: " read l echo "Enter breadth of rectangle: " read b p=`expr $l + $b` p=`expr 2 \* $p` a=`expr $l \* $b` echo "" echo "Perimeter of rectangle is $p units" echo "Area of rectangle is $a sq. units" echo "" <file_sep>/1_simple_interest.sh # 1. Write a shell program to calculate simple interest p=1300 r=10 t=2 s=`expr $p \* $r \* $t` s=`expr $s / 100` echo "Priciple is Rs."$p echo "Rate is "$p"%" echo "Time is "$t" years" echo -n "Simple Interest = Rs.$s"
cfd9d98b438d692c374761472a536eabc51c58f0
[ "Shell" ]
2
Shell
sagar2911/os_programs
9c8be332e42e3c8fbfe95358ab3d3168944e44d0
2c94e33bf62586cfcc23fa3da9bab56bca365d0b
refs/heads/master
<repo_name>mwilsonoliveira/devpleno-sigep<file_sep>/README.md # Sigep Test App para consulta de ceps na API SIGEP dos correios. <file_sep>/examples/buscar-cep.js var sigep = require('../index') sigep('dev') .then(function(sigepClient){ sigepClient .consultarCEP('89053-030') .then(function(endereco){ console.log(endereco) }) .catch(function(err){ console.log(err) }) }) .catch(function(err){ console.log(err) })
6f2cbe621fec6868f3ec40c01e8204258cd1a247
[ "Markdown", "JavaScript" ]
2
Markdown
mwilsonoliveira/devpleno-sigep
f41b53d17aed572eb487a8da8918aa863156ae45
40e8aff8cac6945e3912a684e26ff903a44baaba
refs/heads/master
<file_sep>import kivy print('Kivy World')
3c24f091ce57743839ef2589020754f951f25e2e
[ "Python" ]
1
Python
abydesuyo/kivy-projects
2cd6b42b75b01a04d38ff1408c3d88e014b3dbe9
5e4386d6d8b454caf71ec6d1d9bda4e5c724fa99
refs/heads/master
<file_sep><?php class Students extends CI_Controller{ public function index(){ if(!$this->session->userdata('logged_in')){ redirect('users/login'); } $data['title'] = 'Student'; $std_data['students'] = $this->school_model->get_all(); $this->load->view('templates/header',$data); $this->load->view('student/search', $std_data); $this->load->view('templates/footer'); } public function add(){ $data_header['title'] = 'add Student '; //get all Session $data['session'] = $this->school_model->get_all_sessions(); $data['class'] = $this->school_model->get_all_class(); $data['section'] = $this->school_model->get_all_section(); $this->load->view('templates/header',$data_header); $this->load->view('student/add', $data); $this->load->view('templates/footer'); } public function add_student() { //var_dump($_POST);exit; // Check login // if(!$this->session->userdata('logged_in')){ // redirect('users/login'); // } //array(20) { ["session_id"]=> string(1) "1" ["class_id"]=> string(1) "1" ["section_id"]=> string(1) "1" // ["rool_no"]=> string(2) "12" ["registration_no"]=> string(5) "09-89" ["doa"]=> string(10) "2017-02-11" // ["admission_fee"]=> string(4) "1000" ["tuition_fee"]=> string(4) "2000" ["total_fee"]=> string(4) "3000" // ["std_photo"]=> string(15) "08122012295.jpg" ["student_name"]=> string(13) "<NAME>" ["gender"]=> string(6) "Female" // ["father_cnic"]=> string(13) "3660237111955" ["contact_no"]=> string(12) "0300-0011556" ["prev_school"]=> string(5) "Hawks" // ["father_name"]=> string(12) "<NAME>" ["dob"]=> string(10) "2000-03-12" // ["b_form"]=> string(12) "366029099999" ["religion"]=> string(6) "Muslim" ["address"]=> string(6) "Multan" } $this->form_validation->set_rules('admission_fee', 'Admission Fee', 'required'); $this->form_validation->set_rules('tuition_fee', 'Tuition Fee', 'required'); $this->form_validation->set_rules('total_fee', 'Total Fee', 'required'); $this->form_validation->set_rules('student_name', 'Student Name', 'required'); $this->form_validation->set_rules('gender', 'Gender', 'required'); $this->form_validation->set_rules('father_cnic', 'Father CNIC', 'required'); $this->form_validation->set_rules('contact_no', 'Contact No', 'required'); $this->form_validation->set_rules('prev_school', 'Previous School', 'required'); $this->form_validation->set_rules('doa', 'Date of Admission', 'required'); $this->form_validation->set_rules('father_name', 'Father Name', 'required'); $this->form_validation->set_rules('dob', 'date of Birth', 'required'); $this->form_validation->set_rules('religion', 'Religion', 'required'); $this->form_validation->set_rules('b_form', 'Bay Form', 'required'); $this->form_validation->set_rules('address', 'Address', 'required'); $this->form_validation->set_rules('roll_no', 'Roll Number', 'required'); $this->form_validation->set_rules('registration_no', 'Registration Number', 'required'); if($this->form_validation->run() === TRUE){ $this->student_model->add_student(); // Set message $this->session->set_flashdata('student_created', 'Student record has been created'); } redirect('students/search'); } public function attendance(){ $data_header['title'] = 'add Student '; //get all Session $data['session'] = $this->school_model->get_all_sessions(); $data['class'] = $this->school_model->get_all_class(); $data['section'] = $this->school_model->get_all_section(); $this->load->view('templates/header',$data_header); $this->load->view('student/attendance', $data); $this->load->view('templates/footer'); } public function search(){ $data['title'] = 'Student'; $data['session'] = $this->school_model->get_all_sessions(); $data['class'] = $this->school_model->get_all_class(); $data['section'] = $this->school_model->get_all_section(); $data['students'] = $this->student_model->get_all(); $this->load->view('templates/header',$data); $this->load->view('student/search', $data); $this->load->view('templates/footer'); } } <file_sep><?php class School_model extends CI_Model{ public function __construct() { $this->load->database(); } // get all Session details public function get_all_sessions(){ $query = $this->db->get_where('session', array('school_id' => 1)); return $query->result_array(); } // get all Session details public function get_all_class(){ $query = $this->db->get('class'); return $query->result_array(); } // get all Session details public function get_all_section(){ $query = $this->db->get('section'); return $query->result_array(); } } ?><file_sep> <div class="col-md-10"> <h1>Student Detail List</h1> </div> <div class="col-md-2"> <a href="<?php echo base_url();?>students/add"><button type="button" class="btn btn-primary">Add Student</button> </a> </div> <br><br><br><br> <div class="chit-chat-layer1 row"> <div class="col-md-12"> <div class="work-progres"> <div class="chit-chat-heading"> <div class="row"> <div class="col-md-4"> <div class="form-group" > <!-- <label>Session:</label> --> <select name="Session" id="Session" class="form-control" > <option value="" >Session</option> <?php foreach ($session as $s) { ?> <option value="<?php echo $s['id'];?>" ><?php echo $s['name'];?></option> <?php }?> </select> </div> </div> <div class="col-md-4"> <div class="form-group"> <!-- <label>Course:</label> --> <select name="Class" id="Class" class="form-control" > <option value="" >Class</option> <?php foreach ($class as $s) { ?> <option value="<?php echo $s['id'];?>" ><?php echo $s['name'];?></option> <?php }?> </select> </div> </div> <div class="col-md-4"> <div class="form-group"> <!-- <label>Section:</label> --> <select name="Section" id="Section" class="form-control" > <option value="" >Section</option> <?php foreach ($section as $s) { ?> <option value="<?php echo $s['id'];?>" ><?php echo $s['name'];?></option> <?php }?> </select> </div> </div> </div> </div> <div class="table-responsive"> <table class="table"> <tr> <th class="header"><input type="checkbox"> <i class="icon-sort"></i></th> <th class="header"> Student Name<hr style="margin: 0">Father Name <i class="icon-sort"></i></th> <th class="header"> Roll No<hr style="margin: 0">Registration No <i class="icon-sort"></i></th> <th class="header"> Date of Birth<i class="icon-sort"></i></th> <th class="header"> Gender <i class="icon-sort"></i></th> <th class="header"> B-form<hr style="margin: 0">Father CNIC <i class="icon-sort"></i></th> <th class="header"> Contact No<hr style="margin: 0">Address <i class="icon-sort"></i></th> <th class="header"> Action <i class="icon-sort"></i></th> </tr> <tbody> <?php foreach ($students as $std) {?> <tr> <td><input type="checkbox"> </td> <td> <?php echo $std['name'];?> <br> <?php echo $std['father_name'];?> </td> <td> <?php echo $std['roll_no'];?> <br> <?php echo $std['registration_no'];?> </td> <td> <?php echo $std['date_of_birth'];?> </td> <td> <?php echo $std['gender'];?> </td> <td> <?php echo $std['b_form'];?> <br> <?php echo $std['father_cnic'];?> </td> <td> <?php echo $std['contact_no'];?> <br> <?php echo $std['address'];?> </td> <td> <div class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Option <span class="caret"></span></button> <ul class="dropdown-menu dropdown-menu-right"> <li><a href="{% url 'student:fee_slip_form' %}">Fee slip</a></li> <li><a href="#">Promote</a></li> <li><a href="#">Admission Form</a></li> </ul> </div> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> <file_sep>-- phpMyAdmin SQL Dump -- version 4.5.2 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jun 20, 2017 at 06:51 PM -- Server version: 10.1.13-MariaDB -- PHP Version: 5.6.21 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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 */; -- -- Database: `ci_school` -- -- -------------------------------------------------------- -- -- Table structure for table `students` -- CREATE TABLE `students` ( `id` int(11) NOT NULL, `name` varchar(100) NOT NULL, `father_name` varchar(100) NOT NULL, `b_form` varchar(15) NOT NULL, `father_cnic` varchar(15) NOT NULL, `gender` varchar(6) NOT NULL, `date_of_birth` date NOT NULL, `contact_no` varchar(12) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `students` -- INSERT INTO `students` (`id`, `name`, `father_name`, `b_form`, `father_cnic`, `gender`, `date_of_birth`, `contact_no`) VALUES (1, 'ahsan', 'riaza', '36660', '009889', 'male', '2017-06-01', '099900'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `email` varchar(255) NOT NULL, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `register_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `email`, `username`, `password`, `register_date`) VALUES (1, '<EMAIL>', '<PASSWORD>', '<PASSWORD>', '2017-04-10 13:14:31'), (2, '<EMAIL>', 'john', '<PASSWORD>', '2017-04-10 14:12:14'), (3, '<EMAIL>', 'ah<PASSWORD>', '<PASSWORD>', '2017-06-19 18:18:04'); -- -- Indexes for dumped tables -- -- -- Indexes for table `students` -- ALTER TABLE `students` ADD PRIMARY KEY (`id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `students` -- ALTER TABLE `students` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; /*!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><div class="prices-head"> <h2>Student Registration Form</h2> </div> <?php echo form_open('students/add_student'); ?> <!--mainpage chit-chating--> <div class="chit-chat-layer1"> <div class="col-md-3 chit-chat-layer1-left"> <div class="work-progres"> <div class="chit-chat-heading"> Selection </div> <div class="form-group"> <!-- <label>Session:</label>--> <select name="session_id" id="Session" class="form-control" tabindex="1"> <option value="">Session</option> <?php foreach ($session as $s) { ?> <option value="<?php echo $s['id']; ?>"><?php echo $s['name']; ?></option> <?php } ?> </select> </div> <div class="form-group"> <!-- <label>Course:</label> --> <select name="class_id" id="Class" class="form-control" tabindex="2"> <option value="">Class</option> <?php foreach ($class as $s) { ?> <option value="<?php echo $s['id']; ?>"><?php echo $s['name']; ?></option> <?php } ?> </select> </div> <div class="form-group"> <!-- <label>Section:</label> --> <select name="section_id" id="Section" class="form-control" tabindex="3"> <option value="">Section</option> <?php foreach ($section as $s) { ?> <option value="<?php echo $s['id']; ?>"><?php echo $s['name']; ?></option> <?php } ?> </select> </div> <!-- <div class="form-group"> <button type="button" class="btn btn-primary">Submit</button> </div> --> </div> </div> </div> <div class="col-md-3 chit-chat-layer1-rit"> <div class="work-progres"> <div class="chit-chat-heading"> Admission Detail </div> <div class="form-group"> <input type="text" name="roll_no" class="form-control" required placeholder="Enter Student Roll no" tabindex="4"> </div> <div class="form-group"> <input type="text" name="registration_no" class="form-control" required placeholder="Enter Student Registration No" tabindex="5"> </div> <div class="form-group"> <input type="date" name="doa" class="form-control" required placeholder="Date of Admission" tabindex="6"> </div> </div> </div> <div class="col-md-3 chit-chat-layer1-rit"> <div class="work-progres"> <div class="chit-chat-heading"> Fee Detail </div> <div class="form-group"> <!-- <label>Admission Fee</label> --> <input type="text" name="admission_fee" class="form-control" required placeholder="Admission Fee" tabindex="7"> </div> <div class="form-group"> <!-- <label>Tution Fee</label> --> <input type="text" name="tuition_fee" class="form-control" required placeholder="Tuition Fee" tabindex="8"> </div> <div class="form-group"> <!-- <label>Total</label> --> <input type="text" name="total_fee" class="form-control" required placeholder="Total Fee"> </div> </div> </div> <div class="col-md-3 chit-chat-layer1-rit"> <div class="work-progres"> <div class="chit-chat-heading"> Photo </div> <div class="form-group"> <img src="<?php echo base_url(); ?>images/1.jpg" width="100%" height="100px"> <input type="file" name="std_photo"> </div> </div> </div> <div class="clearfix"></div> <!--main page chit chating end here--> <div class="chit-chat-layer1"> <div class="col-md-6 chit-chat-layer1-left"> <div class="work-progres"> <div class="chit-chat-heading"> Student Personal Info </div> <form> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label>Name:</label> <input class="form-control" name="student_name" type="text" required placeholder="Enter Student's Name" tabindex="10"> </div> <div class="form-group"> <label>Gender:</label> <select name="gender" id="Gender" class="form-control" required tabindex="11"> <option value="Male">Male</option> <option value="Female">Female</option> </select> </div> <div class="form-group"> <label>DOB:</label> <input class="form-control" type="date" name="dob" required placeholder="Enter Student's DOB" tabindex="12"> </div> <div class="form-group"> <label>Bay-Form:</label> <input class="form-control" type="text" name="b_form" required placeholder="_____-_______-_" tabindex="13"> </div> <div class="form-group"> <label>Prev School:</label> <input class="form-control" name="prev_school" type="text" placeholder="Enter Previous School Name" tabindex="14"> </div> <div class="form-group"> <label>Prev Class Name:</label> <input class="form-control" name="prev_class_name" type="text" placeholder="Enter Previous Class Name" tabindex="15"> </div> <div class="form-group"> <label>Cast:</label> <input class="form-control" name="cast" type="text" placeholder="Enter Student's Family Cast" tabindex="16"> </div> <div class="form-group"> <label>Religion:</label> <select name="religion" id="religion" class="form-control" tabindex="17"> <option value="Muslim">Muslim</option> <option value="Non Muslim">Non Muslim</option> </select> </div> </div> </div> </div> </div> </div> <div class="col-md-6 chit-chat-layer1-rit"> <div class="work-progres"> <div class="chit-chat-heading"> Student Family Info </div> <form> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label>Father Name:</label> <input class="form-control" type="text" name="father_name" required tabindex="18" placeholder="Enter Student's Father Name"> </div> <div class="form-group"> <label>Father CNIC:</label> <input class="form-control" name="father_cnic" type="text" required tabindex="19" placeholder="_____-_______-_"> </div> <div class="form-group"> <label>Father Profession:</label> <input class="form-control" type="text" name="father_prof" tabindex="20" placeholder="Enter Student's Father Profession"> </div> <div class="form-group"> <label>Mother Name:</label> <input class="form-control" type="text" name="mother_name" tabindex="21" placeholder="Enter Student's Mother Name"> </div> <div class="form-group"> <label>Guardian is?</label> <input type="radio" name="guardian_is" value="father" selected tabindex="22">Father <input type="radio" name="guardian_is" value="mother" >Mother <input type="radio" name="guardian_is" value="other">other </div> <div class="form-group"> <label>Guardian Name:</label> <input class="form-control" type="text" name="guardian_name" tabindex="23" placeholder="Enter Student's Guardian Name"> </div> <div class="form-group"> <label>Guardian CNIC:</label> <input class="form-control" type="text" name="guardian_cnic" tabindex="24" placeholder="Enter Student's Guardian CNIC"> </div> <div class="form-group"> <label>Contact No:</label> <input class="form-control" name="contact_no" type="text" required tabindex="25" placeholder="Enter Student's Contact No"> </div> <div class="form-group"> <label>Address:</label> <textarea class="form-control" name="address" rows="5" id="text" required tabindex="26" placeholder="Enter Student's Permanent Address"></textarea> </div> </div> </div> </div> </div> <div class="clearfix"></div> <!--main page chit chating end here--> <div class="form-group" style="float: right"> <button type="button" class="btn btn-warning">Reset</button> <button type="submit" class="btn btn-primary">Save</button> <a href=""> <button type="button" class="btn btn-primary">Save and Continue</button> </a> </div> <?php echo form_close(); ?><file_sep><?php class Student_model extends CI_Model { public function __construct() { $this->load->database(); } public function get_all() { $this->db->order_by('id', 'DESC'); $query = $this->db->get('students'); return $query->result_array(); } // public function save_student_personal_info() // { // // } // // public function save_student_family_info() // { // // } // // public function save_student_admission_info() // { // // } // // public function save_student_fee_info() // { // // } public function save() { $personal_info_data = array( 'full_name' => $this->input->post('student_name'), 'bay_form' => $this->input->post('b_form'), 'gender' => $this->input->post('gender'), 'date_of_birth' => $this->input->post('dob'), 'slug' => '', 'prev_school' => $this->input->post(''), 'prev_class_name' => $this->input->post(''), 'user_id' => 1 ); $this->db->insert('students', $personal_info_data); $family_info_data = array( 'student_id' => 1, 'father_name' => $this->input->post('father_name'), 'father_cnic' => $this->input->post('father_cnic'), 'father_profession' => $this->input->post('father_profession'), 'address' => $this->input->post('address'), 'contact_no' => $this->input->post('contact_no'), 'mother_name' => $this->input->post('mother_name'), 'family_income' => $this->input->post('family_income'), 'religion' => $this->input->post('religion'), 'cast' => $this->input->post('cast') ); $this->db->insert('students', $family_info_data); $admission_info_data = array( 'student_id' => 1, 'school_id' => 1, 'session_id' => $this->input->post('session_id'), 'class_id' => $this->input->post('class_id'), 'section_id' => $this->input->post('section_id'), 'roll_no' => $this->input->post('roll_no'), 'registration_no' => $this->input->post('registration_no'), 'date_of_admission' => $this->input->post('date_of_admission') ); $this->db->insert('students', $admission_info_data); $fee_info_data = array( 'student_id' => 1, 'admission_fee' => $this->input->post('admission_fee'), 'tuition_fee' => $this->input->post('tuition_fee'), 'prev_dues' => $this->input->post('prev_dues') ); $this->db->insert('students', $fee_info_data); return 1; } } <file_sep></div> </div> <!--inner block end here--> <!--copy rights start here--> <div class="copyrights"> <p>© 2017 Aatir Sky Tech</p> </div> <!--COPY rights end here--> </div> <!--slider menu--> <div class="sidebar-menu"> <div class="logo"> <a href="#" class="sidebar-icon"> <span class="fa fa-bars"></span> </a> <a href="#"> <span id="logo" ></span> <!--<img id="logo" src="" alt="Logo"/>--> </a> </div> <div class="menu"> <ul id="menu" > <li id="menu-home" ><a href="<?php echo base_url();?>home"><i class="fa fa-tachometer"></i><span>Home</span></a></li> <li><a href="<?php echo base_url();?>students"><i class="fa fa-user"></i><span>Student</span><span class="fa fa-angle-right" style="float: right"></span></a> <ul> <li><a href="<?php echo base_url();?>students/add">Add</a></li> <li><a href="<?php echo base_url();?>students/search">Search</a></li> <li><a href="<?php echo base_url();?>students/attendance">Attendance</a></li> </ul> </li> <!-- <li id="menu-comunicacao" ><a href="#"><i class="fa fa-book nav_icon"></i><span>Element</span><span class="fa fa-angle-right" style="float: right"></span></a>--> <!-- <ul id="menu-comunicacao-sub" >--> <!-- <li id="menu-mensagens" style="width: 120px" ><a href="buttons.html">Buttons</a>--> <!-- </li>--> <!-- <li id="menu-arquivos" ><a href="typography.html">Typography</a></li>--> <!-- <li id="menu-arquivos" ><a href="icons.html">Icons</a></li>--> <!-- </ul>--> <!-- </li>--> <!-- <li><a href="maps.html"><i class="fa fa-map-marker"></i><span>Maps</span></a></li>--> <!-- <li id="menu-academico" ><a href="#"><i class="fa fa-file-text"></i><span>Pages</span><span class="fa fa-angle-right" style="float: right"></span></a>--> <!-- <ul id="menu-academico-sub" >--> <!-- <li id="menu-academico-boletim" ><a href="login.html">Login</a></li>--> <!-- <li id="menu-academico-avaliacoes" ><a href="signup.html">Sign Up</a></li>--> <!-- </ul>--> <!-- </li>--> <!----> <!-- <li><a href="charts.html"><i class="fa fa-bar-chart"></i><span>Charts</span></a></li>--> <!-- <li><a href="#"><i class="fa fa-envelope"></i><span>Mailbox</span><span class="fa fa-angle-right" style="float: right"></span></a>--> <!-- <ul id="menu-academico-sub" >--> <!-- <li id="menu-academico-avaliacoes" ><a href="inbox.html">Inbox</a></li>--> <!-- <li id="menu-academico-boletim" ><a href="inbox-details.html">Compose email</a></li>--> <!-- </ul>--> <!-- </li>--> <!-- <li><a href="#"><i class="fa fa-cog"></i><span>System</span><span class="fa fa-angle-right" style="float: right"></span></a>--> <!-- <ul id="menu-academico-sub" >--> <!-- <li id="menu-academico-avaliacoes" ><a href="404.html">404</a></li>--> <!-- <li id="menu-academico-boletim" ><a href="blank.html">Blank</a></li>--> <!-- </ul>--> <!-- </li>--> <!-- <li><a href="#"><i class="fa fa-shopping-cart"></i><span>E-Commerce</span><span class="fa fa-angle-right" style="float: right"></span></a>--> <!-- <ul id="menu-academico-sub" >--> <!-- <li id="menu-academico-avaliacoes" ><a href="product.html">Product</a></li>--> <!-- <li id="menu-academico-boletim" ><a href="price.html">Price</a></li>--> <!-- </ul>--> <!-- </li>--> </ul> </div> </div> <div class="clearfix"> </div> </div> <!--slide bar menu end here--> <script> var toggle = true; $(".sidebar-icon").click(function() { // alert("sidebar"); if (toggle) { $(".page-container").addClass("sidebar-collapsed").removeClass("sidebar-collapsed-back"); $("#menu span").css({"position":"absolute"}); } else { $(".page-container").removeClass("sidebar-collapsed").addClass("sidebar-collapsed-back"); setTimeout(function() { $("#menu span").css({"position":"relative"}); }, 400); } toggle = !toggle; }); </script> <!--scrolling js-- <script src="<?php echo base_url();?>js/jquery.nicescroll.js"></script> <script src="<?php echo base_url();?>js/scripts.js"></script> <!--//scrolling js--> <script src="<?php echo base_url();?>js/bootstrap.js"> </script> <!-- mother grid end here--> </body> </html> <file_sep>-- phpMyAdmin SQL Dump -- version 4.5.2 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jun 29, 2017 at 03:47 PM -- Server version: 10.1.13-MariaDB -- PHP Version: 5.6.21 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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 */; -- -- Database: `ci_school` -- -- -------------------------------------------------------- -- -- Table structure for table `class` -- CREATE TABLE `class` ( `id` int(11) NOT NULL, `session_id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `number` int(11) NOT NULL, `tuition_fee` int(11) NOT NULL, `admission_fee` int(11) NOT NULL, `created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `class` -- INSERT INTO `class` (`id`, `session_id`, `name`, `number`, `tuition_fee`, `admission_fee`, `created_on`) VALUES (1, 1, '10th', 10, 1000, 1000, '2017-06-21 16:00:17'); -- -------------------------------------------------------- -- -- Table structure for table `config` -- CREATE TABLE `config` ( `site_title` varchar(255) NOT NULL, `sub_title` varchar(255) NOT NULL, `address` varchar(255) NOT NULL, `logo_url` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `school` -- CREATE TABLE `school` ( `id` int(11) NOT NULL, `full_name` varchar(255) NOT NULL, `nick_name` varchar(255) NOT NULL, `address` varchar(255) NOT NULL, `contact_no` varchar(255) NOT NULL, `mobile_no` varchar(255) NOT NULL, `logo_url` varchar(255) NOT NULL, `slogan` varchar(255) NOT NULL, `slug` varchar(255) NOT NULL, `contact_person_name` varchar(255) NOT NULL, `user_id` int(11) NOT NULL, `created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `school` -- INSERT INTO `school` (`id`, `full_name`, `nick_name`, `address`, `contact_no`, `mobile_no`, `logo_url`, `slogan`, `slug`, `contact_person_name`, `user_id`, `created_on`) VALUES (1, 'Hawks School System Mailsi', 'Hawks', '<NAME>', '0000', '000', '', '', 'hawks', 'azhar', 1, '2017-06-21 15:58:50'), (2, '', '', '', '', '', '', '', '', '', 0, '2017-06-21 15:58:50'); -- -------------------------------------------------------- -- -- Table structure for table `section` -- CREATE TABLE `section` ( `id` int(11) NOT NULL, `class_id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `description` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `section` -- INSERT INTO `section` (`id`, `class_id`, `name`, `description`) VALUES (1, 1, 'Pinky', 'any'); -- -------------------------------------------------------- -- -- Table structure for table `session` -- CREATE TABLE `session` ( `id` int(11) NOT NULL, `school_id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `description` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `session` -- INSERT INTO `session` (`id`, `school_id`, `name`, `description`) VALUES (1, 1, '2017-19', 'any'); -- -------------------------------------------------------- -- -- Table structure for table `students_attendance` -- CREATE TABLE `students_attendance` ( `student_id` int(11) NOT NULL, `date` date NOT NULL, `status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '1- present, 0-absent, 2-leave', `create_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `user_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `students_leave` -- CREATE TABLE `students_leave` ( `student_id` int(11) NOT NULL, `date` date NOT NULL, `leave_reason` varchar(255) NOT NULL, `leave_description` text NOT NULL, `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `user_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `student_admission_info` -- CREATE TABLE `student_admission_info` ( `student_id` int(11) NOT NULL, `school_id` int(11) NOT NULL, `session_id` int(11) NOT NULL, `class_id` int(11) NOT NULL, `section_id` int(11) NOT NULL, `roll_no` int(11) NOT NULL, `registration_no` int(11) NOT NULL, `date_of_admission` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `student_admission_info` -- INSERT INTO `student_admission_info` (`student_id`, `school_id`, `session_id`, `class_id`, `section_id`, `roll_no`, `registration_no`, `date_of_admission`) VALUES (0, 0, 0, 0, 0, 0, 0, '2017-06-28 18:40:00'); -- -------------------------------------------------------- -- -- Table structure for table `student_family_info` -- CREATE TABLE `student_family_info` ( `student_id` int(11) NOT NULL, `father_name` varchar(100) NOT NULL, `father_cnic` varchar(15) NOT NULL, `contact_no` varchar(15) NOT NULL, `father_profession` varchar(50) NOT NULL, `address` text NOT NULL, `mother_name` varchar(100) NOT NULL, `family_income` int(11) NOT NULL, `religion` varchar(10) NOT NULL, `cast` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `student_family_info` -- INSERT INTO `student_family_info` (`student_id`, `father_name`, `father_cnic`, `contact_no`, `father_profession`, `address`, `mother_name`, `family_income`, `religion`, `cast`) VALUES (0, '', '', '', '', '', '', 0, '', ''); -- -------------------------------------------------------- -- -- Table structure for table `student_fee_info` -- CREATE TABLE `student_fee_info` ( `student_id` int(11) NOT NULL, `admission_fee` int(11) NOT NULL, `tuition_fee` int(11) NOT NULL, `prev_dues` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `student_fee_info` -- INSERT INTO `student_fee_info` (`student_id`, `admission_fee`, `tuition_fee`, `prev_dues`) VALUES (0, 0, 0, 0); -- -------------------------------------------------------- -- -- Table structure for table `student_personal_info` -- CREATE TABLE `student_personal_info` ( `id` int(11) NOT NULL, `full_name` varchar(100) NOT NULL, `gender` varchar(6) NOT NULL, `date_of_birth` date NOT NULL, `bay_form` varchar(15) NOT NULL, `prev_school` varchar(100) NOT NULL, `prev_class_name` varchar(50) NOT NULL, `slug` varchar(100) NOT NULL, `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `user_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `student_personal_info` -- INSERT INTO `student_personal_info` (`id`, `full_name`, `gender`, `date_of_birth`, `bay_form`, `prev_school`, `prev_class_name`, `slug`, `create_at`, `user_id`) VALUES (1, '', '', '0000-00-00', '', '', '', '', '2017-06-28 18:34:42', 0); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `email` varchar(255) NOT NULL, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `register_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `email`, `username`, `password`, `register_date`) VALUES (1, '<EMAIL>', 'brad', '<PASSWORD>', '2017-04-10 13:14:31'), (2, '<EMAIL>', 'john', '<PASSWORD>', '2017-04-10 14:12:14'), (3, '<EMAIL>', 'ahsanaatir', '<PASSWORD>', '2017-06-19 18:18:04'); -- -- Indexes for dumped tables -- -- -- Indexes for table `class` -- ALTER TABLE `class` ADD PRIMARY KEY (`id`); -- -- Indexes for table `school` -- ALTER TABLE `school` ADD PRIMARY KEY (`id`); -- -- Indexes for table `section` -- ALTER TABLE `section` ADD PRIMARY KEY (`id`); -- -- Indexes for table `session` -- ALTER TABLE `session` ADD PRIMARY KEY (`id`); -- -- Indexes for table `students_attendance` -- ALTER TABLE `students_attendance` ADD PRIMARY KEY (`student_id`,`date`); -- -- Indexes for table `students_leave` -- ALTER TABLE `students_leave` ADD PRIMARY KEY (`student_id`,`date`); -- -- Indexes for table `student_family_info` -- ALTER TABLE `student_family_info` ADD KEY `student_id` (`student_id`), ADD KEY `student_id_2` (`student_id`), ADD KEY `father_name` (`father_name`); -- -- Indexes for table `student_personal_info` -- ALTER TABLE `student_personal_info` ADD PRIMARY KEY (`id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `class` -- ALTER TABLE `class` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `school` -- ALTER TABLE `school` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `section` -- ALTER TABLE `section` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `session` -- ALTER TABLE `session` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `student_personal_info` -- ALTER TABLE `student_personal_info` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; /*!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 */;
d5f9563b2973489b13e4813b3f4e13905e5dd047
[ "SQL", "PHP" ]
8
PHP
itsasfand/Ci_school
9a4d41a6b92e51ea197371daa0e9b9fb08023a96
c2967f78aa1e5254525353e12d0d0441a6f50fd7
refs/heads/master
<file_sep>const ProjectData = [ { title: "Sage Street Coffee Roasters", img: "/img/sage-street.png", desc: `This fully responsive website, made for a fictional coffee shop, was built from scratch using Node.js, Express, and MongoDB as a practice project for working with the server side. It features a working shopping cart and checkout process, user authentication, a blog with commenting capabilities, and email contact form.`, comment: `This website is a passion project inspired by a trip to Oregon, whose multitudes of quaint coffee shops sparked my love for coffee.`, tools: ["HTML", "Handlebars", "SASS", "JQuery", "Node.js", "Express", "MongoDB", "Mongoose"], links: [ { text: "Github", href: "https://github.com/ashley-chang/sage-street-coffee-roasters" } ] }, { title: "Harbor Italian", img: "/img/harbor-spa-fine-dining.png", desc: "This fully responsive website, which features a fictional restaurant/spa, is built with Foundation 6, Sass, and Jquery. It is single-paged, and features a JQuery-powered slider written from scratch, smooth-scrolling and scroll reveal.", comment: "This project was inspired by my love for food, so I had quite a bit of fun thinking up the theme and finding inspiration for photos and the menu.", tools: ["HTML", "JQuery", "Foundation 6", "SASS"], links: [ { text: "Github", href: "https://github.com/ashley-chang/Harbor-Spa-Fine-Dining" } ] }, { title: "Task Timer", img: "/img/task-timer.png", desc: `Task Timer is a Pomodoro-style clock built with React. With a simple settings panel and intuitive interface, it was designed to be smooth, clean, and functional to complement any workflow.`, comment: ``, tools: ["React.js", "CSS"], links: [ { text: "Github", href: "https://github.com/ashley-chang/react-task-timer" }, { text : "CodeSandbox", href: "https://codesandbox.io/s/github/ashley-chang/react-task-timer" }, { text: "Demo", href: "https://6j8wxwmloz.codesandbox.io/" } ] }, { title: "Coffee Friends", img: "/img/coffee-friends.png", desc: `This React-based app is geared towards beginner coffee connoisseurs to explain the differences between several of the most popular types of coffee. Each coffee category features a brief explanation of how it is made, and also includes a small CSS graphic representing ingredient ratios.`, comment: `This was a fun project I built for myself in order to get familiar with all the different types of coffee frequently seen in cafes and restaurants.`, tools: ["React.js", "CSS"], links: [ { text: "Github", href: "https://github.com/ashley-chang/coffee-friends" }, { text: "Demo", href: "https://coffee-friends.herokuapp.com/" } ] }, { title: "Redux Calculator", img: "/img/react-redux-calculator.png", desc: `This calculator was built from scratch using React and Redux. It is fully capable of basic math functions like addition, subtraction, multiplication, and division, and also handles invalid input such as repeated operators. It uses state changes to keep track of current operations, display values, and result values.`, comment: `While Redux may not have been absolutely necessary for this project, this calculator solidified my understanding of how React and Redux work together.`, tools: ["React.js", "Redux", "CSS"], links: [ { text: "Github", href: "https://github.com/ashley-chang/react-redux-calculator" }, { text : "CodeSandbox", href: "https://codesandbox.io/s/github/ashley-chang/react-redux-calculator" }, { text: "Demo", href: "https://38m4rz1w2p.codesandbox.io/" } ] }, { title: "Sustainable Energy Tribute Page", img: "/img/sustainable-energy-tribute-page.png", desc: `This simple tribute page was born out of my love for the environment. It was created simply to provide a basic explanation of sustainable energy; it includes a rundown of what sustainable energy is, what it involves, and why it is important for the future. The page itself is rather minimal, but I enjoyed playing with the layout, which includes a simple JS-powered accordion and decorative pseudo-elements.`, comment: `This project was inspired by Free Code Academy's front-end project ideas.`, tools: ["HTML", "CSS", "Javascript"], links: [ { text: "Demo", href: "https://codepen.io/basilsprout/pen/ZmbrWP#0" } ] }, { title: "Chatty", img: "/img/node-chat-app.png", desc: `Chatty is a fully functioning live chat application that runs on Node.js and Socket.io. Users can create usernames as well as individual rooms to chat in, and can also send information about their location through the geolocation API. Users are also notified whenever someone enters or leaves their chat room.`, comment: `This project was created as a part of <NAME>'s "The Complete Node.js Developer Course" on Udemy.`, tools: ["Javascript", "Node.js", "Socket.io"], links: [ { text: "Github", href: "https://github.com/ashley-chang/node-chat-app" } ] }, { title: "Redux Weather Forecast", img: "/img/redux-weather-app.png", desc: `This weather forecasting app, powered by Google Maps, OpenWeatherMap, and Sparklines APIs, fetches a real-time 5-day weather forecast of any given US city. Search information includes a working map, as well as temperature, humidity, and pressure trends presented in colored line graphs.`, comment: `This project was created a part of Stephen Grider's "Modern React with Redux" course on Udemy.`, tools: ["React.js", "Redux"], links: [ { text: "Github", href: "https://github.com/ashley-chang/redux-weather-app" } ] }, { title: "React Youtube", img: "/img/react-youtube.png", desc: `Built with React, this YouTube clone uses the YouTube API and features an instant search bar that loads videos as you type.`, comment: `This project was created a part of <NAME>'s "Modern React with Redux" course on Udemy.`, tools: ["React.js"], links: [ { text: "Github", href: "https://github.com/ashley-chang/react-youtube" } ] } ]; for (let i = 0 ; i < ProjectData.length; i++) { ProjectData[i]["id"] = i.toString(); } export default ProjectData; <file_sep>import React, { Component } from 'react'; import { Link } from "react-router-dom"; class LandingPage extends Component { render() { return ( <Link to="/about" className="landing-page"> <div className="landing-page-logo index-logo"><NAME></div> <div className="landing-page-enter">click anywhere to enter</div> </Link> ) } } export default LandingPage; <file_sep>import React from 'react'; const Links = props => { //props: label, links [Object Array] let links = props.links.map((link)=> { return <li key={link.text}><a href={link.href}>{link.text}</a></li> }); return ( <div className="links"> <span className="links-label">{props.label}</span> <ul> {links} </ul> </div> ); } export default Links; <file_sep>import React, { Component } from 'react'; import { Link } from "react-router-dom"; import NavButton from './nav_button'; class Nav extends Component { constructor(props) { super(props); this.state = { visible: false } this.toggleNav = this.toggleNav.bind(this); this.clickHandler = this.clickHandler.bind(this); } componentDidMount() { this.setState({ responsiveNav: window.innerWidth < 800 }); window.addEventListener('resize', () => { this.setState({ responsiveNav: window.innerWidth < 800 }); }, false); } toggleNav() { this.setState({ visible: !this.state.visible }); } clickHandler(e) { this.toggleNav(); e.stopPropagation(); } render() { let className; if (this.state.responsiveNav) { className = this.state.visible ? "nav show" : "nav hide"; } else { className = "nav"; } return ( <nav className={ className }> <NavButton visible={this.state.visible} onClick={this.clickHandler}/> <ul> <li> <Link to="/"> <h1 className="index-logo"> <NAME> </h1> </Link> </li> <li className="nav-item" onClick={this.clickHandler}> <div className="nav-item_slide"> <Link to="/about"> <span data-num="001">About</span> </Link> </div> </li> <li className="nav-item" onClick={this.clickHandler}> <div className="nav-item_slide"> <Link to="/projects"> <span data-num="002">Projects</span> </Link> </div> </li> <li className="nav-item" onClick={this.clickHandler}> <div className="nav-item_slide"> <Link to="/contact"> <span data-num="003">Contact</span> </Link> </div> </li> </ul> </nav> ); } }; export default Nav; <file_sep>import React, { Component } from 'react'; import ProjectData from '../data/project_data'; import ProjectSquare from '../components/project_square'; class Projects extends Component { constructor(props) { super(props); this.projects = ProjectData.map((project) => { return <ProjectSquare key={project.id} project={project}/>; }); } render() { return ( <div> <h2 className="container-title" data-num='002'>Projects</h2> <div className="projects"> { this.projects } </div> </div> ); } } export default Projects; <file_sep>import React from 'react'; import { Link } from 'react-router-dom'; const ProjectSquare = (props) => { //receives a project [Object] let path = `/projects/${props.project.id}`; return ( <div className="project-square"> <Link to={ path }> <img className="project-square__image" src={props.project.img} alt={props.project.title} /> <div className="project-square__title">{props.project.title}</div> <Link className="project-square__link" to={ path }>view project</Link> </Link> </div> ); } export default ProjectSquare; <file_sep>import React, { Component } from 'react'; class About extends Component { render() { return ( <div> <h2 className="container-title" data-num='001'>About</h2> <p>Hello! My name is <span className="emphasis"><NAME></span>. I recently graduated from the <span className="emphasis">University of California, Los Angeles (UCLA)</span>&nbsp;with a B.A. in <span className="emphasis">Linguistics & Computer Science</span>&nbsp;and a minor in <span className="emphasis">East Asian Languages and Cultures</span>&nbsp;with a focus in Japanese. </p> <p> I am currently based in Orange County/Los Angeles. My passions lie in integrating creativity with science and logic--which is why I specialize in <span className="emphasis">front-end development</span>. </p> <p> My previous experiences include Web Assistant at the UCLA Lewis Center for Regional Policy Policy Studies/Institute of Transportation Studies (2017-2018), as well as Front-End Web Development Intern at Pro-Lite, Inc. (2017). </p> <p> In my free time, you can find me baking cheesecakes or drawing up a storm. </p> </div> ); } } export default About;
7f298c0c9f9301aaa308c4e183042e21e786f64e
[ "JavaScript" ]
7
JavaScript
ashley-chang/personal-website
2b6a23fda0733cd5e6f377dd53e6bc961c835a87
f37428631b61d0c7bcd130507b40da19dd00133f
refs/heads/master
<repo_name>alsh02/SuperCuteTaeHwan<file_sep>/src/main/java/com/jmt/SuperCuteTaeHwan/controller/QuestionController.java package com.jmt.SuperCuteTaeHwan.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class QuestionController { @GetMapping("/cat/Q2") public String question1Cat() { return "question2"; } @GetMapping("/dog/Q2") public String question1Dog() { return "question2"; } @GetMapping("/dynamic/Q3") public String question2Dynamic() { return "question3"; } @GetMapping("/static/Q3") public String question2Static() { return "question3"; } @GetMapping("/sunny/Q4") public String question3Sunny() { return "question4"; } @GetMapping("/cloudy/Q4") public String question3Cloudy() { return "question4"; } @GetMapping("/newyork/process") public String question4NewYork() { return "result"; } @GetMapping("/bali/process") public String question4Bali() { return "result"; } } <file_sep>/src/main/java/com/jmt/SuperCuteTaeHwan/service/UserService.java package com.jmt.SuperCuteTaeHwan.service; import com.jmt.SuperCuteTaeHwan.domain.User; import com.jmt.SuperCuteTaeHwan.repository.JpaUserRepository; import com.jmt.SuperCuteTaeHwan.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import javax.transaction.Transactional; @Transactional public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } /* 데이터 베이스 저장 */ public void join(User u) { userRepository.save(u); } /* 처음 입력한 이름을 기반으로 검색함. */ public User findUser(String name) { return userRepository.findByName(name); } } <file_sep>/settings.gradle rootProject.name = 'SuperCuteTaeHwan' <file_sep>/README.md # SuperCuteTaeHwan 2020년 한국디지털미디어고등학교 웹프로그래밍 - 스프링 서비스 만들기 수행평가 <file_sep>/src/main/resources/application.properties server.address=localhost server.port=8080 spring.jpa.show-sql=true spring.jpa.generate-ddl=false spring.jpa.database=mysql spring.datasource.url=jdbc:mysql://localhost:3306/dimigo?useSSL=false&characterEncoding=UTF-8&serverTimezone=UTC&allowPublicKeyRetrieval=true&useSSL=false spring.datasource.username=root spring.datasource.password=<PASSWORD> spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect<file_sep>/src/main/java/com/jmt/SuperCuteTaeHwan/domain/Answer.java package com.jmt.SuperCuteTaeHwan.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /* 질문 페이지에서 받은 답변 엔티티 */ @Entity public class Answer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) int id; String q1; String q2; String q3; String q4; public String getQ1() { return q1; } public void setQ1(String q1) { this.q1 = q1; } public String getQ2() { return q2; } public void setQ2(String q2) { this.q2 = q2; } public String getQ3() { return q3; } public void setQ3(String q3) { this.q3 = q3; } public String getQ4() { return q4; } public void setQ4(String q4) { this.q4 = q4; } } <file_sep>/src/main/java/com/jmt/SuperCuteTaeHwan/UserForm.java package com.jmt.SuperCuteTaeHwan; public class UserForm { String name; int age; String gender; String belong; public void setName(String name) { this.name = name; } public String getName() { return name; } public void setAge(int age) { this.age = age; } public int getAge() { return age; } public void setGender(String gender) { this.gender = gender; } public String getGender() { return gender; } public void setBelong(String belong) { this.belong = belong; } public String getBelong() { return belong; } } <file_sep>/src/main/java/com/jmt/SuperCuteTaeHwan/repository/JpaUserRepository.java package com.jmt.SuperCuteTaeHwan.repository; import com.jmt.SuperCuteTaeHwan.domain.User; import javax.persistence.EntityManager; public class JpaUserRepository implements UserRepository { EntityManager em; public JpaUserRepository(EntityManager em) { this.em = em; } @Override public void save(User u) { em.persist(u); } @Override public User findByName(String name) { return null; } }
f56c60d4a4f76d04ace0f3658e1a544504415292
[ "Markdown", "Java", "INI", "Gradle" ]
8
Java
alsh02/SuperCuteTaeHwan
dde09ea72e5294dfc2bc2c9b8439002f3cad184f
bca911e85760d0486551c0130c54ebfc461c9930
refs/heads/master
<file_sep>// // ViewController.swift // ChatMessageScreen // // Created by Appcare Apple on 30/08/20. // Copyright © 2020 Appcare Apple. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tabel: UITableView! let names = ["vikas", "vinay", "viswas", "vivek"] override func viewDidLoad() { super.viewDidLoad() tabel.delegate = self tabel.dataSource = self tabel.register(UITableViewCell.self, forCellReuseIdentifier: "cell") tabel.tableFooterView = UIView() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return names.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tabel.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = names[indexPath.row] cell.imageView?.image = #imageLiteral(resourceName: "Mask Group 31 (1)") return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tabel.deselectRow(at: indexPath, animated: true) let vc = ChatViewController() vc.title = "Messages" navigationController?.pushViewController(vc, animated: true) } } <file_sep>// // MessagesViewController.swift // ChatMessageScreen // // Created by <NAME> on 30/08/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit import MessageKit struct Sender: SenderType { var senderId: String var displayName: String } struct Message: MessageType { var sender: SenderType var messageId: String var sentDate: Date var kind: MessageKind } class ChatViewController: MessagesViewController, MessagesLayoutDelegate, MessagesDisplayDelegate, MessagesDataSource { let currentUser = Sender(senderId: "First", displayName: "Legendary Action") let endUser = Sender(senderId: "Second", displayName: "Bring The Action") var message = [Message]() override func viewDidLoad() { super.viewDidLoad() message.append(Message(sender: currentUser, messageId: "1", sentDate: Date().addingTimeInterval(-86100), kind: .text("Hi"))) message.append(Message(sender: endUser, messageId: "2", sentDate: Date().addingTimeInterval(-70000), kind: .text("Hello"))) message.append(Message(sender: currentUser, messageId: "3", sentDate: Date().addingTimeInterval(-60000), kind: .text("How are you?"))) message.append(Message(sender: endUser, messageId: "4", sentDate: Date().addingTimeInterval(-50000), kind: .text("I am doing good and glad to talk to you after such a long time. Its really means a lot to me for this conversation!"))) message.append(Message(sender: currentUser, messageId: "5", sentDate: Date().addingTimeInterval(-40000), kind: .text("Ho thats really great!! sounds good for the information!!!."))) message.append(Message(sender: endUser, messageId: "6", sentDate: Date().addingTimeInterval(-20000), kind: .text("Hoo!! really.."))) message.append(Message(sender: currentUser, messageId: "7", sentDate: Date().addingTimeInterval(-10000), kind: .text("Let hang up this weekend at some place!! will call you regarding it soon....Thank you"))) messagesCollectionView.messagesDataSource = self messagesCollectionView.messagesLayoutDelegate = self messagesCollectionView.messagesDisplayDelegate = self } func currentSender() -> SenderType { return currentUser } func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType { return message[indexPath.section] } func numberOfSections(in messagesCollectionView: MessagesCollectionView) -> Int { return message.count } }
92e2fee28d1b38dab877da0f536d10d8392da976
[ "Swift" ]
2
Swift
Vikassingamsetty/ChatScreenAPP
9b9cae239ba26b182d69176074d929f5506d62f5
5b37c6f5d81712768084f1f41150e3a5ecfe2dc2
refs/heads/master
<file_sep> # Install Clone a repo ```bash git clone https://github.com/aChudinov/dotfiles.git ``` ## Setup Vundle 1. `bash < ./install.sh` 2. `git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim` 3. Open VIM => `:PluginInstall` ## YouCompleteMe post installation ``` cd ~/.vim/bundle/YouCompleteMe && git submodule update --init --recursive && ./install.py --ts-completer ``` ## markdown-preview post installation ``` cd ~/.vim/bundle/markdown-preview.nvim/app && yarn install ``` ## Install fonts 1. Download `DroidSansMono` ``` cd ~/Library/Fonts && curl -fLo "Droid Sans Mono for Powerline Nerd Font Complete.otf" https://github.com/ryanoasis/nerd-fonts/raw/master/patched-fonts/DroidSansMono/complete/Droid%20Sans%20Mono%20Nerd%20Font%20Complete.otf ``` 2. Use in iTerm2 Options => Profiles => Text => Change Font ## Navigate with arrows in iTerm2 https://coderwall.com/p/h6yfda/use-and-to-jump-forwards-backwards-words-in-iterm-2-on-os-x ## Install fzf 1. Install https://github.com/junegunn/fzf 2. Install https://github.com/beyondgrep/ack2 ## Building VIM from source https://github.com/Valloric/YouCompleteMe/wiki/Building-Vim-from-source ``` make distclean ./configure --with-features=huge \ --enable-multibyte \ --enable-rubyinterp=yes \ --enable-pythoninterp=yes \ --with-python-config-dir=/usr/lib/python2.7/config \ --enable-gui=gtk2 \ --enable-cscope \ --prefix=/usr/local make sudo make install ``` ## Install `ack2` https://github.com/beyondgrep/ack2 ``` cpanm PETDANCE/File-Next-1.16.tar.gz ``` ## `tmux` plugins - [Tmux Plugin Manager](https://github.com/tmux-plugins/tpm) <file_sep># Path to your oh-my-zsh installation. export ZSH="$HOME/.oh-my-zsh" # Set name of the theme to load. ZSH_THEME="robbyrussell" # Plugins plugins=(git) # User configuration source $ZSH/oh-my-zsh.sh export PATH="$HOME/bin:$HOME/.bin:$HOME/git/git-hooks:$HOME/git/git-achievements:/usr/share/perl5/vendor_perl/auto/share/dist/Cope:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/git/bin:$HOME/.rvm/bin" # Exclude .gitignore files from FZF search export FZF_DEFAULT_COMMAND=' (git ls-files --recurse-submodules || find . -path "*/\.*" -prune -o -type f -print -o -type l -print | sed s/^..//) 2> /dev/null' # Open tmux with 256colors to support vim colorscheme alias tmux="TERM=screen-256color-bce tmux" export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm [[ -s "$HOME/.avn/bin/avn.sh" ]] && source "$HOME/.avn/bin/avn.sh" # load avn export PATH="$HOME/.yarn/bin:$PATH" export EDITOR="vim" export PATH="$HOME/.rbenv/bin:$PATH" eval "$(rbenv init -)" <file_sep>#!/usr/bin/env bash set -e DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" echo This bash script will download and install the dotfiles from echo http://github.com/achudinov/dotfiles. # Build up a list of all the dotfiles (ignoring .git and .gitignore) dotfiles=() for f in $(find . -maxdepth 1 -name ".[^.]*" -exec basename {} \; | \ grep -vE ".git(ignore)?$"); do dotfiles+=("$f") done echo echo Symlinking the following dotfiles: for f in "${dotfiles[@]}"; do echo "$f" # And symlink it to the relative directory! abs_path=$("$DIR/bin/readlink-f" "$f") rel_path="${abs_path#$HOME/}" ln -sf $rel_path ~/$f done echo echo Installing vim plugins "(could take a while)" vim +BundleInstall +qall < /dev/tty echo echo -e "\[\033[1;32m\]Everything succesfully installed.\[\033[0m\]"
f81b822d006c3411e64bfd2fd24510f87fc97af5
[ "Markdown", "Shell" ]
3
Markdown
aChudinov/dotfiles
c4b050fb8e0268597b01be6941594a7dc700a95e
955347949bf6e15d35a34ed2bdffd19a071a3753
refs/heads/master
<repo_name>bertt/pnts-tile-cs<file_sep>/src/ByteOffset.cs using System.Text.Json.Serialization; namespace Pnts.Tile { public class ByteOffset { [JsonPropertyName("byteOffset")] public int offset { get; set; } } } <file_sep>/src/Position.cs namespace Pnts.Tile { public class Position:ByteOffset { } } <file_sep>/README.md # pnts-tile-cs .NET Standard 2.1 Library for (de)serializing Cesium pnts tiles [![NuGet Status](http://img.shields.io/nuget/v/pnts-tile.svg?style=flat)](https://www.nuget.org/packages/pnts-tile/) Spec: https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification/TileFormats/PointCloud 3D Tiles Candidate OGC® Community Standard (pdf alert): https://portal.opengeospatial.org/files/79137 ## Sample code ``` string infile = "testfixtures/1-0-1-1.pnts"; var stream = File.OpenRead(infile); var pnts = PntsParser.ParsePnts(stream); Console.WriteLine($"Number of points: {pnts.FeatureTableMetadata.points_length} "); var rtc = pnts.FeatureTableMetadata.Rtc_Center; Console.WriteLine($"RTC_CENTER (relative to center x,y,z): {rtc[0]},{rtc[1]},{rtc[2]}"); Console.WriteLine($"First point (x,y,z): {pnts.Points[0].X}, {pnts.Points[0].Y}, {pnts.Points[0].Z} "); Console.WriteLine($"First point color (r,g,b): {pnts.Colors[0].R}, {pnts.Colors[0].G}, {pnts.Colors[0].B} "); ``` See https://github.com/bertt/pnts-tile-cs/blob/master/samples/ConsoleApp/Program.cs for sample code converting points in tile to longitude, latitude, altitude and writing to csv file. ## Positions From the spec: "RTC_CENTER specifies the center position and all point positions are treated as relative to this value". So for each point, add the point (x,y,z) to the RTC_CENTER to get its position in Cartesian format. For sample code calculating to longitude, latitude, altitude see https://github.com/bertt/pnts-tile-cs/blob/master/samples/ConsoleApp/Program.cs#L19 ## Dependencies - System.Text.Json ## Known limitis - add support for POSITION_QUANTIZED, RGBA, RGB565, NORMAL, NORMAL_OCT16P, BATCH_ID, QUANTIZED_VOLUME_OFFSET, QUANTIZED_VOLUME_SCALE, CONSTANT_RGBA,BATCH_LENGTH - add pnts writer functionality ## History 2018-12-19: Initial coding - pnts reader <file_sep>/src/Rgb.cs namespace Pnts.Tile { public class Rgb:ByteOffset { } } <file_sep>/samples/ConsoleApp/Program.cs using DotSpatial.Positioning; using Pnts.Tile; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace ConsoleApp { class Program { static void Main(string[] args) { string infile = "testfixtures/1-0-1-1.pnts"; var stream = File.OpenRead(infile); Console.WriteLine("Pnts tile sample application"); Console.WriteLine($"Start parsing {infile}..."); var pnts = PntsSerializer.Deserialize(stream); var rtc = pnts.FeatureTableMetadata.Rtc_Center; var rtc_cartesian = GetCartesianPoint(rtc[0], rtc[1], rtc[2]); var cartesian_points = GetCartesianPoints(pnts); var wgs84Points = GetWgs84Points(cartesian_points, rtc_cartesian); WritePositions3DToCsv("positions.csv", wgs84Points); var first_point = wgs84Points[0]; Console.WriteLine($"Number of points: {pnts.FeatureTableMetadata.points_length} "); Console.WriteLine($"RTC_CENTER (relative to center x,y,z): {rtc[0]},{rtc[1]},{rtc[2]}"); Console.WriteLine($"First point (x,y,z): {pnts.Points[0].X}, {pnts.Points[0].Y}, {pnts.Points[0].Z} "); Console.WriteLine($"First point (longitude, latitude, altitude): {first_point.Longitude.DecimalDegrees}, {first_point.Latitude.DecimalDegrees}, {first_point.Altitude} "); Console.WriteLine($"First point color (r,g,b): {pnts.Colors[0].R}, {pnts.Colors[0].G}, {pnts.Colors[0].B} "); Console.WriteLine("Press any key to continue"); Console.ReadKey(); } private static void WritePositions3DToCsv(string file, List<Position3D> points) { var csv = new StringBuilder(); foreach (var p in points) { var newLine = $"{p.Longitude.DecimalDegrees},{p.Latitude.DecimalDegrees},{p.Altitude.Value}"; csv.AppendLine(newLine); } File.WriteAllText(file, csv.ToString()); } private static List<Position3D> GetWgs84Points(List<CartesianPoint> points, CartesianPoint rtc) { var result = new List<Position3D>(); foreach(var point in points) { result.Add((rtc + point).ToPosition3D()); } return result; } private static List<CartesianPoint> GetCartesianPoints(Pnts.Tile.Pnts pnts) { var cartesianpoints = new List<CartesianPoint>(); foreach (var p in pnts.Points) { var cartesian_point = GetCartesianPoint(p.X, p.Y, p.Z); cartesianpoints.Add(cartesian_point); } return cartesianpoints; } private static CartesianPoint GetCartesianPoint(float x, float y, float z) { var distance_x = new Distance(x, DistanceUnit.Meters); var distance_y = new Distance(y, DistanceUnit.Meters); var distance_z = new Distance(z, DistanceUnit.Meters); var cartesian = new CartesianPoint(distance_x, distance_y, distance_z); return cartesian; } } }
c26b571748ba06c8e2c0086820354adc5aa42f38
[ "Markdown", "C#" ]
5
C#
bertt/pnts-tile-cs
83baec52a32b6bb6ffec9145bf65dc469172ca56
bdee53f491761c5371c8338334f2f27f73b7a9a9
refs/heads/master
<repo_name>marcinbunsch/algorithms<file_sep>/sorting/insertion/insertion.rb def insertion_sort(array) for index in 1..(array.length - 1) key = array[index] sort_index = index - 1 while sort_index >= 0 and array[sort_index] > key array[sort_index + 1] = array[sort_index] sort_index -= 1 end array[sort_index + 1] = key end array end arr = [5,2,1,3,4] puts "Before sort:" puts arr.inspect insertion_sort(arr) puts "After sort:" puts arr.inspect<file_sep>/shared/runners/scala.rb name = File.basename(@file).sub(/\.#{@extension}$/, '') classpath = File.join('build', 'scala') shared = File.join('shared', 'includes', '*.scala') puts "Compiling..." if system "scalac -cp #{classpath} #{shared} #{@file}"" -d #{classpath}" puts "Running..." system "cd #{classpath} && scala #{name}" end<file_sep>/sorting/insertion/insertion.js function insertion_sort(array) { var size = array.length; // Start with the second element of the array and move towards the end of the array for (var index = 1; index < size; index++) { // This is the value of the current element that we will be inserting at a different location var key = array[index] // This is the initial index of the element we will start the comparison with, // it is the previous element to the one we have stored under 'key' var sort_index = index - 1 // We start at the sort_index and move back, towards the beginning of the array while (sort_index >= 0 && array[sort_index] > key) { // move the currently compared index one index back to make place for the key array[sort_index + 1] = array[sort_index] // decrease the sort index by 1 to check if the value under the previous index is greater sort_index--; } // As we decreased sort_index at the end of the while loop, // we store the key under sort_index + 1 to make sure it's in the right place array[sort_index + 1] = key } } var array = [4,3,1,5,2] console.log("Before sort:") console.log(array) insertion_sort(array) console.log("After sort:") console.log(array)<file_sep>/shared/runners/py.rb puts "Running..." system "python #{@file}"<file_sep>/shared/runners/io.rb puts "Running..." system "io #{@file}"<file_sep>/sorting/insertion/insertion.py def insertion_sort(array): for index in range(1, len(array)): key = array[index] sort_index = index - 1 while sort_index >= 0 and array[sort_index] > key: array[sort_index + 1] = array[sort_index] sort_index = sort_index - 1 array[sort_index + 1] = key return array alist = [5,2,3,1,4] print "Before sort:" print alist insertion_sort(alist) print "After sort:" print alist<file_sep>/shared/includes/helpers.cpp #include <iostream> using namespace std; void printArray(int *array, int size) { cout << '['; for (int i = 0;i < size;i++) { cout << array[i]; if (i < size - 1) cout << ','; } cout << ']' << endl; } <file_sep>/shared/runners/js.rb puts "Running..." system "node #{@file}"<file_sep>/sorting/insertion/insertion.php <?php function insertion_sort($arr) { for ($sorted_index = 1; $sorted_index < count($arr) - 1; $sorted_index++) { $key = $arr[$sorted_index]; $compared_index = $sorted_index - 1; while ($compared_index >= 0 && $arr[$compared_index] > $key) { $arr[$compared_index + 1] = $arr[$compared_index]; $compared_index--; } $arr[$compared_index + 1] = $key; } return $arr; } $array = array(5,2,1,3,4); echo "Before sort:\n"; echo '[' . join($array, ',') . "]\n"; $array = insertion_sort($array); echo "After sort:\n"; echo '[' . join($array, ',') . "]\n"; ?><file_sep>/shared/runners/cpp.rb name = File.basename(@file).sub(/\.#{@extension}$/, '') out = File.join("build", "cpp", name) puts "Compiling..." if system "g++ #{@file} -o #{out}" puts "Running..." system out end<file_sep>/shared/runners/rb.rb puts "Running..." system "ruby #{@file}"<file_sep>/sorting/quicksort/quicksort.js function quicksort(array) { // An array of zero or one elements is already sorted if (array.length < 2) return array // Temporary arrays which will hold greater and lesser values var less = [], more = [] // Select and remove a pivot value pivot from array var pivot = array.pop() // Push the element to the appropriate temporary array, depending on the value for (var i = 0, len = array.length; i < len; i++) (array[i] <= pivot ? less : more).push(array[i]) // Update the array with the new order array = [].concat(quicksort(less), [pivot], quicksort(more)) return array } var array = [4,3,1,5,2] console.log("Before sort:") console.log(array) array = quicksort(array) console.log("After sort:") console.log(array)<file_sep>/sorting/quicksort/quicksort.rb def quicksort(array) # an array of zero or one elements is already sorted if array.size > 1 # temporary arrays which will hold greater and lesser values less, more = [], [] # select and remove a pivot value pivot from array pivot = array.pop array.each do |element| # Push the element to the appropriate temporary array, depending on the value (element <= pivot ? less : more).push element end # Update the array with the new order array.replace quicksort(less) + [pivot] + quicksort(more) end array end arr = [5,2,1,3,4] puts "Before sort:" puts arr.inspect quicksort(arr) puts "After sort:" puts arr.inspect<file_sep>/run #!/usr/bin/env ruby require 'fileutils' @file = ARGV[0] exit if @file.nil? @extension = File.extname(@file).sub(/^\./, '') runner = File.join('shared', 'runners', @extension + '.rb') if File.exists?(runner) FileUtils.mkdir_p(File.join('build', @extension)) require runner else puts "Runner for #{@extension} not found." end <file_sep>/shared/runners/php.rb puts "Running..." system "php #{@file}"
732173dfed057313a2a18d339697a4e6fc8d8966
[ "Ruby", "JavaScript", "Python", "PHP", "C++" ]
15
Ruby
marcinbunsch/algorithms
2a28d164dd9f5d4850c0cc66b494bc73e2f4f7e2
751ade3788b4e6048531f4f5e2b09a7a07fd8df7
refs/heads/master
<file_sep>#includes "rm_rid.h" RID::RID() : pageNum(INVALID_PAGE), slotNum(INVALID_SLOT) { } RID:RID(PageNum pageNum, SlotNum slotNum) : pageNum(pageNum), slotNum(slotNum) { } RID::~RID() RC RID::GetPageNum(PageNum &pageNum) { if (this.pageNum == INVALID_PAGE) { return RM_RID_NOTINIT; } pageNum = this.pageNum; return (0); } RC RID::GetSlotNum(SlotNum &slotNum) { if (this.slotNum == INVALID_SLOT) { return RM_RID_NOTINIT; } slotnum = this.slotNum; return (0); }
77449deb09b7c43266964024954a3a40b8d6a9bc
[ "C++" ]
1
C++
dogeyes/RedBase
8ba43209fe9c84f312a3322bc6b79972ce669a17
6f4d5841bc65b683deacd871a7bf86c5099457d2
refs/heads/master
<file_sep>//////////////////////////////////////////////////////////////////////////////// // MbpTrackpadControlKeyDriver/MbpTrackpadControlKeyDriver.h #if !defined(MBP_TRACKPAD_CONTROL_KEY_DRIVER__MBP_TRACKPAD_CONTROL_KEY_DRIVER_H) #define MBP_TRACKPAD_CONTROL_KEY_DRIVER__MBP_TRACKPAD_CONTROL_KEY_DRIVER_H #include "../../UserKernelShared.h" #include <IOKit/IOService.h> //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /** * @class jp_or_iij4u_ss_yamaoka_MbpTrackpadControlKeyDriver * @brief */ class IOHIDSystem; class IOHIKeyboard; class DRIVER_CLASS_NAME : public IOService { OSDeclareDefaultStructors(jp_or_iij4u_ss_yamaoka_MbpTrackpadControlKeyDriver) typedef IOService DSuper; public: // IOService interfaces. virtual bool init(OSDictionary* dictionary = 0); virtual void free(); virtual IOService* probe(IOService* provider, SInt32* score); virtual bool start(IOService* provider); virtual void stop(IOService* provider); // local interfaces. virtual IOReturn setControlModifierKey(bool isActive); private: IOHIDSystem* system_; IOHIKeyboard* keyboard_; private: IONotifier* keyboardMatchedNotifier_; IONotifier* keyboardTerminatedNotifier_; static bool keyboardMatchedNotificationHandler (void* target , void* refCon , IOService* newService , IONotifier* notifier); static bool keyboardTerminatedNotificationHandler (void* target , void* refCon , IOService* newService , IONotifier* notifier); void initialize(); void finalize(); bool initiateNotification(); void terminateNotification(); }; #endif<file_sep>//////////////////////////////////////////////////////////////////////////////// // MbpTrackpadControlKeyUtility/UserClientFacade.cpp #include "./UserClientFacade.h" #include "../../UserKernelShared.h" //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // CUserClientFacade //////////////////////////////////////////////////////////////////////////////// kern_return_t CUserClientFacade::openUserClient(io_connect_t connect) { return IOConnectCallScalarMethod(connect , USER_CLIENT_OPEN , NULL , 0 , NULL , NULL); } //////////////////////////////////////////////////////////////////////////////// kern_return_t CUserClientFacade::closeUserClient(io_connect_t connect) { return IOConnectCallScalarMethod(connect , USER_CLIENT_CLOSE , NULL , 0 , NULL , NULL); } //////////////////////////////////////////////////////////////////////////////// kern_return_t CUserClientFacade::setControlModifierKey(io_connect_t connect, bool isActive) { const uint64_t i = isActive ? 1 : 0; return IOConnectCallMethod(connect // an io_connect_t returned from IOServiceOpen(). , SET_CONTROL_MODIFIER_KEY // selector of the function to be called via the user client. , &i // array of scalar (64-bit) input values. , 1 // the number of scalar input values. , NULL // a pointer to the struct input parameter. , 0 // the size of the input structure parameter. , NULL // array of scalar (64-bit) output values. , NULL // pointer to the number of scalar output values. , NULL // pointer to the struct output parameter. , NULL); // pointer to the size of the output structure parameter. } <file_sep>//////////////////////////////////////////////////////////////////////////////// // MbpTrackpadControlKeyDriver/MbpTrackpadControlKeyDriver.cpp #include "./MbpTrackpadControlKeyDriver.h" #include <IOKit/IOLib.h> #include <IOKit/hid/IOHIDKeys.h> #include <IOKit/hidsystem/IOHIKeyboard.h> #include <IOKit/hidsystem/IOHIDSystem.h> #include "../../Logging.h" //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // jp_or_iij4u_ss_yamaoka_MbpTrackpadControlKeyDriver //////////////////////////////////////////////////////////////////////////////// OSDefineMetaClassAndStructors(jp_or_iij4u_ss_yamaoka_MbpTrackpadControlKeyDriver, IOService) //////////////////////////////////////////////////////////////////////////////// bool DRIVER_CLASS_NAME::init(OSDictionary *dictionary) { if (!DSuper::init(dictionary)) { return false; } // This IOLog must follow super::init because getName relies on the superclass initialization. IOLog("%s[%p]::%s(%p)\n", getName(), this, __FUNCTION__, dictionary); system_ = NULL; keyboard_ = NULL; return true; } //////////////////////////////////////////////////////////////////////////////// void DRIVER_CLASS_NAME::free() { IOLog("%s[%p]::%s()\n", getName(), this, __FUNCTION__); DSuper::free(); } //////////////////////////////////////////////////////////////////////////////// IOService* DRIVER_CLASS_NAME::probe(IOService* provider, SInt32* score) { IOLog("%s[%p]::%s(%p, %p)\n", getName(), this, __FUNCTION__, provider, score); IOService *result = DSuper::probe(provider, score); return result; } //////////////////////////////////////////////////////////////////////////////// bool DRIVER_CLASS_NAME::start(IOService* provider) { IOLog("%s[%p]::%s(%p)\n", getName(), this, __FUNCTION__, provider); system_ = NULL; keyboard_ = NULL; if (!DSuper::start(provider)) { return false; } system_ = IOHIDSystem::instance(); if (system_ == NULL) { IOLog("error: IOHIDSystem not loaded.\n"); return false; } if (!initiateNotification()) { IOLog("error: initiateNotification.\n"); return false; } registerService(); IOLog("DRIVER_CLASS_NAME::start succeeded.\n"); return true; } //////////////////////////////////////////////////////////////////////////////// void DRIVER_CLASS_NAME::stop(IOService* provider) { IOLog("%s[%p]::%s(%p)\n", getName(), this, __FUNCTION__, provider); system_ = NULL; keyboard_ = NULL; terminateNotification(); DSuper::stop(provider); } //////////////////////////////////////////////////////////////////////////////// IOReturn DRIVER_CLASS_NAME::setControlModifierKey(bool isActive) { IOLog("%s[%p]::%s(isActive = %d)\n" , getName() , this , __FUNCTION__ , isActive); if (keyboard_ == NULL) { return kIOReturnSuccess; } enum { CONTROL_KEY = (NX_CONTROLMASK | NX_DEVICELCTLKEYMASK), }; unsigned int dfs = keyboard_->deviceFlags(); IOLog("device flags from = %d\n", dfs); if (isActive) { IOLog("control down\n"); dfs |= CONTROL_KEY; } else { IOLog("control up\n"); dfs &= ~CONTROL_KEY; } keyboard_->setDeviceFlags(dfs); IOLog("device flags to = %d\n", keyboard_->deviceFlags()); return kIOReturnSuccess; } //////////////////////////////////////////////////////////////////////////////// bool DRIVER_CLASS_NAME::keyboardMatchedNotificationHandler (void* target , void* refCon , IOService* newService , IONotifier* notifier) { IOLog("%s newService:%p\n", __FUNCTION__, newService); IOHIKeyboard* keyboard = OSDynamicCast(IOHIKeyboard, newService); if (!keyboard) { return false; } const OSNumber* vid = OSDynamicCast(OSNumber, keyboard->getProperty(kIOHIDVendorIDKey)); const OSNumber* pid = OSDynamicCast(OSNumber, keyboard->getProperty(kIOHIDProductIDKey)); const char* name = keyboard->getName(); const OSString* manufacturer = OSDynamicCast(OSString, keyboard->getProperty(kIOHIDManufacturerKey)); const OSString* product = OSDynamicCast(OSString, keyboard->getProperty(kIOHIDProductKey)); IOLog("device: name = %s\n", name); IOLog("device: manufacturer = %s\n", manufacturer->getCStringNoCopy()); IOLog("device: product = %s\n", product->getCStringNoCopy()); IOLog("device: vender ID = %lld\n", vid->unsigned64BitValue()); IOLog("device: product ID = %lld\n", pid->unsigned64BitValue()); if (::strcmp(name, "IOHIDConsumer") == 0) { return false; } // 最初に見つかった keyboard を MBP の keyboard と考える。 DRIVER_CLASS_NAME* driver = static_cast<DRIVER_CLASS_NAME*>(target); if (driver->keyboard_ == NULL) { driver->keyboard_ = keyboard; IOLog("MbpTrackpadControlKeyDriver has detected a keyboard.\n"); } return true; } //////////////////////////////////////////////////////////////////////////////// bool DRIVER_CLASS_NAME::keyboardTerminatedNotificationHandler (void* target , void* refCon , IOService* newService , IONotifier* notifier) { IOLog("%s newService:%p\n", __FUNCTION__, newService); IOHIDevice* keyboard = OSDynamicCast(IOHIKeyboard, newService); if (!keyboard) { return false; } const char* name = keyboard->getName(); if (::strcmp(name, "IOHIDConsumer") == 0) { return true; } DRIVER_CLASS_NAME* driver = static_cast<DRIVER_CLASS_NAME*>(target); if (driver->keyboard_ != NULL) { driver->keyboard_ = NULL; IOLog("MbpTrackpadControlKeyDriver has released the keyboard.\n"); } return true; } //////////////////////////////////////////////////////////////////////////////// bool DRIVER_CLASS_NAME::initiateNotification() { keyboardMatchedNotifier_ = addMatchingNotification(gIOMatchedNotification , serviceMatching("IOHIKeyboard") , keyboardMatchedNotificationHandler , this , NULL , 0); if (keyboardMatchedNotifier_ == NULL) { IOLog("initiateNotification keyboardMatchedNotifier_ == NULL\n"); return false; } keyboardTerminatedNotifier_ = addMatchingNotification(gIOTerminatedNotification , serviceMatching("IOHIKeyboard") , keyboardTerminatedNotificationHandler , this , NULL , 0); if (keyboardTerminatedNotifier_ == NULL) { IOLog("initiateNotification keyboardTerminatedNotifier_ == NULL\n"); return false; } return true; } //////////////////////////////////////////////////////////////////////////////// void DRIVER_CLASS_NAME::terminateNotification() { if (keyboardMatchedNotifier_ != NULL) { keyboardMatchedNotifier_->remove(); } if (keyboardTerminatedNotifier_ != NULL) { keyboardTerminatedNotifier_->remove(); } } <file_sep>//////////////////////////////////////////////////////////////////////////////// // MbpTrackpadControlKeyUtility/CTrackpadController.h #if !defined(MBP_TRACKPAD_CONTROL_KEY_UTILITY__TRACKPAD_CONTROLLER_H) #define MBP_TRACKPAD_CONTROL_KEY_UTILITY__TRACKPAD_CONTROLLER_H #include "./Multipad.h" #include <functional> #include <assert.h> //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /** * @class CTrackpadController * @brief */ class CTrackpadController { public: typedef std::function<void (bool isPressed)> FHandler; CTrackpadController(FHandler handler); ~CTrackpadController(); bool initiate(); void terminate(); void setPressed(bool isPressed); bool isPressed() const { return isPressed_; } private: static CTrackpadController* instance__; FHandler handler_; MTDeviceRef device_; bool isPressed_; static int callback(int device, Finger* data, int nFingers, double timestamp, int frame); }; #endif <file_sep>//////////////////////////////////////////////////////////////////////////////// // MbpTrackpadControlKeyUtility/CUserClientFacade.h #if !defined(MBP_TRACKPAD_CONTROL_KEY_UTILITY__USER_CLIENT_FACADE_H) #define MBP_TRACKPAD_CONTROL_KEY_UTILITY__USER_CLIENT_FACADE_H #include <IOKit/IOKitLib.h> //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /** * @class CUserClientFacade * @brief */ class CUserClientFacade { public: kern_return_t openUserClient(io_connect_t connect); kern_return_t closeUserClient(io_connect_t connect); kern_return_t setControlModifierKey(io_connect_t connect, bool isActive); }; #endif <file_sep>//////////////////////////////////////////////////////////////////////////////// // MbpTrackpadControlKeyUtility/Multipad.h #if !defined(MBP_TRACKPAD_CONTROL_KEY_UTILITY__MULTIPAD_H) #define MBP_TRACKPAD_CONTROL_KEY_UTILITY__MULTIPAD_H // - MultitouchSupport.framework で定義される関数の prototype。 // - 同 framework は header file を提供しないので独自に定義する。 // - 捜せば apple が公式に release する API 仕様、及び header file があるのかも知れない // が、見つけることが出来なかった。 // - "VirtualAwesome" という open source の graphic library でこれらの定義を行っていた // ので、以下それから拝借して来た。 // - ただし、/// で comment out する部分については VirtualAwesome での定義は signature // が間違っていると思われ、適当に修正した。 extern "C" { typedef struct { float x,y; } mtPoint; typedef struct { mtPoint pos,vel; } mtReadout; typedef struct { int frame; double timestamp; int identifier, state, foo3, foo4; mtReadout normalized; float size; int zero1; float angle, majorAxis, minorAxis; // ellipsoid mtReadout mm; int zero2[2]; float unk2; } Finger; ///typedef int MTDeviceRef; typedef void* MTDeviceRef;/// typedef int (*MTContactCallbackFunction)(int,Finger*,int,double,int); MTDeviceRef MTDeviceCreateDefault(); void MTRegisterContactFrameCallback(MTDeviceRef, MTContactCallbackFunction); void MTUnregisterContactFrameCallback(MTDeviceRef, MTContactCallbackFunction); ///void MTDeviceStart(MTDeviceRef); void MTDeviceStart(MTDeviceRef, int);/// void MTDeviceStop(MTDeviceRef); void MTDeviceRelease(MTDeviceRef); } #endif <file_sep>//////////////////////////////////////////////////////////////////////////////// // MbpTrackpadControlKey/Logging.h #if !defined(MBP_TRACKPAD_CONTROL_KEY__LOGGING_H) #define MBP_TRACKPAD_CONTROL_KEY__LOGGING_H // compile unit の中で最後に include すること。 // 例えばもし、IOLog を宣言する <IOKit/IOLib.h> より前に include すると、NDEBUG 時 // IOLog の以下の宣言を置換した結果 compile error となる。 // // void IOLog(const char *format, ...) // __attribute__((format(printf, 1, 2))); #if !defined(NDEBUG) # if !defined(NSLog) # define NSLog( m, args... ) NSLog( m, ##args ) # endif # if !defined(IOLog) # define IOLog( m, args... ) IOLog( m, ##args ) # endif #else # if !defined(NSLog) # define NSLog( m, args... ) # endif # if !defined(IOLog) # define IOLog( m, args... ) # endif #endif #endif<file_sep>//////////////////////////////////////////////////////////////////////////////// // MbpTrackpadControlKeyUserClient/MbpTrackpadControlKeyUserClient.cpp #include "./MbpTrackpadControlKeyUserClient.h" #include <IOKit/IOKitKeys.h> #include <IOKit/IOLib.h> #include <libkern/OSByteOrder.h> #include "../../Logging.h" //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // jp_or_iij4u_ss_yamaoka_MbpTrackpadControlKeyUserClient //////////////////////////////////////////////////////////////////////////////// OSDefineMetaClassAndStructors(jp_or_iij4u_ss_yamaoka_MbpTrackpadControlKeyUserClient, IOUserClient) //////////////////////////////////////////////////////////////////////////////// const IOExternalMethodDispatch USER_CLIENT_CLASS_NAME::methods__[METHOD_COUNT] = { // USER_CLIENT_OPEN { (IOExternalMethodAction) &USER_CLIENT_CLASS_NAME::staticOpenUserClient // method pointer. , 0 // no scalar input values. , 0 // no struct input value. , 0 // no scalar output values. , 0 // no struct output value. } // USER_CLIENT_CLOSE , { (IOExternalMethodAction) &USER_CLIENT_CLASS_NAME::staticCloseUserClient // method pointer. , 0 // no scalar input values. , 0 // no struct input value. , 0 // no scalar output values. , 0 // no struct output value. } // SET_CONTROL_MODIFIER_KEY , { (IOExternalMethodAction) &USER_CLIENT_CLASS_NAME::staticSetControlModifierKey // method pointer. , 1 // one scalar input value. , 0 // no struct input value. , 0 // no scalar output values. , 0 // no struct output value. } }; //////////////////////////////////////////////////////////////////////////////// bool USER_CLIENT_CLASS_NAME::initWithTask (task_t owningTask , void* securityToken , UInt32 type , OSDictionary* properties) { bool success; success = DSuper::initWithTask(owningTask, securityToken, type, properties); // This IOLog must follow DSuper::initWithTask because getName relies on the superclass initialization. IOLog("%s[%p]::%s(%p, %p, %d, %p)\n" , getName() , this , __FUNCTION__ , owningTask , securityToken , type , properties); if (success) { // This code will do the right thing on both PowerPC- and Intel-based systems because the cross-endian // property will never be set on PowerPC-based Macs. isCrossEndian_ = false; if (properties != NULL && properties->getObject(kIOUserClientCrossEndianKey)) { // A connection to this user client is being opened by a user process running using Rosetta. // Indicate that this user client can handle being called from cross-endian user processes by // setting its IOUserClientCrossEndianCompatible property in the I/O Registry. if (setProperty(kIOUserClientCrossEndianCompatibleKey, kOSBooleanTrue)) { isCrossEndian_ = true; IOLog("%s[%p]::%s(): isCrossEndian_ = true\n", getName(), this, __FUNCTION__); } } } task_ = owningTask; provider_ = NULL; return success; } //////////////////////////////////////////////////////////////////////////////// bool USER_CLIENT_CLASS_NAME::start(IOService* provider) { bool success; IOLog("%s[%p]::%s(%p)\n", getName(), this, __FUNCTION__, provider); // Verify that this user client is being started with a provider that it knows // how to communicate with. provider_ = OSDynamicCast(DRIVER_CLASS_NAME, provider); success = (provider_ != NULL); if (success) { // It's important not to call DSuper::start if some previous condition // (like an invalid provider) would cause this function to return false. // I/O Kit won't call stop on an object if its start function returned false. success = DSuper::start(provider); } return success; } //////////////////////////////////////////////////////////////////////////////// void USER_CLIENT_CLASS_NAME::stop(IOService* provider) { IOLog("%s[%p]::%s(%p)\n", getName(), this, __FUNCTION__, provider); DSuper::stop(provider); } //////////////////////////////////////////////////////////////////////////////// IOReturn USER_CLIENT_CLASS_NAME::clientClose(void) { IOLog("%s[%p]::%s()\n", getName(), this, __FUNCTION__); // Defensive coding in case the user process called IOServiceClose // without calling closeUserClient first. (void) closeUserClient(); // Inform the user process that this user client is no longer available. This will also cause the // user client instance to be destroyed. // // terminate would return false if the user process still had this user client open. // This should never happen in our case because this code path is only reached if the user process // explicitly requests closing the connection to the user client. bool success = terminate(); if (!success) { IOLog("%s[%p]::%s(): terminate() failed.\n", getName(), this, __FUNCTION__); } // DON'T call DSuper::clientClose, which just returns kIOReturnUnsupported. return kIOReturnSuccess; } //////////////////////////////////////////////////////////////////////////////// IOReturn USER_CLIENT_CLASS_NAME::clientDied(void) { IOReturn result = kIOReturnSuccess; IOLog("%s[%p]::%s()\n", getName(), this, __FUNCTION__); // The default implementation of clientDied just calls clientClose. result = DSuper::clientDied(); return result; } //////////////////////////////////////////////////////////////////////////////// bool USER_CLIENT_CLASS_NAME::willTerminate(IOService* provider, IOOptionBits options) { IOLog("%s[%p]::%s(%p, %d)\n", getName(), this, __FUNCTION__, provider, options); return DSuper::willTerminate(provider, options); } //////////////////////////////////////////////////////////////////////////////// bool USER_CLIENT_CLASS_NAME::didTerminate(IOService* provider, IOOptionBits options, bool* defer) { IOLog("%s[%p]::%s(%p, %d, %p)\n", getName(), this, __FUNCTION__, provider, options, defer); // If all pending I/O has been terminated, close our provider. If I/O is still outstanding, set defer to true // and the user client will not have stop called on it. closeUserClient(); *defer = false; return DSuper::didTerminate(provider, options, defer); } //////////////////////////////////////////////////////////////////////////////// bool USER_CLIENT_CLASS_NAME::terminate(IOOptionBits options) { bool success; IOLog("%s[%p]::%s(%d)\n", getName(), this, __FUNCTION__, options); success = DSuper::terminate(options); return success; } //////////////////////////////////////////////////////////////////////////////// bool USER_CLIENT_CLASS_NAME::finalize(IOOptionBits options) { bool success; IOLog("%s[%p]::%s(%d)\n", getName(), this, __FUNCTION__, options); success = DSuper::finalize(options); return success; } //////////////////////////////////////////////////////////////////////////////// IOReturn USER_CLIENT_CLASS_NAME::externalMethod (uint32_t selector , IOExternalMethodArguments* arguments , IOExternalMethodDispatch* dispatch , OSObject* target , void* reference) { IOLog("%s[%p]::%s(%d, %p, %p, %p, %p)\n" , getName() , this , __FUNCTION__ , selector , arguments , dispatch , target , reference); if (selector < (uint32_t) METHOD_COUNT) { dispatch = (IOExternalMethodDispatch *) &methods__[selector]; if (!target) { target = this; } } return DSuper::externalMethod(selector, arguments, dispatch, target, reference); } //////////////////////////////////////////////////////////////////////////////// IOReturn USER_CLIENT_CLASS_NAME::staticOpenUserClient (USER_CLIENT_CLASS_NAME* target , void* reference , IOExternalMethodArguments* arguments) { return target->openUserClient(); } //////////////////////////////////////////////////////////////////////////////// IOReturn USER_CLIENT_CLASS_NAME::staticCloseUserClient (USER_CLIENT_CLASS_NAME* target , void* reference , IOExternalMethodArguments* arguments) { return target->closeUserClient(); } //////////////////////////////////////////////////////////////////////////////// IOReturn USER_CLIENT_CLASS_NAME::staticSetControlModifierKey (USER_CLIENT_CLASS_NAME* target , void* reference , IOExternalMethodArguments* arguments) { return target->setControlModifierKey(arguments->scalarInput[0]); } //////////////////////////////////////////////////////////////////////////////// IOReturn USER_CLIENT_CLASS_NAME::openUserClient() { IOLog("%s[%p]::%s()\n", getName(), this, __FUNCTION__); if (provider_ == NULL || isInactive()) { return kIOReturnNotAttached; } else if (!provider_->open(this)) { return kIOReturnExclusiveAccess; } return kIOReturnSuccess; } //////////////////////////////////////////////////////////////////////////////// IOReturn USER_CLIENT_CLASS_NAME::closeUserClient() { IOLog("%s[%p]::%s()\n", getName(), this, __FUNCTION__); if (provider_ == NULL) { IOLog("%s[%p]::%s(): returning kIOReturnNotAttached.\n", getName(), this, __FUNCTION__); return kIOReturnNotAttached; } else if (provider_->isOpen(this)) { provider_->close(this); return kIOReturnSuccess; } else { IOLog("%s[%p]::%s(): returning kIOReturnNotOpen.\n", getName(), this, __FUNCTION__); return kIOReturnNotOpen; } } //////////////////////////////////////////////////////////////////////////////// IOReturn USER_CLIENT_CLASS_NAME::setControlModifierKey(bool isActive) { IOLog("%s[%p]::%s(isActive = %d)\n" , getName() , this , __FUNCTION__ , int(isActive)); if (provider_ == NULL || isInactive()) { return kIOReturnNotAttached; } else if (!provider_->isOpen(this)) { return kIOReturnNotOpen; } else { return provider_->setControlModifierKey(isActive); } } <file_sep>//////////////////////////////////////////////////////////////////////////////// // MbpTrackpadControlKey/UserKernelShared.h #if !defined(MBP_TRACKPAD_CONTROL_KEY__USER_KERNEL_SHARED_H) #define MBP_TRACKPAD_CONTROL_KEY__USER_KERNEL_SHARED_H #define DRIVER_CLASS_NAME jp_or_iij4u_ss_yamaoka_MbpTrackpadControlKeyDriver #define DRIVER_CLASS_NAME_STRING "jp_or_iij4u_ss_yamaoka_MbpTrackpadControlKeyDriver" // user client method dispatch selectors. enum { USER_CLIENT_OPEN, USER_CLIENT_CLOSE, SET_CONTROL_MODIFIER_KEY, METHOD_COUNT, }; #endif<file_sep>//////////////////////////////////////////////////////////////////////////////// // MbpTrackpadControlKeyUtility/CTrackpadController.cpp #include "CTrackpadController.h" //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // CTrackpadController //////////////////////////////////////////////////////////////////////////////// CTrackpadController* CTrackpadController::instance__ = NULL; //////////////////////////////////////////////////////////////////////////////// CTrackpadController::CTrackpadController(FHandler handler) : handler_(handler) , device_(NULL) , isPressed_(false) { assert(instance__ == NULL); assert(handler); } //////////////////////////////////////////////////////////////////////////////// CTrackpadController::~CTrackpadController() { instance__ = NULL; } //////////////////////////////////////////////////////////////////////////////// bool CTrackpadController::initiate() { instance__ = NULL; device_ = NULL; isPressed_ = false; MTDeviceRef device = MTDeviceCreateDefault(); if (device == NULL) { return false; } instance__ = this; device_ = device; MTRegisterContactFrameCallback(device_, callback); MTDeviceStart(device_, 0); return true; } //////////////////////////////////////////////////////////////////////////////// void CTrackpadController::terminate() { MTDeviceStop(device_); MTDeviceRelease(device_); instance__ = NULL; device_ = NULL; isPressed_ = false; } //////////////////////////////////////////////////////////////////////////////// void CTrackpadController::setPressed(bool isPressed) { isPressed_ = isPressed; handler_(isPressed); } //////////////////////////////////////////////////////////////////////////////// int CTrackpadController::callback(int device, Finger* data, int nFingers, double timestamp, int frame) { assert(instance__ != NULL); CTrackpadController& tc = *instance__; if (nFingers == 0) { if (tc.isPressed()) { tc.setPressed(false); } } for (int i = 0; i < nFingers; ++i) { Finger* f = &data[i]; if (0.95 < f->normalized.pos.y) { if (!tc.isPressed()) { tc.setPressed(true); } } else { if (tc.isPressed()) { tc.setPressed(false); } } } return 0; } <file_sep>//////////////////////////////////////////////////////////////////////////////// // MbpTrackpadControlKeyUserClient/MbpTrackpadControlKeyUserClient.h #if !defined(MBP_TRACKPAD_CONTROL_KEY_DRIVER__MBP_TRACKPAD_CONTROL_KEY_USER_CLIENT_H) #define MBP_TRACKPAD_CONTROL_KEY_DRIVER__MBP_TRACKPAD_CONTROL_KEY_USER_CLIENT_H #include "./MbpTrackpadControlKeyDriver.h" #include "../../UserKernelShared.h" #include <IOKit/IOUserClient.h> #define USER_CLIENT_CLASS_NAME jp_or_iij4u_ss_yamaoka_MbpTrackpadControlKeyUserClient //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /** * @class jp_or_iij4u_ss_yamaoka_MbpTrackpadControlKeyUserClient * @brief */ class USER_CLIENT_CLASS_NAME : public IOUserClient { OSDeclareDefaultStructors(jp_or_iij4u_ss_yamaoka_MbpTrackpadControlKeyUserClient) typedef IOUserClient DSuper; public: // IOUserClient interfaces. virtual bool initWithTask(task_t owningTask, void* securityToken, UInt32 type, OSDictionary* properties); virtual bool start(IOService* provider); virtual void stop(IOService* provider); virtual IOReturn clientClose(void); virtual IOReturn clientDied(void); virtual bool willTerminate(IOService* provider, IOOptionBits options); virtual bool didTerminate(IOService* provider, IOOptionBits options, bool* defer); virtual bool terminate(IOOptionBits options = 0); virtual bool finalize(IOOptionBits options); // KPI for supporting access from both 32-bit and 64-bit user processes beginning with Mac OS X 10.5. virtual IOReturn externalMethod(uint32_t selector , IOExternalMethodArguments* arguments , IOExternalMethodDispatch* dispatch , OSObject* target , void* reference); protected: static const IOExternalMethodDispatch methods__[METHOD_COUNT]; DRIVER_CLASS_NAME* provider_; task_t task_; bool isCrossEndian_; static IOReturn staticOpenUserClient(USER_CLIENT_CLASS_NAME* target, void* reference, IOExternalMethodArguments* arguments); static IOReturn staticCloseUserClient(USER_CLIENT_CLASS_NAME* target, void* reference, IOExternalMethodArguments* arguments); static IOReturn staticSetControlModifierKey(USER_CLIENT_CLASS_NAME* target, void* reference, IOExternalMethodArguments* arguments); virtual IOReturn openUserClient(); virtual IOReturn closeUserClient(); virtual IOReturn setControlModifierKey(bool isActive); }; #endif
864a52eb9f9ec5a7720087dae168a78d0bd4bc0b
[ "C", "C++" ]
11
C++
jamakesso/MbpTrackpadControlKey
741d1a32fd272010ef44bcd8b24d2265d7251757
693c12718e53212dad84fb64a368ee456478ff01
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Ghost : MonoBehaviour { Renderer[] rends; float alpha = 1; float flashSpeed = 2; // Start is called before the first frame update void Start() { rends = this.gameObject.GetComponentsInChildren<Renderer>(); foreach (Renderer r in rends) { r.material.SetFloat("_Mode", 3.0f); r.material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); r.material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); r.material.SetInt("_ZWrite", 0); r.material.DisableKeyword("_ALPHATEST_ON"); r.material.EnableKeyword("_ALPHABLEND_ON"); r.material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); r.material.renderQueue = 3000; r.material.color = new Color(1, 1, 1, alpha); } } void OnDisable() { foreach (Renderer r in rends) { r.material.SetFloat("_Mode", 0.0f); r.material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); r.material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); r.material.SetInt("_ZWrite", 1); r.material.DisableKeyword("_ALPHATEST_ON"); r.material.DisableKeyword("_ALPHABLEND_ON"); r.material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); r.material.renderQueue = -1; r.material.color = new Color(1, 1, 1, 1); } } // Update is called once per frame void Update() { alpha = 0.3f + Mathf.PingPong(Time.time * flashSpeed, 0.7f); foreach (Renderer r in rends) { r.material.color = new Color(1, 1, 1, alpha); } } } <file_sep># Build-A-Multiplayer-Kart-Racing-Game-In-Unity-V.2019 Build A Multiplayer Kart Racing Game In Unity V.2019 by Packt Publishing
625fb162ed75a78b2cd2d01690bfb59311aabd44
[ "Markdown", "C#" ]
2
C#
PacktPublishing/Build-A-Multiplayer-Kart-Racing-Game-In-Unity-V.2019
e4ee17d4066be57b2684542f166f21c1da1851f8
0d6c1c02c880c777b7a280e81d2c3212ee8edfca
refs/heads/main
<repo_name>sgrj/prompt-functions<file_sep>/kubernetes-context/kubernetes-context.go package main import ( "fmt" "io/ioutil" "log" "os" "gopkg.in/yaml.v3" ) type Context struct { Cluster string Namespace string User string } type ContextAndName struct { Context Context Name string } type Config struct { Contexts []ContextAndName CurrentContext string `yaml:"current-context"` } func main() { kubeconfig := os.Getenv("KUBECONFIG") if kubeconfig != "" { log.Fatal("$KUBECONFIG is not supported") } data, err := ioutil.ReadFile(fmt.Sprintf("%s/.kube/config", os.Getenv("HOME"))) if err != nil { log.Fatalf("Cannot read config: %v", err) } config := Config{} if err := yaml.Unmarshal([]byte(data), &config); err != nil { log.Fatalf("Cannot parse config: %v", err) } if config.CurrentContext == "" { return } namespace := "" for _, context := range config.Contexts { if context.Name == config.CurrentContext { namespace = context.Context.Namespace break } } fmt.Printf("%v", config.CurrentContext) if namespace != "" { fmt.Printf(" (%v)", namespace) } } <file_sep>/README.md # Prompt functions Functions to be used in a shell prompt as described in my blog post [Performance optimizations for the shell prompt](https://seb.jambor.dev/posts/performance-optimizations-for-the-shell-prompt/). <file_sep>/kubernetes-context/README.md # Kubernetes context Display the current kubernetes context and the namespace set in that context. The shell functions require [yq](https://github.com/mikefarah/yq), compiled from source for best performance. All versions assume that `KUBECONFIG` is not set, and print an error otherwise. <file_sep>/kubernetes-context/kubernetes-context.bash function kubernetes-context { local context namespace if [ -n "$KUBECONFIG" ]; then echo -n "\$KUBECONFIG is not supported" return fi context=$(yq e '.current-context // ""' ~/.kube/config) if [ -z "$context" ]; then return fi namespace=$( yq e "(.contexts[] | select(.name == \"$context\").context.namespace) // \"\"" \ ~/.kube/config ) echo -n "$context" if [ -n "$namespace" ]; then echo -n " ($namespace)" fi } <file_sep>/kubernetes-context/go.mod module seb.jambor.dev/kubernetes-context go 1.13 require ( gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b )
cb3ea8e7fbee698b63930806481cb3b5047e7eca
[ "Markdown", "Go Module", "Go", "Shell" ]
5
Go
sgrj/prompt-functions
3bb8aaa0f2de2ebc7b3c39a72821ea369755560d
b9ee0581f4c95ece810992aacea7ffb460df9115
refs/heads/master
<repo_name>dgomezda/calendar<file_sep>/main.js function calendarWidget(widget, strStartDate, strnumDays, countryCode) { var numDays = +strnumDays; var startDate = toDate(strStartDate); var endDate = new Date(startDate); endDate.setDate(startDate.getDate() + numDays); $(widget).empty(); $(widget).append('<div class="month weekheader"><ul><li>S</li><li>M</li><li>T</li><li>W</li><li>T</li><li>F</li><li>S</li></ul></div>') var tempDate = new Date(startDate.getFullYear(), startDate.getMonth(), 1); while (tempDate <= endDate) { var holidays = []; holidays = getHolidays(tempDate.getMonth()+1, tempDate.getFullYear()); var invalidBefore = getInvalidBefore(startDate, tempDate); var invalidAfter = getInvalidAfter(endDate, tempDate); addMonth(widget ,tempDate.getMonth(), tempDate.getFullYear(), invalidBefore, invalidAfter, holidays); tempDate.setMonth(tempDate.getMonth()+1); } function addMonth(widget, month, year, invalidBefore, invalidAfter, holidays){ var days = getNumDays(month,year), // days per month fDay = getFirstDay(month,year)+1, // 1st day position, considering sunday. months = ['January','February','March','April','May','June','July','August','September','October','November','December']; var monthElement = $("<ul class='group'></ul>") $(monthElement).append('<p class="monthname center">' + months[month] +' '+ year + '</p>') // put the first day in the correct position for (var i=0;i<fDay-1+invalidBefore;i++) { $('<li class="invalidday">&nbsp;</li>').appendTo(monthElement); } // write day numbers in month for (var i = 1+ invalidBefore;i<=days - invalidAfter;i++) { if ((i + fDay -1 )%7 == 1 || (i + fDay -1) % 7 == 0){ $('<li class="weekend">'+i+'</li>').appendTo(monthElement); } else { $('<li class="weekday">'+i+'</li>').appendTo(monthElement); } } $(widget).append($("<div class='month'></div>").append(monthElement)); } function getFirstDay(month,year) { return new Date(year,month,1).getDay(); } function getNumDays(month,year) { return new Date(year,month+1,0).getDate(); } function toDate(dateStr) { var parts = dateStr.split("\/"); return new Date(parts[2], parts[1] - 1, parts[0]); } function getInvalidBefore(startDate, tempDate){ var ndays= 0; if(startDate.getMonth() == tempDate.getMonth() && startDate.getFullYear() == tempDate.getFullYear()) { ndays = startDate.getDay() -1; } return ndays; } function getInvalidAfter(endDate, tempDate){ var ndays= 0; if(endDate.getMonth() == tempDate.getMonth() && endDate.getFullYear() == tempDate.getFullYear()) { ndays = getNumDays(endDate.getMonth(), endDate.getFullYear()) - endDate.getDate() +1 } return ndays; } function getHolidays(month,year) { var holidays = []; $.ajax({ type: "GET", dataType: "json", url: "https://holidayapi.com/v1/holidays?key=<KEY>&country=PE&year="+ year +"&month=" + month, async: false, success: function(data){ if ( data.status == 200) { holidays = data.holidays.map(function (item,index) { return new Date(item.date.substr(0,4), item.date.substr(5,2)-1, item.date.substr(8,2)) }); } } }); return holidays; } } $( "#calendar-form" ).submit(function( event ) { var strStartDate = $("#startDate").val(), strnumDays = $("#numDays").val(), countryCode = $("#countryCode").val(); calendarWidget($('#calendar-container'), strStartDate, strnumDays, countryCode); event.preventDefault(); }); <file_sep>/README.md # calendar a simple javascript calendar
91816d1ea975f2a616f0e913389f0167b91a2e92
[ "JavaScript", "Markdown" ]
2
JavaScript
dgomezda/calendar
d0dea3d35c65d66f202b4d75db68e4e87b893a77
8b8a608ea374fcceeb81610a416eb8f2354e9dff
refs/heads/master
<repo_name>ThesisDistributedProduction/TestResults<file_sep>/TestCalc/index.js // node samples/sample.js var parse = require('csv').parse; var fs = require('fs'); var q = require('q'); var _ = require('lodash-node'); var jStat = require('jStat'); var searchDir = __dirname.split('/'); searchDir.pop(); var _RESULT_FOLDER = "CalcResult"; var _PARAMETER_FILE = "parameters.json"; var _AVG_FIELD_NAMES = ["MS since last write", "sig2:MS since last write"]; var _CHACHE_COUNT = "Cache count" function writeFileTikzBoxplot(file, objects){ var xIndexes = []; var xticklabels = []; var medianPlot = []; var boxPlots = []; var extraAllignmentBoxes = []; var extraPlot = []; if(!_.isUndefined(objects[0].avgCacheCounts)){ extraPlot.push("\\addplot[thick, orange!70] coordinates {"); } for(var i = 0; i < objects.length; i++){ xIndexes.push(i + 1); xticklabels.push(objects[i].xAxisLabel); boxPlots.push("%% " + objects[i].fileName); boxPlots.push([ ' \\buildBoxPlot{' + objects[i].cycleTime.median, objects[i].cycleTime.upperQuardant, objects[i].cycleTime.lowerQuardant, objects[i].cycleTime.max, objects[i].cycleTime.min + '}' ].join('}{') + '\n'); medianPlot.push(" (" + (i + 1) + " ," + objects[i].cycleTime.median + ")"); extraAllignmentBoxes.push("\\buildBoxPlot[black]{0}{0}{0}{0}{0}"); if(!_.isUndefined(objects[0].avgCacheCounts)){ extraPlot.push(" (" + (i + 1) + " ," + objects[i].avgCacheCounts + ")"); /* extraAllignmentBoxes.push([ ' \\buildBoxPlot{' + objects[i].cacheData.median, objects[i].cacheData.upperQuardant, objects[i].cacheData.lowerQuardant, objects[i].cacheData.max, objects[i].cacheData.min + '}' ].join('}{') + '\n'); }else{ extraAllignmentBoxes.push("\\buildBoxPlot[black]{0}{0}{0}{0}{0}"); */ } } if(!_.isUndefined(objects[0].avgCacheCounts)){ extraPlot.push(" };"); } var data = [ "\\begin{tikzpicture}", "\\begin{axis}", " [", " width=\\textwidth,", " axis y line*=left,", " xlabel=" + (objects[0].xAxisType === "msleep" ? "Sleeptime (ms)" : "Number of turbines") + ",", " ylabel=Regulation cycle time (ms),", " ymin = 0,", " xtick={" + xIndexes.join(', ') + "},", " xticklabels={" + xticklabels.join(', ') + "},", " boxplot/draw direction=y", " ]", "", boxPlots.join('\n'), "", "\\addplot[thick, red!70] coordinates {", medianPlot.join('\n'), "", "};", "", "\\end{axis}", "\\end{tikzpicture}", ""].join('\n'); if(!_.isUndefined(objects[0].avgCacheCounts)){ data += [ "\\begin{tikzpicture}", "\\begin{axis}", " [", " width=\\textwidth,", " axis y line*=left,", " xlabel=" + (objects[0].xAxisType === "msleep" ? "Sleeptime (ms)" : "Number of turbines") + ",", " ymin = 0,", " ylabel=Average Cache hits,", " xtick={" + xIndexes.join(', ') + "},", " xticklabels={" + xticklabels.join(', ') + "},", " boxplot/draw direction=y", " ]", extraAllignmentBoxes.join('\n'), extraPlot.join('\n'), "\\end{axis}", "\\end{tikzpicture}" ].join('\n'); } return writeFile(file, data); } function writeFileJson(file, objects){ var data = JSON.stringify(objects, null, 2); return writeFileJson(file, data); } function writeFile(file, data){ var deferred = q.defer(); if(_.isArray(file)){ file = file.join('/'); } console.log("writing file: " + file); fs.writeFile(file, data, function(err){ if(err === null){ deferred.resolve(); }else{ console.log("Error writing file: " + file); deferred.reject(err); } }); return deferred.promise; } function createBoxData(values, factor){ values = values.sort(function(a, b){ return a-b; }); var quardant = values.length / 4; var iUpperQuardant = Math.round(quardant * 3 ); var iMedian = Math.round(values.length / 2 ); var iLowerQuardant = Math.round(quardant); return { max: values[values.length -1 ] / factor, upperQuardant: values[iUpperQuardant] / factor, median: values[iMedian] / factor, lowerQuardant: values[iLowerQuardant] / factor, min: values[0] / factor }; } function getFileIndex(fileName){ var index = fileName.split('.')[0]; index = index.match(/\d*$/)[0]; index = parseInt(index); return index; } function createObj(file, parameters, obj){ var deferred = q.defer(); var fileName = file[file.length -1]; file = file.join("/"); // searchDir.concat([_PARAMETER_FILE]).join('/'); var rs = fs.createReadStream(file); var fileNumberMappingFn; eval( "fileNumberMappingFn = " + parameters.FileNumberMapping.join('\n')); var xAxisLabel = fileNumberMappingFn(getFileIndex(fileName)); var NS_TO_MS_FACTOR = 1000000; function _createObj(name, err, data){ var cycleLabel; var avgCacheCounts = null; var cacheData = null; if( _.isNaN( parseInt( data[0][_AVG_FIELD_NAMES[0]] ) ) ){ cycleLabel = _AVG_FIELD_NAMES[1]; }else{ cycleLabel = _AVG_FIELD_NAMES[0]; } for(var i = 0; i < data.length; i++){ data[i][cycleLabel] = parseInt(data[i][cycleLabel]); if(!_.isUndefined(data[i][_CHACHE_COUNT])){ data[i][_CHACHE_COUNT] = parseInt(data[i][_CHACHE_COUNT]); } if(data[i][cycleLabel] === 0){ data.splice(--i, 1); } } var cycledata = createBoxData(data.map(function(value){ return parseInt(value[cycleLabel]); }), NS_TO_MS_FACTOR); if(data.length > 0 && !_.isUndefined(data[0][_CHACHE_COUNT]) ){ var totalCacheCounts = 0; for(var i = 0; i < data.length; i++){ totalCacheCounts += data[i][_CHACHE_COUNT]; } avgCacheCounts = totalCacheCounts / data.length; /* cacheData = createBoxData(data.map(function(value){ return parseInt(value[_CHACHE_COUNT]); }), 1);*/ } var newObj = { "xAxisLabel": xAxisLabel, "fileName": file, "xAxisType": parameters.type, "cycleTime": cycledata, "cacheData": cacheData }; if(_.isNumber(avgCacheCounts)){ newObj.avgCacheCounts = avgCacheCounts; } obj.results.unshift(newObj); deferred.resolve(obj); } parser = parse({columns: true}, _createObj.bind(this, file)); rs.pipe(parser); return deferred.promise; } function processFiles(files, parameters) { var deferred = q.defer(); var startObj = { results: [], i : files.length -1 }; function callback(obj){ if(--obj.i >= 0){ createObj(files[obj.i], parameters, obj).then(callback); }else{ obj.results = obj.results.sort(function(a, b){ return parseInt(a.xAxisLabel)- parseInt(b.xAxisLabel); }); deferred.resolve(obj.results); } } createObj(files[startObj.i], parameters, startObj).then(callback); return deferred.promise; } function loadParmeters(searchDir, parameters){ var file = searchDir.concat([_PARAMETER_FILE]).join('/'); parameters = _.cloneDeep(parameters); // work with a copy; if( fs.existsSync(file) ){ try{ var _parameters = fs.readFileSync(file); _parameters = JSON.parse(_parameters); parameters = _.merge(parameters, _parameters); //console.log(JSON.stringify(parameters, null, 2)); return parameters; }catch(e){ debugger; console.log("Error parsing parameters: " + e); return parameters; } }else{ return parameters; } } function processDir(searchDir, parameters) { var _parameters = loadParmeters(searchDir, parameters); var files = fs.readdirSync(searchDir.join('/')); //console.log(searchDir.join('/')); var csvFiles = []; var dirsToProcess = []; for(var i = 0; i < files.length; i++){ var elm = files[i]; if(elm.charAt(0) === "." || elm === "TestCalc" || elm === _RESULT_FOLDER){ continue; } var file = searchDir.concat([elm]); var isDir = fs.statSync(file.join('/')).isDirectory(); if(isDir){ dirsToProcess.push(file); }else if(elm.match(/.csv$/)){ csvFiles.push(file); } } if(csvFiles.length > 0){ var resultDir = searchDir.concat([_RESULT_FOLDER]).join('/'); if(!fs.existsSync(resultDir) ){ fs.mkdirSync(resultDir); } processFiles(csvFiles, _parameters).then(function(results){ // writeFileJson(resultDir + "/UsedParameters.json", _parameters); // writeFileJson(resultDir + "/boxplot.json", results); writeFileTikzBoxplot(resultDir + "/boxplot.tex", results); for(var i = 0; i < dirsToProcess.length; i++){ processDir(dirsToProcess[i], _parameters); } }); }else{ for(var i = 0; i < dirsToProcess.length; i++){ processDir(dirsToProcess[i], _parameters); } } } processDir(searchDir, {});
ee4c6fd1df9e0fd495309c95645a2f84e65e6a74
[ "JavaScript" ]
1
JavaScript
ThesisDistributedProduction/TestResults
60ffd46c9b70c6e772b14a840d915cf0adeef415
72c5e883c4ca5269b362aaa9123cce09af7c006a
refs/heads/master
<repo_name>uuboyscy/monitor<file_sep>/.monitor_tws/init.sh #!/bin/bash set -u #set -x ################################################################# # # Sorting job_stream_id, job_detail in files # # Step1. Log in and qurey js_id which are abnormal # Put these information in a temporary file tmp_js_output # # Step2. Read tmp_js_output to extract each id of js # And save them in tmp_id_file # # Step3. Read tmp_id_file to extract id of js # Save detail in tmp_js_detail # Includ the steps in which the ERROR or STUCK occur # ################################################################## ############## Log in TWS ######################### # The shell variable is used to show full name of js export MAESTRO_OUTPUT_STYLE="LONG" # These may be used in the future day_yesterday=$(date -d yesterday +"%d") month_yesterday=$(date -d yesterday +"%m") year_yesterday=$(date -d yesterday +"%Y") #echo "y" | conman -username ap****** -password Qa******** 'ss @ODS_@' | grep $(month_yesterday)/ | grep -E "(ABEND|STUCK|ERROR)" # Save abnormal js to tmp_js_output #echo "y" | conman -username ap****** -password Qa******** 'ss @ODS_@;showid' | grep -E "(ABEND|STUCK|ERROR)" > ./.secret/tmp_js_output #echo "y" | conman -username $(cat ./.secret/.tws_userid) -password $(cat ./.secret/.tws_passwd) 'ss @ODS_@;showid' | grep -E "(ABEND|STUCK|ERROR)" > ./.secret/tmp_js_output #ssh to tpebnkmdmap01p ssh $(cat ./.secret/.tws_userid)@tpebnkmdmap01p 'source ~/.bash_profile;clear;echo "y" | conman "ss FODSETL01#@ODS@;showid" | grep -E "(ABEND|STUCK|ERROR)"' | sed -n '4,$p' > ./.secret/tmp_js_output #################################################### ############ Save id to tmp_id_file ################ # Initial tmp_id_file if [ -f "./.secret/tmp_id_file" ]; then rm ./.secret/tmp_id_file fi # Read each row in ./tmp_js_output # and save each job whit job_id in ./tmp_js_output filename='./.secret/tmp_js_output' exec < $filename while read line do # Save id to tmp_id_file #echo "sj" $(echo $line | awk -F'; ' '{print $2}' | awk -F'{' '{print $2}' | awk -F'}' '{print $1}') ";schedid" >> ./.secret/tmp_id_file #echo "sj FODSETL01#$(echo $line | awk -F' ' '{print $2}' | awk -F'#' '{print $2}')" >> ./.secret/tmp_id_file echo "sj FODSETL01#$(echo $line | awk -F'{' '{print $NF}' | awk -F'}' '{print $1}');schedid" >> ./.secret/tmp_id_file done #################################################### ######## Save job detail to tmp_js_detail ########## # Initial tmp_js_detail if [ -f "./.secret/tmp_js_detail" ]; then rm ./.secret/tmp_js_detail fi # Save js detail to tmp_js_detail #filename='./.secret/tmp_id_file' #exec < $filename #o=1 #while read line #do # echo $line # sleep 2s # echo "++$o++" >> ./.secret/tmp_js_detail # ssh $(cat ./.secret/.tws_userid)@tpebnkmdmap01p "source ~/.bash_profile;echo 'y' | conman '$line' > .tmp_js_detail;cat .tmp_js_detail" >> ./.secret/tmp_js_detail # echo "+$o+" >> ./.secret/tmp_js_detail # echo "" >> ./.secret/tmp_js_detail # # o=$(expr $o + 1) #done ### latest version ssh $(cat ./.secret/.tws_userid)@tpebnkmdmap01p "source ~/.bash_profile;conman -username $(cat ./.secret/.tws_userid) -password $(cat ./.secret/.tws_passwd)" << EOF < ./.secret/tmp_id_file > test_EOF EOF echo "%abcdefg112233" >> test_EOF # Save js detail to tmp_js_detail filename='./.secret/tmp_id_file' exec < $filename o=1 while read line do echo $line "executing..." #sleep 1s echo "++$o++" >> ./.secret/tmp_js_detail echo $line >> ./.secret/tmp_js_detail sed -n "/%${line}/,/%/p" ./test_EOF >> ./.secret/tmp_js_detail echo "+$o+" >> ./.secret/tmp_js_detail echo "" >> ./.secret/tmp_js_detail o=$(expr $o + 1) done #################################################### ######### Execute js_query_form_all.sh ## ########## sleep 1s sh ./js_query_form_all.sh #################################################### <file_sep>/.monitor_tws/show.sh #!/bin/bash set -u ###################################### # # Show each js and its id # The information includes # js name, date, status, id # ###################################### filename='./.secret/tmp_js_output' exec < $filename # Count js c=1 # Initial tmp_id_file if [ -d "./.secret/tmp_id_file" ]; then rm ./.secret/tmp_id_file fi while read line do # Print js and id printf "%-3s %-20s %-8s %-8s" $c. $(echo $line | awk -F'#' '{print $2}' | awk -F' ' '{print $1}') \ $(echo $line | awk -F'#' '{print $2}' | awk -F' ' '{print $4}') \ $(echo $line | awk -F'#' '{print $2}' | awk -F' ' '{print $3}') #echo $line | awk -F'; ' '{print $2}' | awk -F'{' '{print $2}' | awk -F'}' '{print $1}' echo $line | awk -F'{' '{print $NF}' | awk -F'}' '{print $1}' echo "" c=$(expr $c + 1) done <file_sep>/.monitor_tws/js_query_form_all.sh #!/bin/bash set -u #set -x ######################################################## # # Show all job_stream information from oracle # # Include JS_NAME JOB_NAME FIRST_NAME SECOND_NAME # SRC_OWNER SRC_NAME TGT_OWNER TGT_NAME # DESCRIPTION JOB_SYS # # And save them in the file named "sqlplus_output_all" # ####################################################### if [ -f "./.secret/sqlplus_output_all" ]; then rm ./.secret/sqlplus_output_all fi # Count js c=1 for j in $(cat ./.secret/tmp_js_output | awk -F'#' '{print $2}' | awk '{print $1}') do echo "++$c++" >> ./.secret/sqlplus_output_all sh js_query_form.sh $j >> ./.secret/sqlplus_output_all echo "+$c+" >> ./.secret/sqlplus_output_all echo "" >> ./.secret/sqlplus_output_all c=$(expr $c + 1) done <file_sep>/.monitor_tws/forestage_information/show_forestage_info.py #!/usr/bin/env python # -*-coding: utf-8-*- import dataFormat import sys f = open('./test.csv', 'r') csv_str = f.read() f.close() sd = dataFormat.Csv(csv_str, sys.argv) for js in sys.argv[1:]: print('') print('============{:^26}============'.format(js)) print('') try: for n, i in enumerate(sd.output_dict_with_index[js]): if i in ['部門', '科別', '負責人', '部別', '備註']: print('{:8} : {}'.format(i, sd.output_dict_with_index[js][i])) elif i.strip() == '' or i.replace(' ', '').replace(' ', '').strip() == '' or i == ' ' or n == 4: continue else: print('{:10}: {}'.format(i, sd.output_dict_with_index[js][i])) except KeyError: print('No forestage information!') print('') print('=' * 50) print('') <file_sep>/INIT.sh #!/bin/bash set -u #set -x echo "=======================" echo " Setup Oracle " echo "=======================" echo "Enter your OracleDB ID >" read a echo "Enter your OracleDB password >" read b echo "" echo "=======================" echo " Setup TWS " echo "=======================" echo "Enter your TWS ID >" read c echo "Enter your TWS password >" read d echo "" echo "Setting..." echo "$a" > .monitor_tws/.secret/.userid echo "$b" > .monitor_tws/.secret/.passwd echo "$c" > .monitor_tws/.secret/.tws_userid echo "$d" > .monitor_tws/.secret/.tws_passwd sleep 1s echo "Done." echo "" <file_sep>/.monitor_tws/connect_to_db.sh #!/bin/bash put="$(cat /etc/hostname)" sqlplus $(cat ./.secret/.userid)@${put: -1}sid/$(cat ./.secret/.passwd) <file_sep>/APP.sh #!/bin/bash set -u #set -x ###################################################################### # # Usage: # # [JS OVERVIEW] # After js shown # Press 1 to get data information from DB # Press 2 to get abnormal job-stream and job status # Press 3 to get forestage information of abnormal JS # Press 4 to get holding JS forestage information # Press 0 to reload # Press q to quit # # [1 : DB : Select js number shown in the head of each row] # Press 1 ~ n for getting the n_th js information # (The number n is up to query result) # Press r to return to the last step # Press q to quit # # [2 : TWS : Select js number] # Press 1 ~ n for getting single js information # (Include the step where job occur obstacle) # Press r to return to the last step # Press q to quit # # [3 : TWS & CSV & DB : Select js number] # ## Expect to do : # #### 1. Forestage keyperson # #### 2. File name # #### 3. Last execute date and time # Under construction... # # [4 : TWS & CSV & DB : Select js number] # ## Expect to do : # #### 1. Forestage keyperson # #### 2. File name # #### 3. Last execute date and time # Under construction... # ###################################################################### ######## Initiate all tmp file ######### echo "Loading data..." sleep 2s cd .monitor_tws sh init.sh #sleep 2s js_count=$(wc -l ./.secret/tmp_js_output | awk '{print $1}') echo $js_count ######################################## ############ Main function ############# clear OVERVIEW_OPTION="0" while [ "$OVERVIEW_OPTION" != "q" ] do # Show Job Stream menu echo "" echo "====================== JOB STREAM MENU ======================" echo "" sh show.sh echo "=============================================================" echo "" echo "[1] Press 1 to get data information from DB" echo "[2] Press 2 to get abnormal job-stream and job status" echo "[3] Press 3 to get forestage information of abnormal JS" echo "[4] Press 4 to get holding JS forestage information" echo "[0] Press 0 to re-load" echo "[q] Press q to quit" echo -n ">>> " # For overview of all job stream read OVERVIEW_OPTION if [ "x$(echo $OVERVIEW_OPTION)" = "x1" ]; then #echo "You enter $OVERVIEW_OPTION" DB_OPTION="0" while [ "$DB_OPTION" != "r" ] do echo "" echo "[Information to each js from DB]" echo "[1~$js_count] Choose JOB_STREAM number" echo "[0] Or enter 0 to show menu" echo "[r] Enter r to return" echo "[q] Press q to quit" echo -n ">>> " # Show information to JS from DB # Join RD_JOBINFO, RD_JOBSRCINFO, RD_JOBTGTINGO read DB_OPTION if [ "x$(echo $DB_OPTION)" != "xr" ]; then echo "" echo "=========================================" sed -n "/++${DB_OPTION}++/,/+${DB_OPTION}+/p" ./.secret/sqlplus_output_all | sed -n '2,11'p echo "=========================================" fi # Re-show the Job Stream menu if [ "x$(echo $DB_OPTION)" = "x0" ]; then clear echo "====================== JOB STREAM MENU ======================" echo "" sh show.sh echo "=============================================================" fi # Quit the process if [ "x$(echo $DB_OPTION)" = "xq" ]; then clear DB_OPTION="r" OVERVIEW_OPTION="q" fi done elif [ "x$(echo $OVERVIEW_OPTION)" = "x2" ] then #echo "You enter $OVERVIEW_OPTION" TWS_JS_OPTION="0" while [ "$TWS_JS_OPTION" != "r" ] do echo "" echo "[Job information]" echo "[1~$js_count] Choose JOB_STREAM number" echo "[0] Or enter 0 to show menu" echo "[r] Enter r to return" echo "[q] Press q to quit" echo -n ">>> " # Show the form for single job read TWS_JS_OPTION if [ "x$(echo $TWS_JS_OPTION)" != "xr" ]; then echo "" echo "================================================================================================================" #echo "show each step in which the job occur obstacle" sed -n "/++${TWS_JS_OPTION}++/,/+${TWS_JS_OPTION}+/p" .secret/tmp_js_detail | sed '1,3d' | sed '$d' echo "================================================================================================================" fi # Re-show the Job Stream menu if [ "x$(echo $TWS_JS_OPTION)" = "x0" ]; then clear echo "====================== JOB STREAM MENU ======================" echo "" sh show.sh echo "=============================================================" fi # Quit the process if [ "x$(echo $TWS_JS_OPTION)" = "xq" ]; then clear TWS_JS_OPTION="r" OVERVIEW_OPTION="q" fi done elif [ "x$(echo $OVERVIEW_OPTION)" = "x3" ] then JS_FORESTAGE_OPTION="0" while [ "$JS_FORESTAGE_OPTION" != "r" ] do echo "" echo "[JS forestage information]" echo "[1~$js_count] Choose JOB_STREAM number" echo "[0] Or enter 0 to show menu" echo "[r] Enter r to return" echo "[q] Press q to quit" echo -n ">>> " read JS_FORESTAGE_OPTION # Show the form for single JS forestage information if [ "x$(echo $JS_FORESTAGE_OPTION)" != "xr" ]; then TMP_JS_NAME=$(head ./.secret/tmp_js_output -n$JS_FORESTAGE_OPTION | tail -n1 | awk -F'#' '{print $2}' | awk -F' ' '{print $1}') echo "" #echo "show each step in which the job occur obstacle" #echo "$(JS_FORESTAGE_OPTION)" cd forestage_information/ #forestage_information/show_forestage_info.py python show_forestage_info.py $TMP_JS_NAME cd ../ fi # Re-show the Job Stream menu if [ "x$(echo $JS_FORESTAGE_OPTION)" = "x0" ]; then clear echo "====================== JOB STREAM MENU ======================" echo "" sh show.sh echo "=============================================================" fi # Quit the process if [ "x$(echo $JS_FORESTAGE_OPTION)" = "xq" ]; then clear JS_FORESTAGE_OPTION="r" OVERVIEW_OPTION="q" fi done elif [ "x$(echo $OVERVIEW_OPTION)" = "x4" ] then echo "Coming soon..." elif [ "x$(echo $OVERVIEW_OPTION)" = "x0" ] then clear echo "Loading data..." sleep 1s sh init.sh js_count=$(wc -l ./.secret/tmp_js_output | awk '{print $1}') echo $js_count clear fi done ######################################## echo "Bye!" <file_sep>/.monitor_tws/js_query_form.sh #!/bin/bash set -u #set -x ################################################### # # Show certain job_stream information # # Include JS_NAME JOB_NAME FIRST_NAME SECOND_NAME # SRC_OWNER SRC_NAME TGT_OWNER TGT_NAME # DESCRIPTION JOB_SYS # # And save them in the file named "sqlplus_output" # ################################################## if [ -f "./.secret/sqlplus_output" ]; then rm ./.secret/sqlplus_output fi put="$(cat /etc/hostname)" sqlplus $(cat ./.secret/.userid)@${put: -1}sid/$(cat ./.secret/.passwd) << EOF > ./.secret/sqlplus_output.tmp SET LINESIZE 100; SET PAGESIZE 30; SELECT '+++' || CHR(10) || 'JS_NAME' || CHR(9) || CHR(9) || ':' || JS_NAME || CHR(10) || 'JOB_NAME' || CHR(9) || ':' || JOBNAME || CHR(10) || 'FIRST_NAME' || CHR(9) || ':' || FIRST_NAME || CHR(10) || 'SECOND_NAME' || CHR(9) || ':' || SECOND_NAME || CHR(10) || 'SRC_OWNER' || CHR(9) || ':' || SRC_OWNER || CHR(10) || 'SRC_NAME' || CHR(9) || ':' || SRC_NAME || CHR(10) || 'TGT_OWNER' || CHR(9) || ':' || TGT_OWNER || CHR(10) || 'TGT_NAME' || CHR(9) || ':' || TGT_NAME || CHR(10) || 'DESCRIPTION' || CHR(9) || ':' || FILE_DESCRIPTION || CHR(10) || 'JOB_SYS' || CHR(9) || CHR(9) || ':' || JOBSYS || CHR(10) || '++' INFORMATION FROM ( SELECT a.NUM, a.JOBNAME, a.JS_NAME, a.JOBSYS, a.FIRST_NAME, a.SECOND_NAME, a.FILE_DESCRIPTION , a.SRC_OWNER, a.SRC_NAME , b.NAME TGT_NAME, b.OWNER TGT_OWNER FROM ( SELECT a.NUM, a.JOBNAME, a.JS_NAME, a.JOBSYS, a.FIRST_NAME, a.SECOND_NAME, a.FILE_DESCRIPTION , b.OWNER SRC_OWNER, b.NAME SRC_NAME FROM ( SELECT NUM, JOBNAME, JOBSYS, FILE_DESCRIPTION, JS_NAME, FIRST_NAME, SECOND_NAME FROM ODS_SYSTEM.RD_JOBINFO WHERE JS_NAME='$1') a LEFT JOIN ODS_SYSTEM.RD_JOBSRCINFO b ON a.JOBNAME=b.JOBNAME) a LEFT JOIN ODS_SYSTEM.RD_JOBTGTINFO b ON a.JOBNAME=b.JOBNAME); EXIT; EOF sed -n '/+++/,/++/p' ./.secret/sqlplus_output.tmp | sed -n '2,11'p >> ./.secret/sqlplus_output if [ -f "./.secret/sqlplus_output.tmp" ]; then rm ./.secret/sqlplus_output.tmp fi cat ./.secret/sqlplus_output <file_sep>/.monitor_tws/login_tws.sh #!/bin/bash set -u conman -username $(cat ./.secret/.tws_userid) -password $(cat ./.secret/.tws_passwd)
4f5e59c5d4e90ae1dfeb50ee33e6e4e246ba5738
[ "Python", "Shell" ]
9
Shell
uuboyscy/monitor
6e5c04acada5f9ec6bedbd9416a5e426eb3c77d1
2eb6fefc864ad1076bd942ebc298796b123d56f5
refs/heads/master
<file_sep><?php class ProductController extends BaseController { public function index() { $products = Product::all(); return View::make('admin.products.index')->with('products', $products); } public function store() { $title = Input::get('title'); $price = Input::get('price'); $description = Input::get('description'); $category = Input::get('category'); $product = new Product; $product->title = $title; $product->price = $price; $product->description = $description; $product->category_id = $category; if($product->save()) { return Redirect::to('admin/products')->with('message', 'Product successfully created'); } } public function create() { $categories = Category::all(); return View::make('admin.products.create')->with('categories', $categories); } public function edit($id) { $categories = Category::orderBy('name', 'asc')->get(); $product = Product::find($id); return View::make('admin.products.edit')->with(array('product' => $product, 'categories' => $categories)); } public function update($id) { $product = Product::find($id); $title = Input::get('title'); $price = Input::get('price'); $description = Input::get('description'); $category = Input::get('category'); $product->title = $title; $product->price = $price; $product->description = $description; $product->category_id = $category; if($product->save()) { return Redirect::to('admin/products')->with('message', 'Product successfully updated'); } } public function destroy($id) { $product = Product::find($id); if($product->delete()) { return Redirect::to('admin/products')->with('message', 'Product successfully deleted'); } } } <file_sep><?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the Closure to execute when that URI is requested. | */ Route::get('/', function() { $products = Product::all(); return View::make('products.index')->with('products', $products); }); Route::group(array('prefix' => 'admin'), function() { Route::get('/', function() { return View::make('admin.dashboard'); }); Route::resource('products', 'ProductController'); Route::resource('categories', 'CategoryController'); }); <file_sep><?php class CategoryController extends BaseController { public function index() { $categories = Category::all(); return View::make('admin.categories.index')->with('categories', $categories); } public function store() { $name = Input::get('name'); $description = Input::get('description'); $category = new Category; $category->name = $name; $category->description = $description; if($category->save()) { return Redirect::to('admin/categories')->with('message', 'Category successfully created'); } } public function create() { return View::make('admin.categories.create'); } public function edit($id) { $category = Category::find($id); return View::make('admin.categories.edit')->with('category', $category); } public function update($id) { $category = Category::find($id); $name = Input::get('name'); $description = Input::get('description'); $category->name = $name; $category->description = $description; if($category->save()) { return Redirect::to('admin/categories')->with('message', 'Category successfully updated'); } } public function destroy($id) { $category = Category::find($id); if($category->delete()) { return Redirect::to('admin/categories')->with('message', 'Category successfully deleted'); } } } <file_sep><?php class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Eloquent::unguard(); $this->call('CategoryTableSeeder'); $this->call('ProductTableSeeder'); } } class ProductTableSeeder extends Seeder { public function run() { DB::table('products')->delete(); Product::create(array( 'title' => 'Metallica T-Shirt', 'price' => 24.95, 'description' => 'Metallica artwork from the Master of Puppets albumn.', 'category_id' => 1, ) ); Product::create(array( 'title' => 'Iron Maiden T-Shirt', 'price' => 24.95, 'description' => 'Classic Iron Maiden design.', 'category_id' => 1, ) ); Product::create(array( 'title' => 'The Hobbit', 'price' => 66, 'description' => 'The Hobbit, or There and Back Again is a fantasy novel and by English author <NAME>.', 'category_id' => 2, ) ); Product::create(array( 'title' => 'Javascript: The Good Parts', 'price' => 123, 'description' => "Most programming languages contain good and bad parts, but JavaScript has more than its share of the bad, having been developed and released in a hurry before it could be refined. This authoritative book scrapes away these bad features to reveal a subset of JavaScript that's more reliable, readable, and maintainable than the language as a whole—a subset you can use to create truly extensible and efficient code.", 'category_id' => 2, ) ); } } class CategoryTableSeeder extends Seeder { public function run() { DB::table('categories')->delete(); Category::create(array( 'name' => 'Apparel', 'description' => 'Clothing for men & woman', ) ); Category::create(array( 'name' => 'Books', 'description' => "Everyone's favorite pasttime", ) ); } }<file_sep>## LaraCommerce A simple e-commerce manager built using Laravel PHP framework. The application currently has the ability to manage products and categories from the administrative area. This is a work in progress so I will be consistently adding new features & functionality. ## Installation 1. Clone this repository. 2. To set up dependencies, run `composer install && npm install`. 4. Run `gulp` to compile SCSS files & autoprefix CSS3 properties. 5. Create a database called `laracommerce`. 6. Run `php artisan migrate` & `php artisan db:seed` to add seed data.
550745bb5b99a8e0137367c807acceffa1fe7422
[ "Markdown", "PHP" ]
5
PHP
saraalfadil/LaraCommerce
4291a71f7401ac1afa06aa36a7928b8c116d778a
909bcd1f829d6d657e8e79c7df1a591f38596e6e
refs/heads/master
<file_sep>AOS.init(); /*const gridItems = document.querySelectorAll('.grid-item'); let gridItemClicked = false; gridItems.forEach(elem => { elem.addEventListener('click', (event) => { if(gridItemClicked == false){ elem.style.position = "absolute"; elem.style.left = "10%"; elem.style.top = event.screenY - 60 +"%"; elem.style.width = "80%"; elem.style.height = "80%"; gridItemClicked = true; } else{ elem.style.position = ""; elem.style.width = "100%"; elem.style.height = "100%"; gridItemClicked = false; } }) }) */
c75a9dc1232d34d214197a2ca202fe6efbac98ef
[ "JavaScript" ]
1
JavaScript
SzathRobi/stabofficial
12466fe68c1eef56a2cdb8f862b7deee62edf2dc
ee7fbfb6a0cc1e5bea485492b014acfef00421c5
refs/heads/main
<repo_name>FrazShabbir/Misc<file_sep>/speech.py from gtts import gTTS import os language = 'en' hello = input("Enter text to speech word") mytext=hello myobj = gTTS(text=mytext, lang=language, slow=True) myobj.save("voice.mp3") os.system("mpg321 mycomd.mp3") <file_sep>/sendsms.py from twilio.rest import Client #twillio API client=Client("AC5d5beb0fc0613ec610a58767032c1c1a","<KEY>") client.messages.create(to='+923342851998',from_='+12057970697',body="hello!")<file_sep>/Scraper/coronavirus.py import scrapy class CoronaSpider(scrapy.Spider): name = 'corona' start_urls = ['https://www.worldometers.info/coronavirus/country/pakistan/'] def parse(self, response): #data=response.css('.c5TXIP') name=response.css('div>h1::text').extract()[1] Pakistan_total=response.css('div.maincounter-number>span::text').extract()[0] Pakistan_deaths=response.css('div.maincounter-number>span::text').extract()[1] Pakistan_recover=response.css('div.maincounter-number>span::text').extract()[2] yield { 'Country':name, 'Pakistan Total cases ':Pakistan_total, 'Pakistan Total Deaths ':Pakistan_deaths, 'Pakistan Total Recovered ':Pakistan_recover } <file_sep>/Scraper/indeed.py import scrapy class indeedpk(scrapy.Spider): name = 'indeed' what = input("Enter Job title:") where = input("Enter destination:") link="https://pk.indeed.com/jobs?q="+what+"&l="+where start_urls = [link] def parse(self, response): onebyone='https://pk.indeed.com/viewjob?cmp=Vaival-Technologies&t=Website+Quality+Assurance&jk=7440a52b7c6594a3&q=html&vjs=3' url_country= onebyone yield scrapy.Request(url_country,callback=self.parse_api) def parse_api(self,response): job=response.css('div.jobsearch-JobInfoHeader-title-container>h1::text').extract() name=response.css('div#jobDescriptionText>ul>li::text').extract() yield { 'job':job, 'Country':name } <file_sep>/kmeans2.py import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score from sklearn.preprocessing import MinMaxScaler from sklearn.cluster import KMeans iris = pd.read_csv("iris.csv") x = iris.iloc[:, [0, 1, 2, 3]].values iris.info() iris[0:10] #Frequency distribution of species" iris_outcome = pd.crosstab(index=iris["species"], # Make a crosstab columns="count") # Name the count column iris_outcome iris_setosa=iris.loc[iris["species"]=="Iris-setosa"] iris_virginica=iris.loc[iris["species"]=="Iris-virginica"] iris_versicolor=iris.loc[iris["species"]=="Iris-versicolor"] sns.FacetGrid(iris,hue="species",size=3).map(sns.distplot,"petal_length").add_legend() sns.FacetGrid(iris,hue="species",size=3).map(sns.distplot,"petal_width").add_legend() sns.FacetGrid(iris,hue="species",size=3).map(sns.distplot,"sepal_length").add_legend() sns.boxplot(x="species",y="petal_length",data=iris) sns.set_style("whitegrid") sns.pairplot(iris,hue="species",size=3) wcss = [] for i in range(1, 11): kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0) kmeans.fit(x) wcss.append(kmeans.inertia_) kmeans = KMeans(n_clusters = 3, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0) y_kmeans = kmeans.fit_predict(x) #Visualising the clusters plt.scatter(x[y_kmeans == 0, 0], x[y_kmeans == 0, 1], s = 100, c = 'purple', label = 'Iris-setosa') plt.scatter(x[y_kmeans == 1, 0], x[y_kmeans == 1, 1], s = 100, c = 'orange', label = 'Iris-versicolour') plt.scatter(x[y_kmeans == 2, 0], x[y_kmeans == 2, 1], s = 100, c = 'green', label = 'Iris-virginica') #Plotting the centroids of the clusters plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:,1], s = 100, c = 'red', label = 'Centroids') plt.show()<file_sep>/Scraper/daraz.py import scrapy class DarazSpider(scrapy.Spider): name = 'daraz' start_urls = ['https://www.youtube.com/feed/trending'] def parse(self, response): name=response.xpath('//*[@id="video-title"]/yt-formatted-string/@href/text()').extract() yield{ 'name':name } <file_sep>/atm-project-GUI/Data/encrypt.py #for incoding of name def rot13(s): chars = "abcdefghijklmnopqrstuvwxyz" trans = chars[13:]+chars[:13] rot_char = lambda c: trans[chars.find(c)] if chars.find(c)>-1 else c return ''.join( rot_char(c) for c in s ) <file_sep>/atm-project-GUI/main.py ######################## # GUI-Author: <NAME>, <NAME> # Date: 27-03-2018 ######################### ######################### # importing Libraries ######################### # import tkinter as tk # Python 3: "t" lower-case from tkinter import * from tkinter import ttk,messagebox import tkinter, logging, os, csv from Data.data import data from Data.new_acc_class import NewAccount from Data.encrypt import rot13 ########################## #importing files ######################## def exit(): msg = messagebox.askquestion("CONFIRM","ARE YOU SURE YOU WANT TO EXIT?", icon='warning') if msg == "yes": root.deiconify() #makes the root window visible again window.destroy() logging.info('exiting window') else: logging.info('window still running') def new_account(event=None): def limitSize(*args): value = limit.get() if len(value) > 13: limit.set(value[:13]) def data_entry(Pin): filename = os.path.join('Data', 'userdata.csv') with open(filename, 'a') as data_file: fathername, name = rot13(user.father_name.lower()), rot13(user.fullname.lower()) new = [user.username, user.account_no, user.acc_type, name, fathername, user.cnic, Pin, user.balance, 'NEW'] csv.writer(data_file).writerow(new) logging.debug('writing data in file') data_file.close() logging.info('data written successfully in file : {}'.format('userdata.csv')) def next_window(): window.title("PIN BOX") def finish(): Pin, V_Pin = pin.get(), v_pin.get() if (Pin == V_Pin) and (len(Pin) == 4): logging.info('pin matched successfully') window.bell() logging.info('account no generated successfully') messagebox.showinfo('Confirmation', "Dear {}! Your account is created successfully. Your account number is {}.".format(user.fullname, user.account_no)) data_entry(Pin) window.destroy() root.deiconify() return else: window.bell() logging.warning('pin did not match') messagebox.showwarning('Failed' ,"Your PIN did not match!, Try again!") #----First Frame------ Frame_2 = Frame(window) Frame_2.grid() #------empty label---------- Label(Frame_2, text='CREATE NEW PIN', font=("Microsoft Himalaya", 12, "bold")).grid(row=0, rowspan=2, column=1, columnspan=2, sticky=EW) Label(Frame_2).grid(row=2, sticky=EW) Label(Frame_2).grid(row=3, sticky=EW) Label(Frame_2).grid(row=4, sticky=EW) #------label for PIN------- Label(Frame_2, text="4-Digit PIN : ", font="none 12 bold").grid(row=5, column=0, sticky=W) Label(Frame_2, text="Verify PIN : ", font="none 12 bold").grid(row=6, column=0, sticky=W) def limitPin(*args): value = pinLimit.get() if len(value) > 4: pinLimit.set(value[:4]) pinLimit = StringVar() pinLimit.trace('w', limitPin) def limitVerPin(*arg): value = verPinLimit.get() if len(value) > 4: verPinLimit.set(value[:4]) verPinLimit = StringVar() verPinLimit.trace('w', limitVerPin) #------entry for PIN------ logging.debug('creating entries...') bullet = "\u2022" pin = Entry(Frame_2, bg="white", width=20, font="12", show=bullet, textvariable=pinLimit) pin.grid(row=5, column=2, sticky=W) v_pin = Entry(Frame_2, bg="white", width=20, font="12", show=bullet, textvariable=verPinLimit) v_pin.grid(row=6, column=2, sticky=W) #------empty label---------- Label(Frame_2).grid(row=7, sticky=EW) Label(Frame_2).grid(row=8, sticky=EW) Label(Frame_2).grid(row=9, sticky=EW) Label(Frame_2).grid(row=10, sticky=EW) Label(Frame_2).grid(row=11, sticky=EW) Label(Frame_2).grid(row=12, sticky=EW) Label(Frame_2).grid(row=13, sticky=EW) Label(Frame_2).grid(row=14, sticky=EW) logging.debug('creating buttons....') #----button for exit----- finish_bt = Button(Frame_2, text="FINISH", bg="pale green", fg="black", font="Jokerman 12", relief=GROOVE, padx=12, bd=2, command=finish) finish_bt.grid(row=15, column=3, sticky=W+S) def click(event=None): first, last, middle, father, CNIC = f_name.get(), l_name.get(), m_name.get(), ft_name.get(), cnic.get() global user Username, Acc_type = username.get(), acc_type.get() if Acc_type == 1: logging.info('user selected account type as Gold') Acc_type = 'Gold' else: logging.info('user selected account type as Silver') Acc_type = 'Silver' #sending data to NewAccount class user = NewAccount(first, last, father, CNIC, Username, Acc_type, middle) Full_name, CNIC = user.full_name(), user.cnic_check() if not Full_name: window.bell() logging.warn('user entered invalid name') messagebox.showwarning('Failed', "Invalid Name!") elif not CNIC: window.bell() logging.warn('user entered invalid CNIC : {}'.format(CNIC)) messagebox.showwarning('Failed', "Invalid CNIC Number!") elif (Username == " ") or (Username.lower() == first.lower()) or (Username.lower() == last.lower()) or (Username.lower() == father.lower()): window.bell() logging.warn('user entered invalid username : {}'.format(Username)) messagebox.showwarning('Failed', "Invalid username : {}. Please enter a unique username.".format(Username)) else: user.get_account_no() logging.info('user entered correct information and now prompting user for pin...') Frame_1.destroy() next_window() global window window = Toplevel(root) root.withdraw() window.title("NEW ACCOUNT") w = 450 h = 400 window.protocol('WM_DELETE_WINDOW',exit) # if windows default cross button is pressed ws = window.winfo_screenwidth() hs = window.winfo_screenheight() x_axis = (ws/2) - (w/2) y_axis = (hs/2) - (h/2) window.geometry('%dx%d+%d+%d' % (w, h, x_axis, y_axis)) window.resizable(width=False, height=False) icon = os.path.join('Data', 'icon.ico') try: window.iconbitmap(icon) imgicon = PhotoImage(file=icon) window.tk.call('wm', 'iconphoto', window._w, imgicon) except Exception as err: logging.warning(err) icon = os.path.join('Data', 'icon.gif') imgicon = PhotoImage(file=icon) window.tk.call('wm', 'iconphoto', window._w, imgicon) finally: pass #-----creating menus----- my_menu = Menu(window) window.config(menu=my_menu) subMenu = Menu(my_menu) my_menu.add_cascade(label="File", menu=subMenu) subMenu.add_command(label='Exit', command=window.destroy) helpMenu = Menu(my_menu) my_menu.add_cascade(label="Help", menu=helpMenu) helpMenu.add_command(label='About ATM') helpMenu.add_separator() helpMenu.add_command(label='help create account') #----First Frame------ Frame_1 = Frame(window) Frame_1.grid() #------empty label---------- Label(Frame_1, text='CREATE NEW ACCOUNT', font=("Microsoft Himalaya", 12, "bold")).grid(row=0, column=2, sticky=EW) #----label for name------ Label(Frame_1, text="First Name : ", font="none 12 bold").grid(row=1, column=0, sticky=W) Label(Frame_1, text="Middle Name : ", font="none 12 bold").grid(row=2, column=0, sticky=W) Label(Frame_1, text="(optional)", font="none 12 bold").grid(row=2, column=3, sticky=W) Label(Frame_1, text="Last Name : ", font="none 12 bold").grid(row=3, column=0, sticky=W) #------empty label---------- Label(Frame_1).grid(row=4, sticky=EW) #---label for father name----- Label(Frame_1, text="Father's Name : ", font="none 12 bold").grid(row=5, column=0, sticky=W) #------empty label---------- Label(Frame_1).grid(row=6, sticky=EW) #---label for cnic----- l_cnic = Label(Frame_1, text="13-Digit CNIC : ", font="none 12 bold").grid(row=7, column=0, sticky=W) Label(Frame_1, text="without (-)", font="none 12 bold").grid(row=7, column=3, sticky=W) #------empty label---------- Label(Frame_1).grid(row=8, sticky=EW) #-----label for username------ Label(Frame_1, text="Username : ", font="none 12 bold").grid(row=9, column=0, sticky=W) #------empty label---------- Label(Frame_1).grid(row=10, sticky=EW) #-----label for account type------ Label(Frame_1, text="Account Type : ", font="none 12 bold").grid(row=11, column=0, sticky=W) #-----entries for name----- logging.debug('creating entries....') f_name = Entry(Frame_1, bg="white", width=20, font="none 12") f_name.grid(row=1, column=2, sticky=W) m_name = Entry(Frame_1, bg="white", width=20, font="none 12") m_name.grid(row=2, column=2, sticky=W) l_name = Entry(Frame_1, bg="white", width=20, font="none 12") l_name.grid(row=3, column=2, sticky=W) ft_name = Entry(Frame_1, bg="white", width=20, font="none 12") ft_name.grid(row=5, column=2, sticky=W) limit = StringVar() limit.trace('w', limitSize) #---entry for cnic---- cnic = Entry(Frame_1, validate="key", bg="white", width=16, font="12", textvariable=limit) cnic.grid(row=7, column=2, sticky=W) #-----entry for username----- username = Entry(Frame_1, bg="white", width=20, font="none 12") username.grid(row=9, column=2, sticky=W) #-----Radiobutton for account type------- logging.debug('creating buttons ....') acc_type = IntVar() Radiobutton(Frame_1, text="GOLD", variable=acc_type, value=1, font="none 10 bold", bg="gold").grid(row=11, column=2, sticky=W) Radiobutton(Frame_1, text="SILVER", variable=acc_type, value=2, font="none 10 bold", bg="silver").grid(row=11, column=2, sticky=E) #------empty label---------- Label(Frame_1).grid(row=12, sticky=EW) Label(Frame_1).grid(row=13, sticky=EW) #----button for next----- next_bt = Button(Frame_1, text="NEXT", bg="pale green", fg="black", font="Jokerman 12", relief=GROOVE, padx=12, bd=2, command=click) next_bt.grid(row=14, column=2,sticky=E) #----button for exit----- exit_bt = Button(Frame_1, text="EXIT", bg='light grey', fg='black', font="Jokerman 12", relief=GROOVE, padx=12, bd=2, command=exit) exit_bt.grid(row=14, column=3, sticky=W) #------empty label---------- Label(Frame_1).grid(row=15, sticky=EW) try: Path = os.path.join('temp', 'info.log') logging.basicConfig(format='[ATM]:[%(asctime)s]:%(levelname)s:%(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG, filename=Path) except (IOError or FileNotFoundError): os.mkdir('temp') Path = os.path.join('temp', 'info.log') logging.basicConfig(format='[ATM]:[%(asctime)s]:%(levelname)s:%(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG, filename=Path) def login(): logging.debug('user selected login') d = data() Username, Pin = username.get(), pin.get() if Username in d.keys(): logging.debug('username match found in data with name : {}'.format(d[Username][2])) if Pin == d[Username][5]: logging.debug('user entered correct pin') username.delete(0, END) pin.delete(0, END) messagebox.showinfo('Successfull', 'Welcome {} to atm service.'.format((d[Username][2]).upper())) else: pin.delete(0, END) messagebox.showwarning('Unsuccessfull', 'Invalid PIN!') logging.warning('user entered incorrect pin') else: username.delete(0, END) pin.delete(0, END) logging.warning('no match found with username:{}'.format(Username)) messagebox.showwarning('Unsuccessfull', 'Invalid Username! No match found') def windows_size(): root.update() # to get runtime size logging.info('setting width={} and height={}'.format(root.winfo_width(), root.winfo_height())) root = Tk() root.title("ATM Project") icon = os.path.join('Data', 'icon.ico') w, h = 500, 400 #to open window in the centre of screen ws = root.winfo_screenwidth() hs = root.winfo_screenheight() x_axis = (ws/2) - (w/2) y_axis = (hs/2) - (h/2) root.geometry('%dx%d+%d+%d' % (w, h, x_axis, y_axis)) # disable resizing the GUI root.resizable(0,0) try: root.iconbitmap(icon) imgicon = PhotoImage(file=icon) root.tk.call('wm', 'iconphoto', root._w, imgicon) except Exception as err: logging.warning(err) icon = os.path.join('Data', 'icon.gif') imgicon = PhotoImage(file=icon) root.tk.call('wm', 'iconphoto', root._w, imgicon) finally: pass # Menu Bar menuBar = Menu() root.config(menu = menuBar) # Menu Items filemenu = Menu(menuBar, tearoff = 0) filemenu.add_command(label = "New", command=new_account) filemenu.add_separator() filemenu.add_command(label = "Exit", command = quit) #Calling the quit function menuBar.add_cascade(label = "File", menu = filemenu) # Add another Menu to the Menu Bar and an item helpMenu = Menu(menuBar, tearoff=0) helpMenu.add_command(label="About") menuBar.add_cascade(label="Help", menu=helpMenu) # Tab Control / Notebook introduced here ------------------------ tabControl = ttk.Notebook(root) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab tabControl.add(tab1, text='My ATM') # Add the tab tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Instructions') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # --------------------------------------------------------------- instr = ttk.LabelFrame(tab2, text='This Tab will be containing all the Instruction we are going to have for our program!') # using the tkinter grid layout manager instr.grid(column=0, row=0, padx=8, pady=4) ttk.Label(instr, text="All The Instructions are as follows: \n 1. If you are reading this then it means that you have downloaded this file. \n 2. Install Python3 on your system if you haven't already. \n 3. Install tkinter module in order to run the GUI of this program \n 4. If you are having any issues than please report it so we can fix it!").grid(column=0, row=0, sticky='W') ttk.Label(tab1,text="Enter Username: ", font=("Palatino Linotype", 12, "bold")).grid(row=0, sticky="W") username = Entry(tab1, font='none') username.grid(row=0, column=2, padx=1, pady=2, ipadx=2, ipady=2) bullet = "\u2022" ttk.Label(tab1, text="Enter PIN: ", font=("Palatino Linotype", 12, "bold")).grid(row=1, sticky="W") def LimitPin(*arg): value = PinLimit.get() if len(value) > 4: PinLimit.set(value[:4]) PinLimit = StringVar() PinLimit.trace('w', LimitPin) pin = Entry(tab1, show=bullet, font='none', textvariable=PinLimit) pin.grid(row=1, column=2, padx=1, pady=2, ipadx=2, ipady=2) # --------------------------------------------------------------- #Add buttons--------------------------- Button(root, text='LOGIN', bg='deep sky blue', font='Jokerman 12', command=login).pack(side='top', padx=4, pady=4, fill='both') Button(root, text='CREATE NEW ACCOUNT', bg='pale green', font='Jokerman 12', command=new_account).pack(padx=4, pady=4, fill='both') #Copyright label----------------------------------------------------- cp = Label(root, text="FRAZ SHABBIR Project {} 2020".format(chr(0xa9)), relief=SUNKEN, anchor=W, bg='LightCyan2') cp.pack(fill=X) root.mainloop() <file_sep>/googlesearch.py from gtts import gTTS import os import speech_recognition as sr r = sr.Recognizer() with sr.Microphone() as source: # read the audio data from the default microphone audio_data = r.record(source, duration=15) print("Recognizing...") # convert speech to text text = r.recognize_google(audio_data) print(text) language = 'en' mytext=text myobj = gTTS(text=mytext, lang=language, slow=True) myobj.save("mycomd.mp3") os.system("mpg321 mycomd.mp3") from selenium import webdriver driver = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver") driver.get("https://google.com")<file_sep>/Scraper/indeed2_py.py import scrapy class Indeed2(scrapy.Spider): name = 'indeed2' what = input("Enter Job title:") where = input("Enter destination:") link="https://pk.indeed.com/jobs?q="+what+"&l="+where start_urls = [link] def parse(self, response): for i in range (1,10): name = response.css('h2.title::text').get() onebyone= response.css('h2.title>a::attr(href)').get() baserul='https://pk.indeed.com' url_country=baserul+onebyone[] job=response.css('div#vjs-desc>ul>li::text').getall() yield { 'Country':job, 'name':name } <file_sep>/atm-project-GUI/Data/acc_no_gen.py from random import randint, randrange from Data.data import data def account_no_gen(user_name): d = data() alphabets = 'abcdefghijklmnopqrstuvwxyz' acc_no = '' acc_no += str(len(d.keys()) + 10) for alpha in user_name: if (len(acc_no) < 12): if alpha in alphabets: index = alphabets.rfind(alpha) acc_no += str(index + 1) else: acc_no += '0' else: break if len(acc_no) > 12: final_acc_no = '' for index in acc_no: if len(final_acc_no) < 12: final_acc_no += index acc_no = final_acc_no return acc_no if len(acc_no) < 12: remain_index = 12 - len(acc_no) for index in range(remain_index): acc_no += str(randint(0,9)) return acc_no else: return acc_no def code(): a = 'qwertyuiopasdfghjklzxcvbnm' conf_code = '' for i in range(3): conf_code += str(a[randrange(9)])+str(randrange(9)) return conf_code <file_sep>/iprotate.py import requests from bs4 import BeautifulSoup from random import choice def get_proxy(): url="https://www.sslproxies.org/" r=requests.get(url) soup = BeautifulSoup(r.content,'html5lib') return {'https':choice(list(map(lambda x:x[0]+':'+x[1],list(zip(map(lambda x:x.text,soup.findAll('td')[::8]),map(lambda x:x.text,soup.findAll('td')[1::8]))))))} def proxy_request(request_type , url , **kwargs): while 1: try: proxy =get_proxy() print("Using proxy :{}".format(proxy)) r=requests.request(request_type,url,proxies=proxy,timeout=5,**kwargs) break except: pass return r r= proxy_request('get' , "https://www.youtube.com") print('hello')<file_sep>/atm-project-GUI/Data/new_acc_class.py import logging from Data.acc_no_gen import account_no_gen class NewAccount: balance = 0.00 def __init__(self, first_name, last_name, father_name, cnic, username, acc_type, middle_name = None): logging.debug("creating a new account") self.first_name = first_name self.last_name = last_name self.cnic = cnic self.father_name = father_name self.username = username self.acc_type = acc_type self.middle_name = middle_name def full_name(self): logging.info("checking first name...") if self.first_name.isalpha(): logging.info("checking last name...") if self.last_name.isalpha(): if self.middle_name: logging.debug("checking middle name {}".format(self.middle_name)) if self.middle_name.isalpha(): logging.debug("name is cheked, returning full name") self.fullname = self.first_name+" "+self.middle_name+" "+self.last_name return True else: logging.warning("middle name invalid : '{}'".format(self.middle_name)) return False else: logging.info("return full name with no middle name") self.fullname = self.first_name+" "+self.last_name return True else: logging.warning("last name invalid : '{}'".format(self.last_name)) return False else: logging.warning("first name invalid : '{}'".format(self.first_name)) return False def get_account_no(self): name = self.fullname if name: logging.info("creating account number using name :{}".format(name)) self.account_no = account_no_gen(name) return True else: logging.info('account number could not be created...') return False def cnic_check(self): logging.debug("checking CNIC : {}".format(self.cnic)) if (len(self.cnic) == 13) and (self.cnic.isdigit()): logging.info('CNIC checked...') return ("{}-{}-{}".format(self.cnic[0:5], self.cnic[5:12], self.cnic[12])) else: logging.warning("invalid CNIC : {}".format(self.cnic)) return False <file_sep>/test.py from selenium import webdriver from selenium.webdriver.common.keys import Keys #FORM ENABLEING KEY PRESSES from time import sleep from bs4 import BeautifulSoup import requests def gsearch(): driver = webdriver.Chrome("/usr/local/share/chromedriver") what = input("Enter Job title:") where = input("Enter destination:") link="https://pk.indeed.com/jobs?q="+what+"&l="+where driver.get(link) next1=driver.find_element_by_css_selector("h2.title") next1.click() source = requests.get(link).text soup = BeautifulSoup(source,'lxml') ass = soup.find('li').text # for tag in soup.find_all("div",{"id":"vjs-desc"}): # print("{0}: {1}".format(tag.name, tag.text)) headline = ass print(headline) sleep(4000) gsearch() # fname=driver.find_element_by_xpath('//*[@id="text-input-what"]') # fname.send_keys(what) # fname=driver.find_element_by_xpath('//*[@id="text-input-where"]') # fname.send_keys(where) # next1=driver.find_element_by_xpath('//*[@id="whatWhereFormId"]/div[3]/button') # next1.click()<file_sep>/atm-project-GUI/Data/data.py from Data.encrypt import rot13 import os, csv, logging def data(): d = {} new = ['USERNAME', 'ACCOUNT NUMBER', 'ACCOUNT TYPE', 'NAME', '<NAME>', 'CNIC', 'PIN', 'BALANCE', 'LAST ACTIVE SESSION'] filename = os.path.join('Data', 'userdata.csv') #file size shorter than 13 bit with open(filename, "a") as ap: if (os.path.getsize(filename)) <= 0: logging.info("creating a new file as '{}' in dir '{}' ".format(filename, os.getcwd())) wr = csv.writer(ap) wr.writerow(new) ap.close() return d else: with open(filename, "r") as rd: r = csv.reader(rd) for indiv_user_info in r: if (indiv_user_info == new) or (indiv_user_info == []): continue else: try: #rot13() function is called for decoding indiv_user_info[3] = rot13(indiv_user_info[3]) indiv_user_info[7] = float(indiv_user_info[7]) d[indiv_user_info[0]] = indiv_user_info[1],indiv_user_info[2],indiv_user_info[3],indiv_user_info[4],indiv_user_info[5],indiv_user_info[6],indiv_user_info[7],indiv_user_info[8],indiv_user_info[9] except IndexError: d[indiv_user_info[0]] = indiv_user_info[1],indiv_user_info[2],indiv_user_info[3],indiv_user_info[4],indiv_user_info[5],indiv_user_info[6],indiv_user_info[7],indiv_user_info[8],"None" return d <file_sep>/Scraper/fraz.py import scrapy class frazSpider(scrapy.Spider): name = 'fraz' what = input("Enter Job title:") where = input("Enter destination:") link="https://pk.indeed.com/jobs?q="+what+"&l="+where start_urls = [link] def parse(self, response): abc =response.css('.jobsearch-SerpJobCard') for links in abc: onebyone=links.css('h2.title>a::attr(href)').getall() baserul='https://pk.indeed.com' url_country=baserul+onebyone yield scrapy.Request(url_country,callback=self.parse_api) def parse_api(self,response): name=response.css('div#vjs-desc>ul>li::text').getall() yield { 'Country':name, } <file_sep>/hello.py print('hello') d=4 b=7 g=2 c=d+b print(c) <file_sep>/facebook.py from selenium import webdriver from selenium.webdriver.common.keys import Keys #FORM ENABLEING KEY PRESSES from selenium.webdriver.chrome.options import Options from time import sleep from selenium.webdriver.common.action_chains import ActionChains # Chrome drivers driver = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver") #CODE FOR INCOGNITO MODE chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--incognito") driver = webdriver.Chrome(chrome_options=chrome_options) #ACTUAL OPENING LINK e=driver.get('https://web.whatsapp.com/') email=driver.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]') email.send_keys('<EMAIL>') #pass1=driver.find_element_by_xpath('//*[@id="pass"]') #pass1.send_keys('----') #submit=driver.find_element_by_xpath('//*[@id="pane-side"]/div[1]/div/div/div[1]/div/div/div[2]/div[1]/div[1]') email.send_keys(Keys.ENTER) #driver.close() <file_sep>/aprior.py import numpy as np import matplotlib.pyplot as plt import pandas as pd from apyori import apriori store_data = pd.read_csv('D:\\Datasets\\store_data.csv') #Importing Dataset from system store_data.head() # to check the header store_data = pd.read_csv('D:\\Datasets\\store_data.csv', header=None) #keeping header as None association_rules = apriori(records, min_support=0.0045, min_confidence=0.2, min_lift=3, min_length=2) association_results = list(association_rules) print(len(association_rules)) #to check the Total Number of Rules mined print(association_rules[0]) #to print the first item the association_rules list to see the first rule for item in association_rules: #to display the rule, the support, the confidence, and lift for each rule in a more clear way: # first index of the inner list # Contains base item and add item pair = item[0] items = [x for x in pair] print("Rule: " + items[0] + " -> " + items[1]) #second index of the inner list print("Support: " + str(item[1])) #third index of the list located at 0th #of the third index of the inner list print("Confidence: " + str(item[2][0][2])) print("Lift: " + str(item[2][0][3]))<file_sep>/scrap.py from selenium import webdriver from bs4 import BeautifulSoup import pandas as pd driver = webdriver.Chrome("/usr/local/share/chromedriver") # Daraz Scraper Still not working chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--incognito") driver = webdriver.Chrome(options=chrome_options) products=[] #List to store name of the products prices=[] #List to store price of the products ratings=[] #List to store rating of the products driver.get("https://www.daraz.pk/smartphones/?spm=a2a0e.home.cate_1.1.35e34937FAeKl5") content = driver.page_source soup = BeautifulSoup(content, 'html5lib') for a in soup.findAll('a',href=True, attrs={'class':'c3e8SH'}): name=a.find('div', attrs={'class':'c16H9d'}) price=a.find('div', attrs={'class':'c13VH6'}) rating=a.find('div', attrs={'class':'c15YQ9'}) products.append(name.text) prices.append(price.text) ratings.append(rating.text) df = pd.DataFrame({'Product Name':products,'Price':prices,'Rating':ratings}) df.to_csv('products.csv', index=False, encoding='utf-8') driver.close() # Import scrapy import scrapy # Import the CrawlerProcess: for running the spider from scrapy.crawler import CrawlerProcess # Create the Spider class class DC_Chapter_Spider(scrapy.Spider): name = "dc_chapter_spider" # start_requests method def start_requests(self): yield scrapy.Request(url = url_short, callback = self.parse_front) # First parsing method def parse_front(self, response): course_blocks = response.css('div.course-block') course_links = course_blocks.xpath('./a/@href') links_to_follow = course_links.extract() for url in links_to_follow: yield response.follow(url = url, callback = self.parse_pages) # Second parsing method def parse_pages(self, response): crs_title = response.xpath('//h1[contains(@class,"title")]/text()') crs_title_ext = crs_title.extract_first().strip() ch_titles = response.css('h4.chapter__title::text') ch_titles_ext = [t.strip() for t in ch_titles.extract()] dc_dict[ crs_title_ext ] = ch_titles_ext # Initialize the dictionary **outside** of the Spider class dc_dict = dict() # Run the Spider process = CrawlerProcess() process.crawl(DC_Chapter_Spider) process.start() # Print a preview of courses previewCourses(dc_dict) # Import scrapy import scrapy # Import the CrawlerProcess from scrapy.crawler import CrawlerProcess # Create the Spider class class YourSpider(scrapy.Spider): name = 'yourspider' # start_requests method def start_requests( self ): yield scrapy.Request(url = url_short, callback=self.parse) def parse(self, response): # My version of the parser you wrote in the previous part crs_titles = response.xpath('//h4[contains(@class,"block__title")]/text()').extract() crs_descrs = response.xpath('//p[contains(@class,"block__description")]/text()').extract() for crs_title, crs_descr in zip( crs_titles, crs_descrs ): dc_dict[crs_title] = crs_descr # Initialize the dictionary **outside** of the Spider class dc_dict = dict() # Run the Spider process = CrawlerProcess() process.crawl(YourSpider) process.start() # Print a preview of courses previewCourses(dc_dict)<file_sep>/Scraper/worldometer.py import scrapy class WorldometerSpider(scrapy.Spider): name = 'corona' start_urls = ['https://www.worldometers.info/coronavirus/#countries'] def parse(self, response): for i in range(0 ,215): onebyone=response.xpath('//*[@id="main_table_countries_today"]/tbody/tr/td/a[@class="mt_a"]/@href').extract()[i] baserul='https://www.worldometers.info/coronavirus/' url_country=baserul+onebyone yield scrapy.Request(url_country,callback=self.parse_api) def parse_api(self,response): name=response.css('div>h1::text').extract()[1] all_total=response.css('div.maincounter-number>span::text').extract()[0] all_deaths=response.css('div.maincounter-number>span::text').extract()[1] all_recover=response.css('div.maincounter-number>span::text').extract()[2] yield { 'Country':name, 'Country Total cases ':all_total, 'Country Total Deaths ':all_deaths, 'Country Total Recovered ':all_recover } <file_sep>/Scraper/indeed3.py import scrapy class indeedpk(scrapy.Spider): name = 'indeed' what = input("Enter Job title:") where = input("Enter destination:") link="https://pk.indeed.com/jobs?q="+what+"&l="+where start_urls = [link] def parse(self, response): links = response.css('div.jobsearch-SerpJobCard') for link in links: name = response.css('h2.title::text').get() onebyone= link.css('h2.title>a::attr(href)').get() baserul='https://pk.indeed.com' url_country=baserul+onebyone yield scrapy.Request(url_country,callback=self.parse_api) def parse_api(self,response): job=response.css('div#vjs-desc>ul>li::text').getall() job3=response.css('div#jobDescriptionText>ul>li::text').getall() job2=response.css('div>p::text').getall() name = response.css('h1::text').get() yield { 'name':name, 'Job title':job, 'Requirements':job3, 'Text':job2, } <file_sep>/pillow.py from PIL import Image img1 = Image.open(r"Source_Image_path") # The values used to crop the original image (will form a bbox) x1, y1, x2, y2 = 10, 10, 400, 400 # The angle at which the cropped Image must be rotated angle = 50 # cropping the original image img = img1.crop((x1, y1, x2, y2)) # Firstly converting the Image mode to RGBA, and then rotating it img = img.convert("RGBA").rotate(angle, resample=Image.BICUBIC) # calibrating the bbox for the beginning and end position of the cropped image in the original image # i.e the cropped image should lie in the center of the original image x1 = int(.5 * img1.size[0]) - int(.5 * img.size[0]) y1 = int(.5 * img1.size[1]) - int(.5 * img.size[1]) x2 = int(.5 * img1.size[0]) + int(.5 * img.size[0]) y2 = int(.5 * img1.size[1]) + int(.5 * img.size[1]) # pasting the cropped image over the original image, guided by the transparency mask of cropped image img1.paste(img, box=(x1, y1, x2, y2), mask=img) # converting the final image into its original color mode, and then saving it img1.convert(img1.mode).save("Destination_path") <file_sep>/proxy_rotation.py """# -*- coding: utf-8 -*- """ """ import requests from bs4 import BeautifulSoup from random import choice def get_proxy(): url="https://www.sslproxies.org/" r=requests.get(url) soup = BeautifulSoup(r.content,'html5lib') return {'https':choice(list(map(lambda x:x[0]+':'+x[1],list(zip(map(lambda x:x.text,soup.findAll('td')[::8]),map(lambda x:x.text,soup.findAll('td')[1::8]))))))} get_proxy() def proxy_request(request_type , url , **kwargs): while 1: try: proxy =get_proxy() print("Using proxy :{}".format(proxy)) r=requests.request(request_type,url,proxies=proxy,timeout=5,**kwargs) break except: pass return r r= proxy_request('get' , "https://youtube.com") print('hello') print(r) """ from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0 not using PROXY = "12.345.678.910:8080" chrome_options = WebDriverWait.ChromeOptions() chrome_options.add_argument('--proxy-server=%s' % PROXY) chrome = webdriver.Chrome(chrome_options=chrome_options) chrome.get("https://www.google.com")
540c978a1b4f05bf5729aef49d471db05e9264f7
[ "Python" ]
24
Python
FrazShabbir/Misc
9ec82f2aa0e777df805f59017f4a24810ec7a1b5
4cfc242663fe50c90b1d69ce425c253b7466584b
refs/heads/master
<repo_name>QIICR/TCIABrowser<file_sep>/TCIABrowser/Testing/Python/CMakeLists.txt slicer_add_python_unittest(SCRIPT TCIABrowserModuleAPIV1Test.py ) slicer_add_python_unittest(SCRIPT TCIABrowserModuleAPIV3Test.py ) <file_sep>/TCIABrowser/Testing/Python/TCIABrowserModuleAPIV3Test.py import qt, json, os, zipfile,dicom import unittest import slicer import TCIABrowserLib from Helper import * class TCIABrowserModuleAPIV3Test(unittest.TestCase): def testAPIV3(self): helper = Helper() print 'Started API v3 Test...' helper.delayDisplay('API V3 Test Started') TCIAClient = TCIABrowserLib.TCIAClient() self.assertTrue(helper.downloadSeries(TCIAClient)) helper.delayDisplay('API V3 Test Passed') <file_sep>/TCIABrowser/TCIABrowser.py from __future__ import division import codecs import csv import json import logging import os.path import pickle import string import time import unittest import webbrowser import xml.etree.ElementTree as ET import zipfile from random import randint import DICOM import pydicom import os import sys import urllib from itertools import chain from __main__ import vtk, qt, ctk, slicer from TCIABrowserLib import TCIAClient from slicer.ScriptedLoadableModule import * # # TCIABrowser # class TCIABrowser(ScriptedLoadableModule): def __init__(self, parent): parent.title = "TCIA Browser" parent.categories = ["Informatics"] parent.dependencies = [] parent.contributors = ["<NAME> (SPL, BWH), <NAME> (SPL, BWH), <NAME> (GU), <NAME> (FNLCR)"] parent.helpText = """ Connect to <a href=\"https://cancerimagingarchive.net">The Cancer Imaging Archive</a> and get a list of all available collections. After choosing a collection, the patients table will be populated. Click on a patient and the studies for the patient will be presented. Do the same for studies. Finally choose a series from the series table and download the images from the server by pressing the "Download and Load" button. See the <a href=\"https://github.com/QIICR/TCIABrowser/blob/master/Documentation.md"> documentation</a> for more information.""" parent.acknowledgementText = """ <img src=':Logos/QIICR.png'><br><br> Supported by NIH U24 CA180918 (PIs Kikinis and Fedorov).<br><br> This project has been funded in whole or in part with Federal funds from the National Cancer Institute, National Institutes of Health, under Contract No. 75N91019D00024. The content of this publication does not necessarily reflect the views or policies of the Department of Health and Human Services, nor does mention of trade names, commercial products, or organizations imply endorsement by the U.S. Government. """ self.parent = parent # Add this test to the SelfTest module's list for discovery when the module # is created. Since this module may be discovered before SelfTests itself, # create the list if it doesn't already exist. try: slicer.selfTests except AttributeError: slicer.selfTests = {} slicer.selfTests['TCIABrowser'] = self.runTest def runTest(self): tester = TCIABrowserTest() tester.runTest() # # browserWidget Initialization # Defines size and position # class browserWindow(qt.QWidget): def __init__(self): super().__init__() def closeEvent(self, event): settings = qt.QSettings() if settings.value("loginStatus"): settings.setValue("browserWidgetGeometry", qt.QRect(self.pos, self.size)) event.accept() # # qTCIABrowserWidget # class TCIABrowserWidget(ScriptedLoadableModuleWidget): def __init__(self, parent=None): self.loadToScene = False # self.browserWidget = qt.QWidget() self.browserWidget = browserWindow() self.browserWidget.setWindowTitle('TCIA Browser') self.initialConnection = False self.seriesTableRowCount = 0 self.studiesTableRowCount = 0 self.downloadProgressBars = {} self.downloadProgressLabels = {} self.selectedSeriesNicknamesDic = {} self.downloadQueue = {} self.seriesRowNumber = {} self.imagesToDownloadCount = 0 self.downloadProgressBarWidgets = [] self.settings = qt.QSettings() self.settings.setValue("loginStatus", False) self.settings.setValue("browserWidgetGeometry", "") item = qt.QStandardItem() # Put the files downloaded from TCIA in the DICOM database folder by default. # This makes downloaded files relocatable along with the DICOM database in # recent Slicer versions. databaseDirectory = slicer.dicomDatabase.databaseDirectory self.storagePath = self.settings.value("customStoragePath") if self.settings.contains("customStoragePath") else databaseDirectory + "/TCIALocal/" if not os.path.exists(self.storagePath): os.makedirs(self.storagePath) if not self.settings.contains("defaultStoragePath"): self.settings.setValue("defaultStoragePath", (databaseDirectory + "/TCIALocal/")) self.cachePath = slicer.dicomDatabase.databaseDirectory + "/TCIAServerResponseCache/" # Gets a list of series UIDs from the DICOM database self.previouslyDownloadedSeries = set([slicer.dicomDatabase.seriesForFile(x) for x in slicer.dicomDatabase.allFiles()]) if not os.path.exists(self.cachePath): os.makedirs(self.cachePath) self.useCacheFlag = False if not parent: self.parent = slicer.qMRMLWidget() self.parent.setLayout(qt.QVBoxLayout()) self.parent.setMRMLScene(slicer.mrmlScene) else: self.parent = parent self.layout = self.parent.layout() if not parent: self.setup() self.parent.show() def enter(self): pass def setup(self): # Instantiate and connect widgets ... if 'TCIABrowser' in slicer.util.moduleNames(): self.modulePath = slicer.modules.tciabrowser.path.replace("TCIABrowser.py", "") else: self.modulePath = '.' self.reportIcon = qt.QIcon(self.modulePath + '/Resources/Icons/report.png') downloadAndIndexIcon = qt.QIcon(self.modulePath + '/Resources/Icons/downloadAndIndex.png') downloadAndLoadIcon = qt.QIcon(self.modulePath + '/Resources/Icons/downloadAndLoad.png') browserIcon = qt.QIcon(self.modulePath + '/Resources/Icons/TCIABrowser.png') cancelIcon = qt.QIcon(self.modulePath + '/Resources/Icons/cancel.png') self.downloadIcon = qt.QIcon(self.modulePath + '/Resources/Icons/download.png') self.storedlIcon = qt.QIcon(self.modulePath + '/Resources/Icons/stored.png') self.browserWidget.setWindowIcon(browserIcon) # # Reload and Test area # reloadCollapsibleButton = ctk.ctkCollapsibleButton() reloadCollapsibleButton.text = "Reload && Test" # uncomment the next line for developing and testing # self.layout.addWidget(reloadCollapsibleButton) # reloadFormLayout = qt.QFormLayout(reloadCollapsibleButton) # reload button # (use this during development, but remove it when delivering your module to users) # self.reloadButton = qt.QPushButton("Reload") # self.reloadButton.toolTip = "Reload this module." # self.reloadButton.name = "TCIABrowser Reload" # reloadFormLayout.addWidget(self.reloadButton) # self.reloadButton.connect('clicked()', self.onReload) # reload and test button # (use this during development, but remove it when delivering your module to users) # self.reloadAndTestButton = qt.QPushButton("Reload and Test") # self.reloadAndTestButton.toolTip = "Reload this module and then run the self tests." # reloadFormLayout.addWidget(self.reloadAndTestButton) # self.reloadAndTestButton.connect('clicked()', self.onReloadAndTest) # # Browser Area # browserCollapsibleButton = ctk.ctkCollapsibleButton() browserCollapsibleButton.text = "TCIA Browser" self.layout.addWidget(browserCollapsibleButton) browserLayout = qt.QGridLayout(browserCollapsibleButton) self.popupGeometry = qt.QRect() mainWindow = slicer.util.mainWindow() if mainWindow: width = mainWindow.width * 0.75 height = mainWindow.height * 0.75 self.popupGeometry.setWidth(width) self.popupGeometry.setHeight(height) self.popupPositioned = False self.browserWidget.setGeometry(self.popupGeometry) # # Login Area # self.promptLabel = qt.QLabel("To browse collections, please log in first.") self.usernameLabel = qt.QLabel("Username: ") self.passwordLabel = qt.QLabel("Password: ") self.usernameEdit = qt.QLineEdit("nbia_guest") self.usernameEdit.setPlaceholderText("For public access, enter \"nbia_guest\".") self.passwordEdit = qt.QLineEdit() self.passwordEdit.setPlaceholderText("No password required for public access.") self.passwordEdit.setEchoMode(qt.QLineEdit.Password) self.loginButton = qt.QPushButton("Log In") self.loginButton.toolTip = "Logging in to TCIA Server." self.loginButton.enabled = True self.nlstSwitch = qt.QCheckBox("NLST Database") self.nlstSwitch.setCheckState(False) self.nlstSwitch.setTristate(False) browserLayout.addWidget(self.usernameLabel, 1, 1, 1, 1) browserLayout.addWidget(self.usernameEdit, 1, 2, 1, 1) browserLayout.addWidget(self.passwordLabel, 2, 1, 1, 1) browserLayout.addWidget(self.passwordEdit, 2, 2, 1, 1) browserLayout.addWidget(self.promptLabel, 0, 0, 1, 0) browserLayout.addWidget(self.loginButton, 3, 1, 2, 1) browserLayout.addWidget(self.nlstSwitch, 3, 2, 1, 1) self.logoutButton = qt.QPushButton("Log Out") self.logoutButton.toolTip = "Logging out of TCIA Browser." self.logoutButton.hide() browserLayout.addWidget(self.logoutButton, 1, 0, 2, 1) # # Show Browser Button # self.showBrowserButton = qt.QPushButton("Show Browser") # self.showBrowserButton.toolTip = "." self.showBrowserButton.enabled = False self.showBrowserButton.hide() browserLayout.addWidget(self.showBrowserButton, 1, 2, 2, 1) # Browser Widget Layout within the collapsible button browserWidgetLayout = qt.QVBoxLayout(self.browserWidget) self.collectionsCollapsibleGroupBox = ctk.ctkCollapsibleGroupBox() self.collectionsCollapsibleGroupBox.setTitle('Collections') browserWidgetLayout.addWidget(self.collectionsCollapsibleGroupBox) collectionsFormLayout = qt.QHBoxLayout(self.collectionsCollapsibleGroupBox) # # Collection Selector ComboBox # self.collectionSelectorLabel = qt.QLabel('Current Collection:') collectionsFormLayout.addWidget(self.collectionSelectorLabel) # Selector ComboBox self.collectionSelector = qt.QComboBox() self.collectionSelector.setMinimumWidth(200) collectionsFormLayout.addWidget(self.collectionSelector) # # Use Cache CheckBox # self.useCacheCeckBox = qt.QCheckBox("Cache server responses") self.useCacheCeckBox.toolTip = '''For faster browsing if this box is checked\ the browser will cache server responses and on further calls\ would populate tables based on saved data on disk.''' collectionsFormLayout.addWidget(self.useCacheCeckBox) self.useCacheCeckBox.setCheckState(False) self.useCacheCeckBox.setTristate(False) collectionsFormLayout.addStretch(4) logoLabelText = "<img src='" + self.modulePath + "/Resources/Logos/logo-vertical.png'" + ">" self.logoLabel = qt.QLabel(logoLabelText) collectionsFormLayout.addWidget(self.logoLabel) # # Collection Description Widget # self.collectionDescriptions = [] self.collectionDescriptionCollapsibleGroupBox = ctk.ctkCollapsibleGroupBox() self.collectionDescriptionCollapsibleGroupBox.setTitle('Collection Description') self.collectionDescription = qt.QTextBrowser() collectionDescriptionBoxLayout = qt.QVBoxLayout(self.collectionDescriptionCollapsibleGroupBox) collectionDescriptionBoxLayout.addWidget(self.collectionDescription) browserWidgetLayout.addWidget(self.collectionDescriptionCollapsibleGroupBox) # # Patient Table Widget # self.patientsCollapsibleGroupBox = ctk.ctkCollapsibleGroupBox() self.patientsCollapsibleGroupBox.setTitle('Patients') browserWidgetLayout.addWidget(self.patientsCollapsibleGroupBox) patientsVBoxLayout1 = qt.QVBoxLayout(self.patientsCollapsibleGroupBox) patientsExpdableArea = ctk.ctkExpandableWidget() patientsVBoxLayout1.addWidget(patientsExpdableArea) patientsVBoxLayout2 = qt.QVBoxLayout(patientsExpdableArea) # patientsVerticalLayout = qt.QVBoxLayout(patientsExpdableArea) self.patientsTableWidget = qt.QTableWidget() self.patientsModel = qt.QStandardItemModel() self.patientsTableHeaderLabels = ['Patient ID', 'Patient Sex', 'Phantom', 'Species Description'] self.patientsTableWidget.setColumnCount(4) self.patientsTableWidget.sortingEnabled = True self.patientsTableWidget.setHorizontalHeaderLabels(self.patientsTableHeaderLabels) self.patientsTableWidgetHeader = self.patientsTableWidget.horizontalHeader() self.patientsTableWidgetHeader.setStretchLastSection(True) self.patientsTableWidgetHeader.setDefaultAlignment(qt.Qt.AlignLeft) # patientsTableWidgetHeader.setResizeMode(qt.QHeaderView.Stretch) patientsVBoxLayout2.addWidget(self.patientsTableWidget) # self.patientsTreeSelectionModel = self.patientsTableWidget.selectionModel() abstractItemView = qt.QAbstractItemView() self.patientsTableWidget.setSelectionBehavior(abstractItemView.SelectRows) verticalheader = self.patientsTableWidget.verticalHeader() verticalheader.setDefaultSectionSize(20) patientsVBoxLayout1.setSpacing(0) patientsVBoxLayout2.setSpacing(0) patientsVBoxLayout1.setMargin(0) patientsVBoxLayout2.setContentsMargins(7, 3, 7, 7) self.patientsTableWidget.setEditTriggers(qt.QAbstractItemView.NoEditTriggers) # # Studies Table Widget # self.studiesCollapsibleGroupBox = ctk.ctkCollapsibleGroupBox() self.studiesCollapsibleGroupBox.setTitle('Studies') browserWidgetLayout.addWidget(self.studiesCollapsibleGroupBox) studiesVBoxLayout1 = qt.QVBoxLayout(self.studiesCollapsibleGroupBox) studiesExpdableArea = ctk.ctkExpandableWidget() studiesVBoxLayout1.addWidget(studiesExpdableArea) studiesVBoxLayout2 = qt.QVBoxLayout(studiesExpdableArea) self.studiesTableWidget = qt.QTableWidget() self.studiesTableWidget.setCornerButtonEnabled(True) self.studiesModel = qt.QStandardItemModel() self.studiesTableHeaderLabels = ['Study Instance UID', 'Patient ID', 'Study Date', 'Study Description','Patient Age', 'Event Type', 'Days From Event', 'Series Count'] self.studiesTableWidget.setColumnCount(8) self.studiesTableWidget.sortingEnabled = True self.studiesTableWidget.hideColumn(0) self.studiesTableWidget.setHorizontalHeaderLabels(self.studiesTableHeaderLabels) self.studiesTableWidget.resizeColumnsToContents() studiesVBoxLayout2.addWidget(self.studiesTableWidget) # self.studiesTreeSelectionModel = self.studiesTableWidget.selectionModel() self.studiesTableWidget.setSelectionBehavior(abstractItemView.SelectRows) studiesVerticalheader = self.studiesTableWidget.verticalHeader() studiesVerticalheader.setDefaultSectionSize(20) self.studiesTableWidgetHeader = self.studiesTableWidget.horizontalHeader() self.studiesTableWidgetHeader.setStretchLastSection(True) self.studiesTableWidgetHeader.setDefaultAlignment(qt.Qt.AlignLeft) studiesSelectOptionsWidget = qt.QWidget() studiesSelectOptionsLayout = qt.QHBoxLayout(studiesSelectOptionsWidget) studiesSelectOptionsLayout.setMargin(0) studiesVBoxLayout2.addWidget(studiesSelectOptionsWidget) studiesSelectLabel = qt.QLabel('Select:') studiesSelectOptionsLayout.addWidget(studiesSelectLabel) self.studiesSelectAllButton = qt.QPushButton('All') self.studiesSelectAllButton.enabled = False self.studiesSelectAllButton.setMaximumWidth(50) studiesSelectOptionsLayout.addWidget(self.studiesSelectAllButton) self.studiesSelectNoneButton = qt.QPushButton('None') self.studiesSelectNoneButton.enabled = False self.studiesSelectNoneButton.setMaximumWidth(50) studiesSelectOptionsLayout.addWidget(self.studiesSelectNoneButton) studiesSelectOptionsLayout.addStretch(1) studiesVBoxLayout1.setSpacing(0) studiesVBoxLayout2.setSpacing(0) studiesVBoxLayout1.setMargin(0) studiesVBoxLayout2.setContentsMargins(7, 3, 7, 7) self.studiesTableWidget.setEditTriggers(qt.QAbstractItemView.NoEditTriggers) # # Series Table Widget # self.seriesCollapsibleGroupBox = ctk.ctkCollapsibleGroupBox() self.seriesCollapsibleGroupBox.setTitle('Series') browserWidgetLayout.addWidget(self.seriesCollapsibleGroupBox) seriesVBoxLayout1 = qt.QVBoxLayout(self.seriesCollapsibleGroupBox) seriesExpdableArea = ctk.ctkExpandableWidget() seriesVBoxLayout1.addWidget(seriesExpdableArea) seriesVBoxLayout2 = qt.QVBoxLayout(seriesExpdableArea) self.seriesTableWidget = qt.QTableWidget() # self.seriesModel = qt.QStandardItemModel() self.seriesTableWidget.setColumnCount(14) self.seriesTableWidget.sortingEnabled = True self.seriesTableWidget.hideColumn(0) self.seriesTableHeaderLabels = ['Series Instance UID', 'Status', 'Patient ID', 'Study Date', 'Series Description', 'Series Number', 'Modality', 'Body Part Examined', 'Image Count', 'File Size (MB)', 'Protocol Name', 'Manufacturer', 'Manufacturer Model Name', 'License URI'] self.seriesTableWidget.setHorizontalHeaderLabels(self.seriesTableHeaderLabels) self.seriesTableWidget.resizeColumnsToContents() seriesVBoxLayout2.addWidget(self.seriesTableWidget) # self.seriesTreeSelectionModel = self.studiesTableWidget.selectionModel() self.seriesTableWidget.setSelectionBehavior(abstractItemView.SelectRows) self.seriesTableWidget.setSelectionMode(3) self.seriesTableWidgetHeader = self.seriesTableWidget.horizontalHeader() self.seriesTableWidgetHeader.setStretchLastSection(True) self.seriesTableWidgetHeader.setDefaultAlignment(qt.Qt.AlignLeft) # seriesTableWidgetHeader.setResizeMode(qt.QHeaderView.Stretch) seriesVerticalheader = self.seriesTableWidget.verticalHeader() seriesVerticalheader.setDefaultSectionSize(20) seriesSelectOptionsWidget = qt.QWidget() seriesSelectOptionsLayout = qt.QHBoxLayout(seriesSelectOptionsWidget) seriesVBoxLayout2.addWidget(seriesSelectOptionsWidget) seriesSelectOptionsLayout.setMargin(0) seriesSelectLabel = qt.QLabel('Select:') seriesSelectOptionsLayout.addWidget(seriesSelectLabel) self.seriesSelectAllButton = qt.QPushButton('All') self.seriesSelectAllButton.enabled = False self.seriesSelectAllButton.setMaximumWidth(50) seriesSelectOptionsLayout.addWidget(self.seriesSelectAllButton) self.seriesSelectNoneButton = qt.QPushButton('None') self.seriesSelectNoneButton.enabled = False self.seriesSelectNoneButton.setMaximumWidth(50) seriesSelectOptionsLayout.addWidget(self.seriesSelectNoneButton) seriesVBoxLayout1.setSpacing(0) seriesVBoxLayout2.setSpacing(0) seriesVBoxLayout1.setMargin(0) seriesVBoxLayout2.setContentsMargins(7, 3, 7, 7) seriesSelectOptionsLayout.addStretch(1) self.imagesCountLabel = qt.QLabel() self.imagesCountLabel.text = 'No. of images to download: ' + '<span style=" font-size:8pt; font-weight:600; ' \ 'color:#aa0000;">' + str(self.imagesToDownloadCount) + '</span>' + ' ' seriesSelectOptionsLayout.addWidget(self.imagesCountLabel) # seriesSelectOptionsLayout.setAlignment(qt.Qt.AlignTop) self.seriesTableWidget.setEditTriggers(qt.QAbstractItemView.NoEditTriggers) # Index Button # self.indexButton = qt.QPushButton() self.indexButton.setMinimumWidth(50) self.indexButton.toolTip = "Download and Index: The browser will download" \ " the selected sereies and index them in 3D Slicer DICOM Database." self.indexButton.setIcon(downloadAndIndexIcon) iconSize = qt.QSize(70, 40) self.indexButton.setIconSize(iconSize) # self.indexButton.setMinimumHeight(50) self.indexButton.enabled = False # downloadWidgetLayout.addStretch(4) seriesSelectOptionsLayout.addWidget(self.indexButton) # downloadWidgetLayout.addStretch(1) # # Load Button # self.loadButton = qt.QPushButton("") self.loadButton.setMinimumWidth(50) self.loadButton.setIcon(downloadAndLoadIcon) self.loadButton.setIconSize(iconSize) # self.loadButton.setMinimumHeight(50) self.loadButton.toolTip = "Download and Load: The browser will download" \ " the selected sereies and Load them in 3D Slicer scene." self.loadButton.enabled = False seriesSelectOptionsLayout.addWidget(self.loadButton) # downloadWidgetLayout.addStretch(4) self.cancelDownloadButton = qt.QPushButton('') seriesSelectOptionsLayout.addWidget(self.cancelDownloadButton) self.cancelDownloadButton.setIconSize(iconSize) self.cancelDownloadButton.toolTip = "Cancel all downloads." self.cancelDownloadButton.setIcon(cancelIcon) self.cancelDownloadButton.enabled = False self.statusFrame = qt.QFrame() browserWidgetLayout.addWidget(self.statusFrame) statusHBoxLayout = qt.QHBoxLayout(self.statusFrame) statusHBoxLayout.setMargin(0) statusHBoxLayout.setSpacing(0) self.statusLabel = qt.QLabel('') statusHBoxLayout.addWidget(self.statusLabel) statusHBoxLayout.addStretch(1) # # delete data context menu # self.seriesTableWidget.setContextMenuPolicy(2) self.removeSeriesAction = qt.QAction("Remove from disk", self.seriesTableWidget) self.seriesTableWidget.addAction(self.removeSeriesAction) # self.removeSeriesAction.enabled = False # # Settings Area # settingsCollapsibleButton = ctk.ctkCollapsibleButton() settingsCollapsibleButton.text = "Settings" self.layout.addWidget(settingsCollapsibleButton) settingsGridLayout = qt.QGridLayout(settingsCollapsibleButton) settingsCollapsibleButton.collapsed = True # Storage Path button # # storageWidget = qt.QWidget() # storageFormLayout = qt.QFormLayout(storageWidget) # settingsVBoxLayout.addWidget(storageWidget) storagePathLabel = qt.QLabel("Storage Folder: ") self.storagePathButton = ctk.ctkDirectoryButton() self.storagePathButton.directory = self.storagePath self.storageResetButton = qt.QPushButton("Reset Path") self.storageResetButton.toolTip = "Resetting the storage folder to default." self.storageResetButton.enabled = True if self.settings.contains("customStoragePath") else False settingsGridLayout.addWidget(storagePathLabel, 0, 0, 1, 1) settingsGridLayout.addWidget(self.storagePathButton, 0, 1, 1, 4) settingsGridLayout.addWidget(self.storageResetButton, 1, 0, 1, 1) # connections self.showBrowserButton.connect('clicked(bool)', self.onShowBrowserButton) self.collectionSelector.connect('currentIndexChanged(QString)', self.collectionSelected) self.patientsTableWidget.connect('itemSelectionChanged()', self.patientsTableSelectionChanged) self.studiesTableWidget.connect('itemSelectionChanged()', self.studiesTableSelectionChanged) self.seriesTableWidget.connect('itemSelectionChanged()', self.seriesSelected) self.loginButton.connect('clicked(bool)', self.AccountSelected) self.logoutButton.connect('clicked(bool)', self.onLogoutButton) self.useCacheCeckBox.connect('stateChanged(int)', self.onUseCacheStateChanged) self.indexButton.connect('clicked(bool)', self.onIndexButton) self.loadButton.connect('clicked(bool)', self.onLoadButton) self.cancelDownloadButton.connect('clicked(bool)', self.onCancelDownloadButton) self.storagePathButton.connect('directoryChanged(const QString &)', self.onStoragePathButton) self.removeSeriesAction.connect('triggered()', self.onRemoveSeriesContextMenuTriggered) self.seriesSelectAllButton.connect('clicked(bool)', self.onSeriesSelectAllButton) self.seriesSelectNoneButton.connect('clicked(bool)', self.onSeriesSelectNoneButton) self.studiesSelectAllButton.connect('clicked(bool)', self.onStudiesSelectAllButton) self.studiesSelectNoneButton.connect('clicked(bool)', self.onStudiesSelectNoneButton) self.storageResetButton.connect('clicked(bool)', self.onStorageResetButton) # self.patientsTableWidget.horizontalHeader().sortIndicatorChanged.connect(lambda: self.tableWidgetReorder("patients")) # self.studiesTableWidget.horizontalHeader().sortIndicatorChanged.connect(lambda: self.tableWidgetReorder("studies")) # self.seriesTableWidget.horizontalHeader().sortIndicatorChanged.connect(lambda: self.tableWidgetReorder("series")) # Add vertical spacer self.layout.addStretch(1) # def tableWidgetReorder(self, tableType): # pass def cleanup(self): pass def AccountSelected(self): # print(self.closeEvent()) if self.nlstSwitch.isChecked(): self.usernameEdit.setText("nbia_guest") self.passwordEdit.setText("") elif self.usernameEdit.text.strip() != 'nbia_guest' and self.passwordEdit.text.strip() == '': qt.QMessageBox.critical(slicer.util.mainWindow(), 'TCIA Browser', "Please enter username and password.", qt.QMessageBox.Ok) return None self.getCollectionValues() def onLogoutButton(self): if self.loginButton.isVisible(): self.settings.setValue("loginStatus", True) if hasattr(self.TCIAClient, "exp_time"): message = "You have logged in. Your token will expire at " + str(self.TCIAClient.exp_time) else: message = "You have logged in." self.promptLabel.setText(message) self.usernameLabel.hide() self.usernameEdit.hide() self.passwordLabel.hide() self.passwordEdit.hide() self.loginButton.hide() self.nlstSwitch.hide() self.logoutButton.show() self.showBrowserButton.show() self.showBrowserButton.enabled = True else: self.collectionDescriptions = [] # if self.usernameEdit.text.strip() != "nbia_guest": # self.TCIAClient.logOut() del(self.TCIAClient) self.settings.setValue("loginStatus", False) self.browserWidget.close() self.promptLabel.setText("To browse collections, please log in first") self.usernameEdit.setText("") self.usernameLabel.show() self.usernameEdit.show() self.passwordEdit.setText("") self.passwordLabel.show() self.passwordEdit.show() self.loginButton.enabled = True self.loginButton.setText("Log In") self.loginButton.show() self.nlstSwitch.show() self.logoutButton.hide() self.showBrowserButton.hide() self.showBrowserButton.enabled = False self.settings.setValue("browserWidgetGeometry", "") def onShowBrowserButton(self): self.showBrowser() def onUseCacheStateChanged(self, state): if state == 0: self.useCacheFlag = False elif state == 2: self.useCacheFlag = True def onRemoveSeriesContextMenuTriggered(self): removeList = [] rows = rows = [i.row() for i in self.seriesTableWidget.selectionModel().selectedRows()] for row in rows: self.seriesTableWidget.item(row, 1).setIcon(self.downloadIcon) removeList.append(self.seriesTableWidget.item(row, 0).text()) slicer.dicomDatabase.removeSeries(self.seriesTableWidget.item(row, 0).text(), True) self.previouslyDownloadedSeries = set([slicer.dicomDatabase.seriesForFile(x) for x in slicer.dicomDatabase.allFiles()]) # self.studiesTableSelectionChanged() def showBrowser(self): self.browserWidget.adjustSize() if not self.browserWidget.isVisible(): self.popupPositioned = True self.browserWidget.show() if self.settings.value("browserWidgetGeometry") != "": self.browserWidget.setGeometry(self.settings.value("browserWidgetGeometry")) self.browserWidget.raise_() if not self.popupPositioned: mainWindow = slicer.util.mainWindow() screenMainPos = mainWindow.pos x = screenMainPos.x() + 100 y = screenMainPos.y() + 100 self.browserWidget.move(qt.QPoint(x, y)) self.popupPositioned = True def showStatus(self, message): self.statusLabel.text = message self.statusLabel.setStyleSheet("QLabel { background-color : #F0F0F0 ; color : #383838; }") slicer.app.processEvents() def clearStatus(self): self.statusLabel.text = '' self.statusLabel.setStyleSheet("QLabel { background-color : white; color : black; }") def onStoragePathButton(self): self.storagePath = self.storagePathButton.directory self.settings.setValue("customStoragePath", self.storagePath) self.storageResetButton.enabled = True def onStorageResetButton(self): self.settings.remove("customStoragePath") self.storageResetButton.enabled = False self.storagePath = self.settings.value("defaultStoragePath") self.storagePathButton.directory = self.storagePath def getCollectionValues(self): self.initialConnection = True # Instantiate TCIAClient object self.loginButton.enabled = False self.loginButton.setText("Logging In") self.TCIAClient = TCIAClient.TCIAClient(self.usernameEdit.text.strip(), self.passwordEdit.text.strip(), self.nlstSwitch.isChecked()) self.showStatus("Getting Available Collections") if hasattr(self.TCIAClient, "credentialError"): qt.QMessageBox.critical(slicer.util.mainWindow(),'TCIA Browser', self.TCIAClient.credentialError, qt.QMessageBox.Ok) return None try: self.showBrowser() response = self.TCIAClient.get_collection_values() self.populateCollectionsTreeView(response) self.clearStatus() except Exception as error: self.loginButton.setText("Log In") self.loginButton.enabled = True self.clearStatus() message = "getCollectionValues: Error in getting response from TCIA server.\nHTTP Error:\n" + str(error) qt.QMessageBox.critical(slicer.util.mainWindow(), 'TCIA Browser', message, qt.QMessageBox.Ok) self.onLogoutButton() def onStudiesSelectAllButton(self): self.studiesTableWidget.selectAll() def onStudiesSelectNoneButton(self): self.studiesTableWidget.clearSelection() def onSeriesSelectAllButton(self): self.seriesTableWidget.selectAll() def onSeriesSelectNoneButton(self): self.seriesTableWidget.clearSelection() def collectionSelected(self, item): self.loadButton.enabled = False self.indexButton.enabled = False self.clearPatientsTableWidget() self.clearStudiesTableWidget() self.clearSeriesTableWidget() self.selectedCollection = item if not os.path.exists(f"{self.cachePath}{self.selectedCollection}"): os.mkdir(f"{self.cachePath}{self.selectedCollection}") cacheFile = f"{self.cachePath}{self.selectedCollection}/Collection - {self.selectedCollection}.json" self.progressMessage = "Getting available patients for collection: " + self.selectedCollection self.showStatus(self.progressMessage) # Check if there is a cache for collection descriptions collectionCache = f"{self.cachePath}NLSTDescription.json" if self.nlstSwitch.isChecked() else f"{self.cachePath}CollectionDescriptions.json" # If there is cache, use the cache if os.path.isfile(collectionCache): f = codecs.open(collectionCache, 'rb', encoding='utf8') self.collectionDescriptions = json.loads(f.read()[:]) f.close() # If there is no cache, fetch from the server and save a cache else: self.collectionDescriptions = self.TCIAClient.get_collection_descriptions() with open(collectionCache, 'wb') as outputFile: self.stringBufferReadWrite(outputFile, self.collectionDescriptions) outputFile.close() # Fetch a new list of collection descriptions from the server if the existing cache is outdated filteredDescriptions = list(filter(lambda record: record["collectionName"] == self.selectedCollection, self.collectionDescriptions)) if len(filteredDescriptions) != 0: self.collectionDescription.setHtml(filteredDescriptions[0]["description"]) else: self.collectionDescriptions = self.TCIAClient.get_collection_descriptions() with open(collectionCache, 'wb') as outputFile: self.stringBufferReadWrite(outputFile, self.collectionDescriptions) outputFile.close() filteredDescriptions = list(filter(lambda record: record["collectionName"] == self.selectedCollection, self.collectionDescriptions)) if len(filteredDescriptions) != 0: self.collectionDescription.setHtml(filteredDescriptions[0]["description"]) patientsList = None if os.path.isfile(cacheFile) and self.useCacheFlag: f = codecs.open(cacheFile, 'rb', encoding='utf8') patientsList = f.read()[:] f.close() if not len(patientsList): patientsList = None if patientsList: self.populatePatientsTableWidget(patientsList) self.clearStatus() groupBoxTitle = 'Patients (Accessed: ' + time.ctime(os.path.getmtime(cacheFile)) + ')' self.patientsCollapsibleGroupBox.setTitle(groupBoxTitle) else: try: response = self.TCIAClient.get_patient(collection=self.selectedCollection) with open(cacheFile, 'wb') as outputFile: self.stringBufferReadWrite(outputFile, response) outputFile.close() f = codecs.open(cacheFile, 'rb', encoding='utf8') responseString = json.loads(f.read()[:]) self.populatePatientsTableWidget(responseString) groupBoxTitle = 'Patients (Accessed: ' + time.ctime(os.path.getmtime(cacheFile)) + ')' self.patientsCollapsibleGroupBox.setTitle(groupBoxTitle) self.clearStatus() except Exception as error: self.clearStatus() message = "collectionSelected: Error in getting response from TCIA server.\nHTTP Error:\n" + str(error) qt.QMessageBox.critical(slicer.util.mainWindow(), 'TCIA Browser', message, qt.QMessageBox.Ok) def patientsTableSelectionChanged(self): self.clearStudiesTableWidget() self.clearSeriesTableWidget() self.studiesTableRowCount = 0 rows = [i.row() for i in self.patientsTableWidget.selectionModel().selectedRows()] self.numberOfSelectedPatients = len(rows) self.patientSelected(rows) def patientSelected(self, rows): self.loadButton.enabled = False self.indexButton.enabled = False # self.clearStudiesTableWidget() self.clearSeriesTableWidget() self.selectedPatients = [] responseString = [] try: for row in rows: self.selectedPatients.append(self.patientsTableWidget.item(row, 0).text()) cacheFile = f"{self.cachePath}{self.selectedCollection}/Patient - {self.selectedPatients[-1]}.json" self.progressMessage = "Getting available studies for patient ID: " + self.selectedPatients[-1] self.showStatus(self.progressMessage) if os.path.isfile(cacheFile) and self.useCacheFlag: f = codecs.open(cacheFile, 'rb', encoding='utf8') responseString.append(json.loads(f.read())) f.close() else: response = self.TCIAClient.get_patient_study(self.selectedCollection, self.selectedPatients[-1]) responseString.append(response) response = json.dumps(response).encode("utf-8") with open(cacheFile, 'wb') as outputFile: outputFile.write(response) outputFile.close() responseString = str(list(chain(*responseString))).replace("\'", "\"") self.populateStudiesTableWidget(responseString) if self.numberOfSelectedPatients == 1: groupBoxTitle = 'Studies (Accessed: ' + time.ctime(os.path.getmtime(cacheFile)) + ')' else: groupBoxTitle = 'Studies ' self.studiesCollapsibleGroupBox.setTitle(groupBoxTitle) self.clearStatus() except Exception as error: self.clearStatus() message = "patientSelected: Error in getting response from TCIA server.\nHTTP Error:\n" + str(error) qt.QMessageBox.critical(slicer.util.mainWindow(), 'TCIA Browser', message, qt.QMessageBox.Ok) def studiesTableSelectionChanged(self): self.clearSeriesTableWidget() self.seriesTableRowCount = 0 rows = [i.row() for i in self.studiesTableWidget.selectionModel().selectedRows()] self.numberOfSelectedStudies = len(rows) self.studySelected(rows) def studySelected(self, rows): self.loadButton.enabled = False self.indexButton.enabled = False self.selectedStudies = [] responseString = [] self.previouslyDownloadedSeries = set([slicer.dicomDatabase.seriesForFile(x) for x in slicer.dicomDatabase.allFiles()]) try: for row in rows: self.selectedStudies.append(self.studiesTableWidget.item(row, 0).text()) cacheFile = f"{self.cachePath}{self.selectedCollection}/Study - {self.selectedStudies[-1]}.json" self.progressMessage = "Getting available series for studyInstanceUID: " + self.selectedStudies[-1] self.showStatus(self.progressMessage) if os.path.isfile(cacheFile) and self.useCacheFlag: f = codecs.open(cacheFile, 'rb', encoding='utf8') responseString.append(json.loads(f.read())) f.close() else: response = self.TCIAClient.get_series(self.selectedCollection, None, self.selectedStudies[-1]) responseString.append(response) response = json.dumps(response).encode("utf-8") with open(cacheFile, 'wb') as outputFile: outputFile.write(response) outputFile.close() responseString = str(list(chain(*responseString))).replace("\'", "\"") self.populateSeriesTableWidget(responseString) if self.numberOfSelectedStudies == 1: groupBoxTitle = 'Series (Accessed: ' + time.ctime(os.path.getmtime(cacheFile)) + ')' else: groupBoxTitle = 'Series ' self.seriesCollapsibleGroupBox.setTitle(groupBoxTitle) self.clearStatus() except Exception as error: self.clearStatus() message = "studySelected: Error in getting response from TCIA server.\nHTTP Error:\n" + str(error) qt.QMessageBox.critical(slicer.util.mainWindow(), 'TCIA Browser', message, qt.QMessageBox.Ok) self.onSeriesSelectAllButton() # self.loadButton.enabled = True # self.indexButton.enabled = True def seriesSelected(self): self.imagesToDownloadCount = 0 self.loadButton.enabled = False self.indexButton.enabled = False rows = [i.row() for i in self.seriesTableWidget.selectionModel().selectedRows()] for row in rows: self.imagesToDownloadCount += int(self.seriesTableWidget.item(row, 8).text()) self.loadButton.enabled = True self.indexButton.enabled = True self.imagesCountLabel.text = 'No. of images to download: ' + '<span style=" font-size:8pt; font-weight:600; color:#aa0000;">' + str( self.imagesToDownloadCount) + '</span>' + ' ' def onIndexButton(self): self.loadToScene = False self.addSelectedToDownloadQueue() # self.addFilesToDatabase() def onLoadButton(self): self.loadToScene = True self.addSelectedToDownloadQueue() def onCancelDownloadButton(self): self.cancelDownload = True for series in self.downloadQueue.keys(): self.removeDownloadProgressBar(series) downloadQueue = {} seriesRowNumber = {} def addFilesToDatabase(self, seriesUID): self.progressMessage = "Adding Files to DICOM Database " self.showStatus(self.progressMessage) dicomWidget = slicer.modules.dicom.widgetRepresentation().self() indexer = ctk.ctkDICOMIndexer() # DICOM indexer uses the current DICOM database folder as the basis for relative paths, # therefore we must convert the folder path to absolute to ensure this code works # even when a relative path is used as self.extractedFilesDirectory. indexer.addDirectory(slicer.dicomDatabase, os.path.abspath(self.extractedFilesDirectory)) indexer.waitForImportFinished() self.clearStatus() def addSelectedToDownloadQueue(self): DICOM.DICOMFileDialog.createDefaultDatabase() self.cancelDownload = False allSelectedSeriesUIDs = [] downloadQueue = {} self.seriesRowNumber = {} self.downloadQueue = {} refSeriesList = [] imageSizeToDownload = 0 rows = [i.row() for i in self.seriesTableWidget.selectionModel().selectedRows()] for row in rows: print(row) selectedSeries = self.seriesTableWidget.item(row, 0).text() self.selectedSeriesNicknamesDic[selectedSeries] = str(row + 1) allSelectedSeriesUIDs.append(selectedSeries) imageSizeToDownload += float(self.seriesTableWidget.item(row, 9).text()) if self.seriesTableWidget.item(row, 9).text() != "< 0.01" else 0.01 if not any(selectedSeries == s for s in self.previouslyDownloadedSeries): # check if selected is an RTSTRUCT or SEG file if self.seriesTableWidget.item(row, 6).text() in ["RTSTRUCT", "SEG"]: try: refSeries, refSeriesSize = self.TCIAClient.get_seg_ref_series(seriesInstanceUid = selectedSeries) # check if the reference series is also selected or is already downloaded if not self.seriesTableWidget.findItems(refSeries, qt.Qt.MatchExactly)[0].isSelected() and not any(refSeries == r for r in self.previouslyDownloadedSeries) and refSeries not in refSeriesList: message = f"Your selection {selectedSeries} is an RTSTRUCT or SEG file and it seems you have not either downloaded the reference series {refSeries}. Do you wish to download it as well?" choice = qt.QMessageBox.warning(slicer.util.mainWindow(), 'TCIA Browser', message, qt.QMessageBox.Yes | qt.QMessageBox.No) if (choice == qt.QMessageBox.Yes): allSelectedSeriesUIDs.append(refSeries) refSeriesList.append(refSeries) downloadFolderPath = os.path.join(self.storagePath, refSeries) + os.sep self.downloadQueue[refSeries] = [downloadFolderPath, refSeriesSize] imageSizeToDownload += refSeriesSize # check if the reference series is in the same table if len(self.seriesTableWidget.findItems(refSeries, qt.Qt.MatchExactly)) != 0: refRow = self.seriesTableWidget.row(self.seriesTableWidget.findItems(refSeries, qt.Qt.MatchExactly)[0]) self.selectedSeriesNicknamesDic[refSeries] = str(refRow + 1) self.seriesRowNumber[refSeries] = refRow except Exception: pass downloadFolderPath = os.path.join(self.storagePath, selectedSeries) + os.sep self.downloadQueue[selectedSeries] = [downloadFolderPath, self.seriesTableWidget.item(row, 9).text()] self.seriesRowNumber[selectedSeries] = row if imageSizeToDownload < 1024: downloadWarning = f"You have selected {len(self.downloadQueue)} series to download, the download size is {round(imageSizeToDownload, 2)} MB, do you wish to proceed?" else: downloadWarning = f"You have selected {len(self.downloadQueue)} series to download, the download size is {round(imageSizeToDownload/1024, 2)} GB, do you wish to proceed?" # Warn users of the download size and series downloadChoice = qt.QMessageBox.warning(slicer.util.mainWindow(), 'TCIA Browser', downloadWarning, qt.QMessageBox.Yes | qt.QMessageBox.No) if (downloadChoice == qt.QMessageBox.No): return None self.downloadQueue = dict(reversed(self.downloadQueue.items())) self.seriesTableWidget.clearSelection() self.patientsTableWidget.enabled = False self.studiesTableWidget.enabled = False self.collectionSelector.enabled = False self.downloadSelectedSeries() if self.loadToScene: availablePlugins = list(slicer.modules.dicomPlugins) for seriesUID in allSelectedSeriesUIDs: if any(seriesUID == s for s in self.previouslyDownloadedSeries): self.progressMessage = "Examine Files to Load" self.showStatus(self.progressMessage) if slicer.dicomDatabase.fieldForSeries("Modality", seriesUID) == ("RTSTRUCT"): # if not "DicomRtImportExportPlugin" in availablePlugins: # self.progressMessage = "It appears that SlicerRT extension is not installed or enabled, skipping series: " + seriesUID # self.showStatus(self.progressMessage) # continue plugin = slicer.modules.dicomPlugins["DicomRtImportExportPlugin"]() elif slicer.dicomDatabase.fieldForSeries("Modality", seriesUID) == ("SEG"): # if not "DICOMSegmentationPlugin" in availablePlugins: # self.progressMessage = "It appears that QuantitativeReporting extension is not installed or enabled, skipping series: " + seriesUID # self.showStatus(self.progressMessage) # continue plugin = slicer.modules.dicomPlugins["DICOMSegmentationPlugin"]() else: plugin = slicer.modules.dicomPlugins["DICOMScalarVolumePlugin"]() seriesUID = seriesUID.replace("'", "") dicomDatabase = slicer.dicomDatabase fileList = slicer.dicomDatabase.filesForSeries(seriesUID) loadables = plugin.examine([fileList]) self.clearStatus() volume = plugin.load(loadables[0]) self.browserWidget.close() def downloadSelectedSeries(self): while self.downloadQueue and not self.cancelDownload: self.cancelDownloadButton.enabled = True selectedSeries, [downloadFolderPath, seriesSize] = self.downloadQueue.popitem() seriesSize = 0.01 if seriesSize == "< 0.01" else float(seriesSize) if not os.path.exists(downloadFolderPath): logging.debug("Creating directory to keep the downloads: " + downloadFolderPath) os.makedirs(downloadFolderPath) # save series uid in a text file for further reference # with open(downloadFolderPath + 'seriesUID.txt', 'w') as f: # f.write(selectedSeries) # f.close() fileName = downloadFolderPath + 'images.zip' logging.debug("Downloading images to " + fileName) self.extractedFilesDirectory = downloadFolderPath + 'images' self.progressMessage = "Downloading Images for series InstanceUID: " + selectedSeries self.showStatus(self.progressMessage) logging.debug(self.progressMessage) try: response = self.TCIAClient.get_image(seriesInstanceUid=selectedSeries) slicer.app.processEvents() # Save server response as images.zip in current directory if response.getcode() == 200: self.makeDownloadProgressBar(selectedSeries) destinationFile = open(fileName, "wb") status = self.__bufferReadWrite(destinationFile, response, selectedSeries, seriesSize) destinationFile.close() logging.debug("Downloaded file %s from the TCIA server" % fileName) self.clearStatus() if status: self.progressMessage = "Extracting Images" logging.debug("Extracting images") # Unzip the data self.showStatus(self.progressMessage) totalItems = self.unzip(fileName, self.extractedFilesDirectory) if totalItems == 0: qt.QMessageBox.critical(slicer.util.mainWindow(), 'TCIA Browser', "Failed to retrieve images for series %s. Please report this message to the developers!" % selectedSeries, qt.QMessageBox.Ok) self.clearStatus() # Import the data into dicomAppWidget and open the dicom browser self.addFilesToDatabase(selectedSeries) # self.previouslyDownloadedSeries = set([slicer.dicomDatabase.seriesForFile(x) for x in slicer.dicomDatabase.allFiles()]) n = self.seriesRowNumber[selectedSeries] table = self.seriesTableWidget item = table.item(n, 1) item.setIcon(self.storedlIcon) else: logging.error("Failed to download images!") self.removeDownloadProgressBar(selectedSeries) self.downloadQueue.pop(selectedSeries, None) os.remove(fileName) else: self.clearStatus() logging.error("downloadSelectedSeries: Error getting image: " + str(response.getcode)) # print error code except Exception as error: self.clearStatus() message = "downloadSelectedSeries: Error in getting response from TCIA server.\nHTTP Error:\n" + str(error) qt.QMessageBox.critical(slicer.util.mainWindow(), 'TCIA Browser', message, qt.QMessageBox.Ok) self.cancelDownloadButton.enabled = False self.collectionSelector.enabled = True self.patientsTableWidget.enabled = True self.studiesTableWidget.enabled = True def makeDownloadProgressBar(self, selectedSeries): # downloadProgressBar = qt.QProgressBar() # self.downloadProgressBars[selectedSeries] = downloadProgressBar # titleLabel = qt.QLabel(selectedSeries) # progressLabel = qt.QLabel(self.selectedSeriesNicknamesDic[selectedSeries] + ' (0 KB)') # self.downloadProgressLabels[selectedSeries] = progressLabel n = self.seriesRowNumber[selectedSeries] table = self.seriesTableWidget # table.setCellWidget(n, 1, downloadProgressBar) table.setItem(n, 1, qt.QTableWidgetItem("Downloading")) # self.downloadFormLayout.addRow(progressLabel,downloadProgressBar) def removeDownloadProgressBar(self, selectedSeries): n = self.seriesRowNumber[selectedSeries] table = self.seriesTableWidget # table.setCellWidget(n, 1, None) table.setItem(n, 1, qt.QTableWidgetItem("")) # self.downloadProgressBars[selectedSeries].deleteLater() # del self.downloadProgressBars[selectedSeries] # self.downloadProgressLabels[selectedSeries].deleteLater() # del self.downloadProgressLabels[selectedSeries] def stringBufferReadWrite(self, dstFile, response, bufferSize=819): response = json.dumps(response).encode("utf-8") self.downloadSize = 0 while 1: # # If DOWNLOAD FINISHED # buffer = response[self.downloadSize:self.downloadSize + bufferSize] # buffer = response.read(bufferSize)[:] slicer.app.processEvents() if not buffer: # Pop from the queue break # # Otherwise, Write buffer chunk to file # slicer.app.processEvents() dstFile.write(buffer) # # And update progress indicators # self.downloadSize += len(buffer) # This part was adopted from XNATSlicer module def __bufferReadWrite(self, dstFile, response, selectedSeries, seriesSize, bufferSize=8192): # currentDownloadProgressBar = self.downloadProgressBars[selectedSeries] # currentProgressLabel = self.downloadProgressLabels[selectedSeries] # Define the buffer read loop self.downloadSize = 0 while 1: # If DOWNLOAD FINISHED buffer = response.read(bufferSize) slicer.app.processEvents() if not buffer: # Pop from the queue # currentDownloadProgressBar.setMaximum(100) # currentDownloadProgressBar.setValue(100) # currentDownloadProgressBar.setVisible(False) # currentProgressLabel.setVisible(False) self.removeDownloadProgressBar(selectedSeries) self.downloadQueue.pop(selectedSeries, None) break if self.cancelDownload: return False # Otherwise, Write buffer chunk to file slicer.app.processEvents() dstFile.write(buffer) # # And update progress indicators # self.downloadSize += len(buffer) # currentDownloadProgressBar.setValue(self.downloadSize / seriesSize * 100) # currentDownloadProgressBar.setMaximum(0) # currentProgressLabel.text = self.selectedSeriesNicknamesDic[ # selectedSeries] + ' (' + str(int(self.downloadSize / 1024) # ) + ' of ' + str( # int(seriesSize / 1024)) + " KB)" # return self.downloadSize return True def unzip(self, sourceFilename, destinationDir): totalItems = 0 with zipfile.ZipFile(sourceFilename) as zf: for member in zf.infolist(): logging.debug("Found item %s in archive" % member.filename) words = member.filename.split('/') path = destinationDir for word in words[:-1]: drive, word = os.path.splitdrive(word) head, word = os.path.split(word) if word in (os.curdir, os.pardir, ''): continue path = os.path.join(path, word) logging.debug("Extracting %s" % words[-1]) zf.extract(member, path) try: dcm = pydicom.read_file(os.path.join(path,words[-1])) totalItems = totalItems + 1 except: pass logging.debug("Total %i DICOM items extracted from image archive." % totalItems) return totalItems def populateCollectionsTreeView(self, responseString): collections = responseString # populate collection selector n = 0 self.collectionSelector.disconnect('currentIndexChanged(QString)') self.collectionSelector.clear() self.collectionSelector.connect('currentIndexChanged(QString)', self.collectionSelected) collectionNames = [] for collection in collections: collectionNames.append(collection['Collection']) collectionNames.sort() for name in collectionNames: self.collectionSelector.addItem(name) def populatePatientsTableWidget(self, responseString): self.clearPatientsTableWidget() table = self.patientsTableWidget patients = responseString table.setRowCount(len(patients)) n = 0 for patient in patients: keys = patient.keys() for key in keys: if key == 'PatientId': patientIDString = str(patient['PatientId']) patientID = qt.QTableWidgetItem(patientIDString) table.setItem(n, 0, patientID) if key == 'PatientSex': patientSex = qt.QTableWidgetItem(str(patient['PatientSex'])) table.setItem(n, 1, patientSex) if key == 'Phantom': phantom = qt.QTableWidgetItem(str(patient['Phantom'])) table.setItem(n, 2, phantom) if key == 'SpeciesDescription': speciesDescription = qt.QTableWidgetItem(str(patient['SpeciesDescription'])) table.setItem(n, 3, speciesDescription) n += 1 self.patientsTableWidget.resizeColumnsToContents() self.patientsTableWidget.sortByColumn(0, qt.Qt.AscendingOrder) self.patientsTableWidgetHeader.setStretchLastSection(True) def populateStudiesTableWidget(self, responseString): self.studiesSelectAllButton.enabled = True self.studiesSelectNoneButton.enabled = True self.clearStudiesTableWidget() table = self.studiesTableWidget studies = json.loads(responseString) n = self.studiesTableRowCount table.setRowCount(n + len(studies)) for study in studies: keys = study.keys() for key in keys: if key == 'StudyInstanceUID': studyInstanceUID = qt.QTableWidgetItem(str(study['StudyInstanceUID'])) table.setItem(n, 0, studyInstanceUID) if key == 'PatientID': patientID = qt.QTableWidgetItem(str(study['PatientID'])) table.setItem(n, 1, patientID) if key == 'StudyDate': studyDate = qt.QTableWidgetItem(str(study['StudyDate'])) table.setItem(n, 2, studyDate) if key == 'StudyDescription': studyDescription = qt.QTableWidgetItem(str(study['StudyDescription'])) table.setItem(n, 3, studyDescription) if key == 'PatientAge': patientAge = qt.QTableWidgetItem(str(study['PatientAge'])) table.setItem(n, 4, patientAge) if key == 'LongitudinalTemporalEventType': longitudinalTemporalEventType = qt.QTableWidgetItem(str(study['LongitudinalTemporalEventType'])) table.setItem(n, 5, longitudinalTemporalEventType) if key == 'LongitudinalTemporalOffsetFromEvent': longitudinalTemporalOffsetFromEvent = qt.QTableWidgetItem(str(study['LongitudinalTemporalOffsetFromEvent'])) table.setItem(n, 6, longitudinalTemporalOffsetFromEvent) if key == 'SeriesCount': seriesCount = qt.QTableWidgetItem(str(study['SeriesCount'])) table.setItem(n, 7, seriesCount) n += 1 self.studiesTableWidget.resizeColumnsToContents() self.studiesTableWidget.sortByColumn(1, qt.Qt.AscendingOrder) self.studiesTableWidgetHeader.setStretchLastSection(True) self.studiesTableRowCount = n def populateSeriesTableWidget(self, responseString): self.clearSeriesTableWidget() table = self.seriesTableWidget seriesCollection = json.loads(responseString) self.seriesSelectAllButton.enabled = True self.seriesSelectNoneButton.enabled = True self.previouslyDownloadedSeries = set([slicer.dicomDatabase.seriesForFile(x) for x in slicer.dicomDatabase.allFiles()]) n = self.seriesTableRowCount table.setRowCount(n + len(seriesCollection)) for series in seriesCollection: keys = series.keys() for key in keys: if key == 'SeriesInstanceUID': seriesInstanceUID = str(series['SeriesInstanceUID']) seriesInstanceUIDItem = qt.QTableWidgetItem(seriesInstanceUID) table.setItem(n, 0, seriesInstanceUIDItem) if any(seriesInstanceUID == s for s in self.previouslyDownloadedSeries): self.removeSeriesAction.enabled = True icon = self.storedlIcon else: icon = self.downloadIcon downloadStatusItem = qt.QTableWidgetItem(str('')) downloadStatusItem.setTextAlignment(qt.Qt.AlignCenter) downloadStatusItem.setIcon(icon) table.setItem(n, 1, downloadStatusItem) if key == 'PatientID': patientID = qt.QTableWidgetItem(str(series['PatientID'])) table.setItem(n, 2, patientID) if key == 'TimeStamp': rows = [i.row() for i in self.studiesTableWidget.selectionModel().selectedRows()] studyIDs = [self.studiesTableWidget.item(row, 0).text() for row in rows] try: studyIDIndex = studyIDs.index(str(series['StudyInstanceUID'])) studyDate = self.studiesTableWidget.item(studyIDIndex, 2).text() seriesDate = qt.QTableWidgetItem(studyDate) table.setItem(n, 3, seriesDate) except: pass if key == 'SeriesDescription': seriesDescription = qt.QTableWidgetItem(str(series['SeriesDescription'])) table.setItem(n, 4, seriesDescription) if key == 'SeriesNumber': seriesNumber = qt.QTableWidgetItem(str(series['SeriesNumber'])) table.setItem(n, 5, seriesNumber) if key == 'Modality': modality = qt.QTableWidgetItem(str(series['Modality'])) table.setItem(n, 6, modality) if key == 'BodyPartExamined': bodyPartExamined = qt.QTableWidgetItem(str(series['BodyPartExamined'])) table.setItem(n, 7, bodyPartExamined) if key == 'ImageCount': imageCount = qt.QTableWidgetItem(str(series['ImageCount'])) table.setItem(n, 8, imageCount) if key == 'FileSize': fileSizeConversion = "< 0.01" if str(round(series['FileSize']/1048576, 2)) == "0.0" else str(round(series['FileSize']/1048576, 2)) fileSize = qt.QTableWidgetItem(fileSizeConversion) table.setItem(n, 9, fileSize) if key == 'ProtocolName': protocolName = qt.QTableWidgetItem(str(series['ProtocolName'])) table.setItem(n, 10, protocolName) if key == 'Manufacturer': manufacturer = qt.QTableWidgetItem(str(series['Manufacturer'])) table.setItem(n, 11, manufacturer) if key == 'ManufacturerModelName': manufacturerModelName = qt.QTableWidgetItem(str(series['ManufacturerModelName'])) table.setItem(n, 12, manufacturerModelName) if key == 'LicenseURI': licenseURI = qt.QTableWidgetItem(str(series['LicenseURI'])) table.setItem(n, 13, licenseURI) n += 1 self.seriesTableWidget.resizeColumnsToContents() self.seriesTableWidget.sortByColumn(2, qt.Qt.AscendingOrder) self.seriesTableRowCount = n self.seriesTableWidgetHeader.setStretchLastSection(True) def clearPatientsTableWidget(self): self.patientsTableWidget.horizontalHeader().setSortIndicator(-1, qt.Qt.AscendingOrder) table = self.patientsTableWidget self.patientsCollapsibleGroupBox.setTitle('Patients') # self.collections = [] table.setRowCount(0) table.clearContents() table.setHorizontalHeaderLabels(self.patientsTableHeaderLabels) def clearStudiesTableWidget(self): self.studiesTableWidget.horizontalHeader().setSortIndicator(-1, qt.Qt.AscendingOrder) self.studiesTableRowCount = 0 table = self.studiesTableWidget self.studiesCollapsibleGroupBox.setTitle('Studies') table.setRowCount(0) table.clearContents() table.setHorizontalHeaderLabels(self.studiesTableHeaderLabels) def clearSeriesTableWidget(self): self.seriesTableWidget.horizontalHeader().setSortIndicator(-1, qt.Qt.AscendingOrder) self.seriesTableRowCount = 0 table = self.seriesTableWidget self.seriesCollapsibleGroupBox.setTitle('Series') table.setRowCount(0) table.clearContents() table.setHorizontalHeaderLabels(self.seriesTableHeaderLabels) def onReload(self, moduleName="TCIABrowser"): """Generic reload method for any scripted module. ModuleWizard will subsitute correct default moduleName. """ import imp, sys, os, slicer import time import xml.etree.ElementTree as ET import webbrowser import string, json import csv import zipfile, os.path widgetName = moduleName + "Widget" # reload the source code # - set source file path # - load the module to the global space filePath = eval('slicer.modules.%s.path' % moduleName.lower()) p = os.path.dirname(filePath) if not sys.path.__contains__(p): sys.path.insert(0, p) fp = open(filePath, "rb") globals()[moduleName] = imp.load_module( moduleName, fp, filePath, ('.py', 'r', imp.PY_SOURCE)) fp.close() # rebuild the widget # - find and hide the existing widget # - create a new widget in the existing parent parent = slicer.util.findChildren(name='%s Reload' % moduleName)[0].parent().parent() for child in parent.children(): try: child.hide() except AttributeError: pass # Remove spacer items item = parent.layout().itemAt(0) while item: parent.layout().removeItem(item) item = parent.layout().itemAt(0) # delete the old widget instance if hasattr(globals()['slicer'].modules, widgetName): getattr(globals()['slicer'].modules, widgetName).cleanup() # create new widget inside existing parent globals()[widgetName.lower()] = eval( 'globals()["%s"].%s(parent)' % (moduleName, widgetName)) globals()[widgetName.lower()].setup() setattr(globals()['slicer'].modules, widgetName, globals()[widgetName.lower()]) self.showBrowserButton.enabled = True def onReloadAndTest(self, moduleName="TCIABrowser"): self.onReload() evalString = 'globals()["%s"].%sTest()' % (moduleName, moduleName) tester = eval(evalString) tester.runTest() # # TCIABrowserLogic # class TCIABrowserLogic(ScriptedLoadableModuleLogic): """This class should implement all the actual computation done by your module. The interface should be such that other python code can import this class and make use of the functionality without requiring an instance of the Widget """ def __init__(self): pass def hasImageData(self, volumeNode): """This is a dummy logic method that returns true if the passed in volume node has valid image data """ if not volumeNode: print('no volume node') return False if volumeNode.GetImageData() == None: print('no image data') return False return True def delayDisplay(self, message, msec=1000): # # logic version of delay display # print(message) self.info = qt.QDialog() self.infoLayout = qt.QVBoxLayout() self.info.setLayout(self.infoLayout) self.label = qt.QLabel(message, self.info) self.infoLayout.addWidget(self.label) qt.QTimer.singleShot(msec, self.info.close) self.info.exec_() def takeScreenshot(self, name, description, type=-1): # show the message even if not taking a screen shot self.delayDisplay(description) if self.enableScreenshots == 0: return lm = slicer.app.layoutManager() # switch on the type to get the requested window widget = 0 if type == -1: # full window widget = slicer.util.mainWindow() elif type == slicer.qMRMLScreenShotDialog().FullLayout: # full layout widget = lm.viewport() elif type == slicer.qMRMLScreenShotDialog().ThreeD: # just the 3D window widget = lm.threeDWidget(0).threeDView() elif type == slicer.qMRMLScreenShotDialog().Red: # red slice window widget = lm.sliceWidget("Red") elif type == slicer.qMRMLScreenShotDialog().Yellow: # yellow slice window widget = lm.sliceWidget("Yellow") elif type == slicer.qMRMLScreenShotDialog().Green: # green slice window widget = lm.sliceWidget("Green") # grab and convert to vtk image data qpixMap = qt.QPixmap().grabWidget(widget) qimage = qpixMap.toImage() imageData = vtk.vtkImageData() slicer.qMRMLUtils().qImageToVtkImageData(qimage, imageData) annotationLogic = slicer.modules.annotations.logic() annotationLogic.CreateSnapShot(name, description, type, self.screenshotScaleFactor, imageData) def run(self, inputVolume, outputVolume, enableScreenshots=0, screenshotScaleFactor=1): """ Run the actual algorithm """ self.delayDisplay('Running the aglorithm') self.enableScreenshots = enableScreenshots self.screenshotScaleFactor = screenshotScaleFactor self.takeScreenshot('TCIABrowser-Start', 'Start', -1) return True class TCIABrowserTest(unittest.TestCase): """ This is the test case for your scripted module. """ def delayDisplay(self, message, msec=1000): """This utility method displays a small dialog and waits. This does two things: 1) it lets the event loop catch up to the state of the test so that rendering and widget updates have all taken place before the test continues and 2) it shows the user/developer/tester the state of the test so that we'll know when it breaks. """ print(message) self.info = qt.QDialog() self.infoLayout = qt.QVBoxLayout() self.info.setLayout(self.infoLayout) self.label = qt.QLabel(message, self.info) self.infoLayout.addWidget(self.label) qt.QTimer.singleShot(msec, self.info.close) self.info.exec_() def setUp(self): """ Do whatever is needed to reset the state - typically a scene clear will be enough. """ slicer.mrmlScene.Clear(0) def runTest(self): import traceback """Run as few or as many tests as needed here. """ self.setUp() self.testBrowserDownloadAndLoad() def testBrowserDownloadAndLoad(self): self.delayDisplay("Starting the test") widget = TCIABrowserWidget(None) widget.getCollectionValues() browserWindow = widget.browserWidget collectionsCombobox = browserWindow.findChildren('QComboBox')[0] print('Number of collections: {}'.format(collectionsCombobox.count)) if collectionsCombobox.count > 0: collectionsCombobox.setCurrentIndex(randint(0, collectionsCombobox.count - 1)) currentCollection = collectionsCombobox.currentText if currentCollection != '': print('connected to the server successfully') print('current collection: {}'.format(currentCollection)) tableWidgets = browserWindow.findChildren('QTableWidget') patientsTable = tableWidgets[0] if patientsTable.rowCount > 0: selectedRow = randint(0, patientsTable.rowCount - 1) selectedPatient = patientsTable.item(selectedRow, 0).text() if selectedPatient != '': print('selected patient: {}'.format(selectedPatient)) patientsTable.selectRow(selectedRow) studiesTable = tableWidgets[1] if studiesTable.rowCount > 0: selectedRow = randint(0, studiesTable.rowCount - 1) selectedStudy = studiesTable.item(selectedRow, 0).text() if selectedStudy != '': print('selected study: {}'.format(selectedStudy)) studiesTable.selectRow(selectedRow) seriesTable = tableWidgets[2] if seriesTable.rowCount > 0: selectedRow = randint(0, seriesTable.rowCount - 1) selectedSeries = seriesTable.item(selectedRow, 0).text() if selectedSeries != '': print('selected series to download: {}'.format(selectedSeries)) seriesTable.selectRow(selectedRow) pushButtons = browserWindow.findChildren('QPushButton') for pushButton in pushButtons: toolTip = pushButton.toolTip if toolTip[16:20] == 'Load': loadButton = pushButton if loadButton != None: loadButton.click() else: print('could not find Load button') else: print("Test Failed. No collection found.") scene = slicer.mrmlScene self.assertEqual(scene.GetNumberOfNodesByClass('vtkMRMLScalarVolumeNode'), 1) self.delayDisplay('Browser Test Passed!') <file_sep>/README.md TCIABrowser =========== ## Introduction TCIABrowser is a [3D Slicer](http://slicer.org/) module for browsing and downloading medical imaging collections from [The Cancer Imaging Archive (TCIA)](http://www.cancerimagingarchive.net/). See [documentation](Documentation.md) for more information. ![alt tag](TCIABrowser/Resources/Screenshot/Screenshot_1.png) ![alt tag](TCIABrowser/Resources/Screenshot/Screenshot_2.png) ## Acknowledgments This work is supported in part by the following National Institutes of Health grant: * Quantitative Image Informatics for Cancer Research [QIICR](http://qiicr.org/) (U24 CA180918, PIs Kikinis and Fedorov) * This project has been funded in whole or in part with Federal funds from the National Cancer Institute, National Institutes of Health, under Contract No. 75N91019D00024. The content of this publication does not necessarily reflect the views or policies of the Department of Health and Human Services, nor does mention of trade names, commercial products, or organizations imply endorsement by the U.S. Government. ## Contributors: * <NAME>, Brigham and Women's Hospital * <NAME>, Brigham and Women's Hospital * <NAME>, Georgetown University * <NAME>, Frederick National Laboratory for Cancer Research ## License * [Slicer License](https://github.com/Slicer/Slicer/blob/main/License.txt) <file_sep>/TCIABrowser/Testing/Python/Helper.py import qt, json, os, zipfile,dicom import unittest import slicer import TCIABrowserLib class Helper(object): def delayDisplay(self,message,msec=1000): # # logic version of delay display # print(message) self.info = qt.QDialog() self.infoLayout = qt.QVBoxLayout() self.info.setLayout(self.infoLayout) self.label = qt.QLabel(message,self.info) self.infoLayout.addWidget(self.label) qt.QTimer.singleShot(msec, self.info.close) self.info.exec_() def downloadSeries(self, TCIAClient): # Get collections try: responseString = TCIAClient.get_collection_values().read()[:] collections = json.loads(responseString) collectionsCount = len(collections) print ('Number of available collection(s): %d.'%collectionsCount) except Exception, error: raise Exception('Failed to get the collections!') return False # Get patients slicer.app.processEvents() collection = 'TCGA-GBM' print('%s was chosen.'%collection) try: responseString = TCIAClient.get_patient(collection = collection).read()[:] patients = json.loads(responseString) patientsCount = len(patients) print ('Number of available patient(s): %d'%patientsCount) except Exception, error: raise Exception('Failed to get patient!') return False patient = 'TCGA-06-0119' print('%s was chosen.'%patient) # Get studies slicer.app.processEvents() try: responseString = TCIAClient.get_patient_study(patientId = patient).read()[:] studies = json.loads(responseString) studiesCount = len(studies) print ('Number of available study(ies): %d'%studiesCount) except Exception, error: raise Exception('Failed to get patient study!') return False study = studies[0]['StudyInstanceUID'] print('%s was chosen.'%study) # Get series slicer.app.processEvents() try: responseString = TCIAClient.get_series(studyInstanceUID = study).read()[:] seriesCollection = json.loads(responseString) seriesCollectionCount = len(seriesCollection) print ('Number of available series: %d'%seriesCollectionCount) except Exception, error: raise Exception('Failed to get series!') return False series = seriesCollection[0]['SeriesInstanceUID'] print('%s was chosen.'%series) try: responseString = TCIAClient.get_series_size(series).read()[:] jsonResponse = json.loads(responseString) size = float(jsonResponse[0]['TotalSizeInBytes'])/(1024**2) print 'total size in bytes: %.2f MB'%size except Exception, error: raise Exception('Failed to get series size!') return False fileName = './images.zip' try: response = TCIAClient.get_image(seriesInstanceUid = series) slicer.app.processEvents() # Save server response as images.zip in current directory if response.getcode() == 200: destinationFile = open(fileName, "wb") bufferSize = 1024*512 print 'Downloading ', while 1: buffer = response.read(bufferSize) slicer.app.processEvents() if not buffer: break destinationFile.write(buffer) print 'X', destinationFile.close() print '... [DONE]' with zipfile.ZipFile(fileName) as zf: zipTest = zf.testzip() zf.close() destinationDir = './images/' if zipTest == None: with zipfile.ZipFile(fileName) as zf: zf.extractall(destinationDir) else: raise Exception('The zip file was corrupted!') return False dicomDir = './images/files/' firstFileName = os.listdir(dicomDir)[0] print 'Reading downloaded dicom images ....' ds = dicom.read_file(dicomDir + firstFileName) print 'downloaded Patient ID:', ds.PatientID print 'downloaded Study Instance UID:', ds.StudyInstanceUID print 'downloaded Series Instance UID:', ds.SeriesInstanceUID if str(ds.StudyInstanceUID) != str(study) or str(ds.SeriesInstanceUID) != str(series): print 'downloaded uids are not the same as requested' except Exception, error: print error raise Exception('Failed to get image!') return False # Test Passed return True <file_sep>/Documentation.md TCIABrowser Documentation ========================= ## Introduction and Acknowledgements Extension: **TCIABrowser** <br> Extension Category: Informatics <br> Acknowledgments: This work is funded by the National Institutes of Health, National Cancer Institute through the Grant Quantitative Image Informatics for Cancer Research (QIICR) (U24 CA180918) (PIs Kikinis and Fedorov). <br> Contributors: <NAME>(SPL), <NAME>(SPL), <NAME>(GU), <NAME>(FNLCR) <br> Contact: <NAME>, <email><EMAIL></email>; <NAME>, <email><EMAIL></email> <br> License: [Slicer License](https://github.com/Slicer/Slicer/blob/main/License.txt) <br> ## Module Description <img src="TCIABrowser.png" width="150"> The Cancer Imaging Archive (TCIA) hosts a large collection of Cancer medical imaging data which is available to the public through a programmatic interface (REST API). TCIA Browser is a Slicer module by which the user can connect to the TCIA archive, browse different collections, patient subjects, studies, and series, download the images, and visualize them in 3D Slicer.<br> [TCIA metrics dashboard](https://www.cancerimagingarchive.net/stats) provides extensive details on the types of imaging data by anatomy and other characteristics available within TCIA. ## Panels and their use 1. #### Settings > By opening the TCIABrowser module, it will show the settings. There are two settings currently available: Account and Storage Folder. > By default, the username field is filled by "nbia_guest" with an empty password field. > To browse and download public data, click "Login" and proceed. > To access the NLST(National Lung Screening Trial) dataset, check the "nlst" box and proceed with the default login information. > When the "nlst" box is checked, all entered account information will be discarded. > Click the folder box and change the path to change where images are downloaded. > To reset the storage folder back to its original location, click the "Reset Path" button. > When done using the browser, click "logout" to exit or click "Show Browser" to check other available datasets. > ![Settings Screenshot](TCIABrowser/Resources/Screenshot/Settings.png) > - A: Login area > - B: Storage location 2. #### Browsing Collections, Patients and Studies > After logging into an account, it will connect to the TCIA server and list all available collections. > Select a collection from the "Current Collection" combo box. > The browser will get the patient data from the TCIA server and populate the Patients table. > The use Cache checkbox will cache the query results on your hard drive, making further recurring queries faster. > The user can uncheck this box if a direct query from the TCIA server is desired. In the case of caching server responses, the latest access time is provided for each table separately. > Further selecting a patient will populate the study table for the selected one, and selecting a study will update the series table. > ![Downloading Data Screenshot](TCIABrowser/Resources/Screenshot/Downloading.png) > - A: Collection selector combobox > - B: Cache server response to the local storage > - C: Tables are expandable > - D: Status of the series (Available on local database / Available on TCIA server) > - E: Download and Index to the Slicer DICOM database (local storage) > - F: Download and load into the Slicer scene 3. #### Downloading Series > After selecting at least one series, the download icons will become activated. > Pressing the "Download and Index" button will download the images from TCIA to your computer and index the DICOM files inside the 3D Slicer DICOM database. > So you can review them, check the meta-data, and load them into the scene later with the Slicer DICOM module. > Pressing the "Download and Load" button will download and load the images into the Slicer scene. > You can select multiple items from all of the tables. > By holding the Ctrl key and clicking on different patients, the studies for all the selected ones will be added to the studies table. > You can select all the studies by pressing the 'Select All' button or make a specific selection by Ctrl+Click, and all the available series for download will be added to the series table. > At the final step, select series for download from the series table. > The total number of images for the selected series is indicated at the bottom right corner of the series table. > After pressing the download button, you can check the download status of each series at the 'Download Status' collapsible button at the module's widget. > While the download is in progress, you can still browse and add other series to the download queue or view the downloaded images in the 3D Slicer Scene. > ![Downloading Data Screenshot](TCIABrowser/Resources/Screenshot/Downloading.png) > - A: Progress bar showing the download status of the selected series > - B: Status bar showing the current process and the status of server responses > - C: Cancel downloads button ## Similar Modules - [SNATSlicer](https://github.com/NrgXnat/XNATSlicer.git) - [DICOM](https://slicer.readthedocs.io/en/latest/user_guide/modules/dicom.html) ## Reference - [Quantitative Image Informatics for Cancer Research (QIICR)](http://qiicr.org/) - [Quantitative Imaging Network (QIN)](https://imaging.cancer.gov/programs_resources/specialized_initiatives/qin/about/default.htm) - [TCIA Home Page](https://cancerimagingarchive.net/) - [TCIA Rest API Documentation](https://wiki.cancerimagingarchive.net/display/Public/TCIA+Programmatic+Interface+REST+API+Guides) - [Project page at NAMIC 2014 Project Week](http://www.na-mic.org/Wiki/index.php/2014_Project_Week:TCIA_Browser_Extension_in_Slicer) - [Rapid API page for testing TCIA API endpoint](https://rapidapi.com/tcia/api/the-cancer-imaging-archive/) ## Information for Developers **[Source Code](https://github.com/QIICR/TCIABrowser.git)** <br> Extension Dependencies: - [QuantitativeReporting](https://qiicr.gitbook.io/quantitativereporting-guide/) - [SlicerRT](http://slicerrt.github.io) Checking the API from the Python console: ``` import TCIABrowserLib as tblib client = tblib.TCIAClient.TCIAClient() response = client.get_collection_values() print(response_string) ``` <file_sep>/TCIABrowser/Util/reportStats.py from TCIAClient import * def getTCIASummary(fileName): # which attributes to keep track of seriesAttributes = ['SeriesInstanceUID','Modality','ProtocolName','SeriesDate','BodyPartExamined',\ 'AnnotationsFlag','Manufacturer','ImageCount'] summaryFile = open(fileName,'w') tcia_client = TCIAClient() print('Connected') response = tcia_client.get_collection_values() collectionsStr = response.read()[:] collections = [c['Collection'] for c in json.loads(collectionsStr)] import datetime startTime = datetime.datetime.now() for attr in seriesAttributes: summaryFile.write(attr+',') summaryFile.write('\n') for c in collections: response = tcia_client.get_patient(collection=c) patientsStr = response.read()[:] patients = [p['PatientID'] for p in json.loads(patientsStr)] print 'Collection ',c,' (total of ',len(patients),' patients)' for p in patients: response = tcia_client.get_patient_study(collection=c,patientId=p) studiesStr = response.read()[:] studies = [s['StudyInstanceUID'] for s in json.loads(studiesStr)] print ' Patient ',p,' (total of ',len(studies),' studies)' for s in studies: response = tcia_client.get_series(collection=c,studyInstanceUID=s) seriesStr = response.read()[:] series = json.loads(seriesStr) print ' Study ',s,' (total of ',len(series),' series)' for ser in series: for attr in seriesAttributes: try: summaryFile.write(str(ser[attr])+',') except: summaryFile.write('NA,') summaryFile.write('\n') endTime = datetime.datetime.now() print "Started: ",startTime.isoformat() print "Finished: ",endTime.isoformat() <file_sep>/TCIABrowser/TCIABrowserLib/TCIAClient.py import slicer, json, string, urllib.request, urllib.parse, urllib.error try: slicer.util.pip_install('tcia_utils -U -q') except: slicer.util.pip_install('tcia_utils') import tcia_utils.nbia #import TCIABrowserLib # # Refer https://wiki.cancerimagingarchive.net/display/Public/TCIA+Programmatic+Interface+REST+API+Guides for the API guide # class TCIAClient: def __init__(self, user = "nbia_guest", pw = "", nlst = False): if nlst: self.apiUrl = "nlst" elif user == "nbia_guest": self.apiUrl = "" else: self.apiUrl = "restricted" if self.apiUrl == "restricted": tcia_utils.nbia.getToken(user, pw) try: tcia_utils.nbia.api_call_headers != None self.exp_time = tcia_utils.nbia.token_exp_time except: self.credentialError = "Please check your credential and try again.\nFor more information, check the Python console." def get_collection_values(self): return tcia_utils.nbia.getCollections(api_url = self.apiUrl) def get_collection_descriptions(self): return tcia_utils.nbia.getCollectionDescriptions("nlst" if self.apiUrl == "nlst" else "") def get_patient(self, collection = None): return tcia_utils.nbia.getPatient(collection, api_url = self.apiUrl) def get_patient_study(self, collection = None, patientId = None, studyInstanceUid = None): return tcia_utils.nbia.getStudy(collection, patientId, studyInstanceUid, api_url = self.apiUrl) def get_series(self, collection = None, patientId = None, studyInstanceUID = None, seriesInstanceUID = None, modality = None, bodyPartExamined = None, manufacturer = None, manufacturerModel = None): return tcia_utils.nbia.getSeries(collection, patientId, studyInstanceUID, seriesInstanceUID, modality, bodyPartExamined, manufacturer, manufacturerModel, api_url = self.apiUrl) def get_image(self, seriesInstanceUid): queryParameters = {"SeriesInstanceUID": seriesInstanceUid} url = tcia_utils.nbia.setApiUrl("getImage", self.apiUrl) + "getImage?NewFileNames=Yes&%s" % urllib.parse.urlencode(queryParameters) headers = {"api_key": self.apiUrl} if self.apiUrl == "restricted": headers = headers | tcia_utils.nbia.api_call_headers request = urllib.request.Request(url = url, headers = headers) return urllib.request.urlopen(request) def get_seg_ref_series(self, seriesInstanceUid): refSeries = tcia_utils.nbia.getSegRefSeries(seriesInstanceUid) metadata = tcia_utils.nbia.getSeriesMetadata(refSeries, api_url = self.apiUrl)[0] fileSize = round(int(metadata["File Size"])/1048576, 2) return metadata["Series UID"], 0.01 if fileSize <= 0.01 else fileSize def logOut(self): tcia_utils.nbia.logoutToken(api_url = self.apiUrl)<file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 2.8.9) project(TCIABrowser) #----------------------------------------------------------------------------- set(EXTENSION_HOMEPAGE "https://github.com/QIICR/TCIABrowser/blob/master/") set(EXTENSION_CATEGORY "Informatics") set(EXTENSION_CONTRIBUTORS "<NAME>(SPL and BWH), <NAME> (SPL and BWH), <NAME> (GU), <NAME> (FNLCR)") set(EXTENSION_DESCRIPTION "A Module to download DICOM data from The Cancer Imaging Archive.") set(EXTENSION_ICONURL "https://raw.githubusercontent.com/QIICR/TCIABrowser/master/TCIABrowser/Resources/Icons/TCIABrowser.png") set(EXTENSION_SCREENSHOTURLS "https://raw.githubusercontent.com/QIICR/TCIABrowser/master/TCIABrowser/Resources/Screenshot/Screenshot_2.png") set(EXTENSION_DEPENDS QuantitativeReporting SlicerRT) #----------------------------------------------------------------------------- find_package(Slicer REQUIRED) include(${Slicer_USE_FILE}) #----------------------------------------------------------------------------- add_subdirectory(TCIABrowser) #----------------------------------------------------------------------------- include(${Slicer_EXTENSION_CPACK}) <file_sep>/TCIABrowser/Testing/Python/TCIABrowserModuleAPIV1Test.py import qt, json, os, zipfile,dicom import unittest import slicer import TCIABrowserLib from Helper import * class TCIABrowserModuleAPIV1Test(unittest.TestCase): def testAPIV3(self): helper = Helper() print 'Started API v1 Test...' helper.delayDisplay('API V1 Test Started') TCIAClient = TCIABrowserLib.TCIAClient(baseUrl='https://services.cancerimagingarchive.net/services/TCIA/TCIA/query') self.assertTrue(helper.downloadSeries(TCIAClient)) helper.delayDisplay('API V1 Test Passed')
27302d8fe27afacb2898a51d7ca99e89e3118571
[ "Markdown", "Python", "CMake" ]
10
CMake
QIICR/TCIABrowser
067a02ee902cdf5aa63e2c763a34baee686e893a
a8d335172b14dd8d3aef25ad7e20c935c678e603
refs/heads/master
<repo_name>397-F19/LabCat-Native<file_sep>/README.md ### LabCat-Native Too Lazy to write a useful README<file_sep>/screens/Profile.js import React, {useState, useEffect} from 'react'; import { StyleSheet, Dimensions, ScrollView, Image, ImageBackground, Platform, View, TouchableOpacity} from 'react-native'; import { Block, Text, theme } from 'galio-framework'; import { LinearGradient } from 'expo-linear-gradient'; import { Icon, Study } from '../components'; import { Images, materialTheme } from '../constants'; import { HeaderHeight } from "../constants/utils"; import db from '../firebase/fb'; const { width, height } = Dimensions.get('screen'); const thumbMeasure = (width - 48 - 32) / 3; export default function Profile() { const [studies, setStudies] = useState([]); const [users, setUsers] = useState([]); const [displayUpcomingStudies, updateDisplayUpcomingStudies] = useState(true); const renderData = () => { useEffect(() => { const handleStudies = snap => { let temp = Object.values(snap.val()); setStudies(temp); }; const handleUsers = snap => { let temp = Object.values(snap.val()); setUsers(temp); }; db.ref("studies").on("value", handleStudies, error => alert(error)); db.ref("users").on("value", handleUsers, error => alert(error)); return () => { db.ref("studies").off("value", handleStudies); db.ref("users").off("value", handleUsers); }; }, []); }; renderData(); const studyId = users.filter((x)=>x.uid == "001"); var currDate = new Date("11/01/2019 12:00"); var study = studyId[0]; var studyIds = []; var pastStudiesIds = []; var upcomingStudiesIds = []; var upcomingStudies = []; var pastStudies = []; if (study != undefined) { studyIds = Object.keys(study["studies"]); pastStudiesIds = studyIds.filter((x)=>new Date(study["studies"][x]["start"]) < currDate); upcomingStudiesIds = studyIds.filter((x)=>new Date(study["studies"][x]["start"]) >= currDate); upcomingStudies = studies.filter( function(x) { for (var i = 0; i < upcomingStudiesIds.length; i++) { if (x.sid == upcomingStudiesIds[i]) { return true; } } return false; } ); pastStudies = studies.filter( function(x) { for (var i = 0; i < pastStudiesIds.length; i++) { if (x.sid == pastStudiesIds[i]) { return true; } } return false; } ); } let listToDisplay; let listText; if (displayUpcomingStudies == true) { listToDisplay = upcomingStudies; listText = "Your Upcoming Studies" } else { listToDisplay = pastStudies; listText = "Your Past Studies" } return ( <Block flex style={styles.profile}> <Block flex> <ImageBackground source={{uri: Images.Profile}} style={styles.profileContainer} imageStyle={styles.profileImage}> <Block flex style={styles.profileDetails}> <Block style={styles.profileTexts}> <Text color="white" size={28} style={{ paddingBottom: 8 }}><NAME></Text> <Block row space="between"> <Block row> <Text color="white" size={16} muted style={styles.seller}>Student</Text> </Block> <Block> <Text color={theme.COLORS.MUTED} size={16}> <Icon name="map-marker" family="font-awesome" color={theme.COLORS.MUTED} size={16} /> {` `} Evanston, IL </Text> </Block> </Block> </Block> <LinearGradient colors={['rgba(0,0,0,0)', 'rgba(0,0,0,1)']} style={styles.gradient} /> </Block> </ImageBackground> </Block> <Block flex style={styles.options}> <ScrollView showsVerticalScrollIndicator={false}> <Block row space="between" style={{ padding: theme.SIZES.BASE, }}> <TouchableOpacity onPress={() => updateDisplayUpcomingStudies(true)} > <Block middle> <Text bold size={12} style={{marginBottom: 8}}>{upcomingStudiesIds.length}</Text> <Text muted size={12}>Upcoming Studies</Text> </Block> </TouchableOpacity> <TouchableOpacity onPress={() => updateDisplayUpcomingStudies(false)}> <Block middle> <Text bold size={12} style={{marginBottom: 8}}>{pastStudiesIds.length}</Text> <Text muted size={12}>Past Studies</Text> </Block> </TouchableOpacity> </Block> <Block row space="between" style={{ paddingVertical: 16, alignItems: 'baseline' }}> <Text size={16}>{listText}</Text> </Block> <Block style={{ paddingBottom: -HeaderHeight * 5 }}> <Block col space="between" style={{ flexWrap: 'wrap' }} > {listToDisplay.map(study => <Study key={study.title} study={study} style={{ marginRight: theme.SIZES.BASE }} />)} </Block> </Block> </ScrollView> </Block> </Block> ); } const styles = StyleSheet.create({ profile: { marginTop: Platform.OS === 'android' ? -HeaderHeight : 0, marginBottom: -HeaderHeight * 2, }, profileImage: { width: width * 1.1, height: 'auto', }, profileContainer: { width: width, height: height / 3, }, profileDetails: { paddingTop: theme.SIZES.BASE, justifyContent: 'flex-end', position: 'relative', }, profileTexts: { paddingHorizontal: theme.SIZES.BASE * 2, paddingVertical: theme.SIZES.BASE * 2, zIndex: 2 }, pro: { backgroundColor: materialTheme.COLORS.LABEL, paddingHorizontal: 6, marginRight: theme.SIZES.BASE / 2, borderRadius: 4, height: 19, width: 38, }, seller: { marginRight: theme.SIZES.BASE / 2, }, options: { position: 'relative', padding: theme.SIZES.BASE, marginHorizontal: theme.SIZES.BASE, marginTop: -theme.SIZES.BASE * 21, borderTopLeftRadius: 13, borderTopRightRadius: 13, backgroundColor: theme.COLORS.WHITE, shadowColor: 'black', shadowOffset: { width: 0, height: 0 }, shadowRadius: 8, shadowOpacity: 0.2, zIndex: 2, }, thumb: { borderRadius: 4, marginVertical: 4, alignSelf: 'center', width: thumbMeasure, height: thumbMeasure }, gradient: { zIndex: 1, left: 0, right: 0, bottom: 0, height: '30%', position: 'absolute', }, }); <file_sep>/screens/StudyPage.js import React, { useState, useEffect } from "react"; import { withNavigation } from "react-navigation"; import { StyleSheet, Dimensions, TouchableWithoutFeedback, ScrollView, Platform, SafeAreaView, Alert } from "react-native"; import { Block, Text, theme, Button } from "galio-framework"; import Hr from "react-native-hr-component"; import materialTheme from "../constants/Theme"; import { HeaderHeight } from "../constants/utils"; import COLORS from "galio-framework/src/theme/colors"; import db from "../firebase/fb"; import * as LocalAuthentication from 'expo-local-authentication'; import * as Permissions from "expo-permissions"; import * as Calendar from "expo-calendar"; const { width, height } = Dimensions.get("screen"); const StudyPage = ({ navigation }) => { const study = navigation.getParam("study"); const [ registerStudy, setRegisterStudy ] = useState(null); const [ calendar, setCalendar ] = useState(null); const authCalendar = async () => { const { status } = await Permissions.askAsync(Permissions.CALENDAR); if (status === 'granted') { const calendars = await Calendar.getCalendarsAsync(); setCalendar(calendars); } }; useEffect(()=> { if (registerStudy !== null && calendar !== null) { const startDate = new Date(registerStudy.start); const offset = []; calendar.map(tmp => { if (tmp.title === 'Calendar'){ const cid = tmp.id; const details = { "title" : study.title, "startDate" : startDate, "endDate" : new Date(registerStudy.end), "location" : study.location, "alarms": [ {relativeOffset: -1440 } ] }; const calid = Calendar.createEventAsync(cid,details); } }) } }, [{registerStudy, calendar}]); const handlePress = event => { var uid = "001"; var now = new Date(); let time = event.times; let availableTime = time.filter(x => new Date(x.start) > now); const newPostKey = db .ref("users") .child(uid) .child("studies") .child(event.sid); Alert.alert( "Available Time", "please select an available time", [ ...availableTime.map(x => ({ text: `${x.start} to ${x.end}`, onPress: async() => { try { let results = await LocalAuthentication.authenticateAsync(); if (results.success) { newPostKey.set(x); setRegisterStudy(x); await authCalendar(); Alert.alert("Register Success"); } else { Alert.alert(results.error); } } catch (e) { console.log(e); } } })), { text: "Cancel", onPress: () => console.log("Cancel Pressed"), style: "cancel" } ], { cancelable: false } ); }; return ( <SafeAreaView style={styles.container}> <ScrollView showsVerticalScrollIndicator={true} style={styles.studies} maximumZoomScale={2} minimumZoomScale={1} bouncesZoom={true} > <Block center style={styles.studyTitle}> <Text h4 style={styles.textBase}> {study.title} </Text> </Block> <Hr lineColor="#eee" width={width - theme.SIZES.BASE} text={"✨"} /> <Block flex style={styles.studyContent}> <Text p style={styles.textContent}> <Text p style={styles.textKey}> Description: </Text>{" "} {study.description} </Text> </Block> <Block flex style={styles.studyContent}> <Text p style={styles.textContent}> <Text p style={styles.textKey}> Location: </Text>{" "} {study.location} </Text> </Block> <Block flex style={styles.studyContent}> <Text p style={styles.textContent}> <Text p style={styles.textKey}> Payment: </Text>{" "} {study.payment} </Text> </Block> <Block center style={styles.studyButton}> <Button round size="small" onPress={() => handlePress(study)}> Register Study! </Button> </Block> </ScrollView> </SafeAreaView> ); }; export default StudyPage; const styles = StyleSheet.create({ container: { flex: 1, marginTop: HeaderHeight, height: height }, studies: { width: width, paddingVertical: theme.SIZES.BASE, paddingHorizontal: theme.SIZES.BASE * 2, backgroundColor: theme.COLORS.WHITE, height: height - HeaderHeight, marginTop: 15 }, studyTitle: { marginTop: theme.SIZES.BASE, width: width - theme.SIZES.BASE, marginHorizontal: 20, marginBottom: 20 }, textBase: { fontFamily: "Cochin", fontWeight: "bold" }, textContent: { fontFamily: "Georgia", lineHeight: 25, textAlign: "justify" }, textKey: { fontWeight: "bold" }, studyContent: { width: width - theme.SIZES.BASE * 4, marginVertical: 10 }, studyButton: { marginTop: 25, marginBottom: 30 } }); console.disableYellowBox = true; <file_sep>/App.js /*! ========================================================= * Material Kit React Native - v1.4.0 ========================================================= * Product Page: https://demos.creative-tim.com/material-kit-react-native/ * Copyright 2019 Creative Tim (http://www.creative-tim.com) * Licensed under MIT (https://github.com/creativetimofficial/material-kit-react-native/blob/master/LICENSE) ========================================================= * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ import React, {useState} from 'react'; import { Platform, StatusBar, Image } from 'react-native'; import { AppLoading } from 'expo'; import { Asset } from 'expo-asset'; import { Block, GalioProvider } from 'galio-framework'; import AppContainer from './navigation/Screens'; import { Images, studies, materialTheme } from './constants/'; import db from './firebase/fb'; // cache app images const assetImages = [ Images.Pro, Images.Profile, Images.Avatar, Images.Onboarding, ]; // cache study images studies.map(study => assetImages.push(study.image)); function cacheImages(images) { return images.map(image => { if (typeof image === 'string') { return Image.prefetch(image); } else { return Asset.fromModule(image).downloadAsync(); } }); } export default function App() { [isLoadingComplete,setloading] = useState(false); [skiploadingscreen, setskip] = useState(false) if (isLoadingComplete && skiploadingscreen) { return ( <AppLoading startAsync={_loadResourcesAsync} onError={_handleLoadingError} onFinish={_handleFinishLoading} /> ); } else { return ( <GalioProvider theme={materialTheme}> <Block flex> {Platform.OS === 'ios' && <StatusBar barStyle="default" />} <AppContainer /> </Block> </GalioProvider> ); } const _loadResourcesAsync = async () => { return Promise.all([ ...cacheImages(assetImages), ]); }; const _handleLoadingError = error => { // In this case, you might want to report the error to your error // reporting service, for example Sentry console.warn(error); }; const _handleFinishLoading = () => { setloading(true); }; }
1d577e6c287f49da4ba95439f8442bfa5cded122
[ "Markdown", "JavaScript" ]
4
Markdown
397-F19/LabCat-Native
10452674edf955927eaeea7e4d101d905100cbd5
218b4b1e06bdfc4455829eb4efccf7968c1aa9fb
refs/heads/master
<file_sep>package com.solvetech.engvr.back.spring.security.impl; import com.solvetech.engvr.back.common.constant.EngvrBackConstants; import com.solvetech.engvr.core.common.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.SecurityMetadataSource; import org.springframework.security.access.intercept.AbstractSecurityInterceptor; import org.springframework.security.access.intercept.InterceptorStatusToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * <br/> * create time 2017年4月11日 下午3:21:17 * * @author t0mpi9 */ public class EngvrFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter { private final static Logger logger = LoggerFactory.getLogger(EngvrFilterSecurityInterceptor.class); private FilterInvocationSecurityMetadataSource securityMetadataSource; public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() { return securityMetadataSource; } public void setSecurityMetadataSource(FilterInvocationSecurityMetadataSource securityMetadataSource) { this.securityMetadataSource = securityMetadataSource; } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { FilterInvocation fi = new FilterInvocation(request, response, chain); try { invoke(fi); HttpServletRequest httpServletRequest = fi.getHttpRequest(); String url = httpServletRequest.getContextPath() + httpServletRequest.getServletPath(); logger.info("请求的url为: {}", url); String sessionSelectedUrl = httpServletRequest.getServletPath().substring(0, httpServletRequest.getServletPath().lastIndexOf("/")); if (StringUtils.isNotEmpty(sessionSelectedUrl)) { httpServletRequest.getSession().setAttribute(EngvrBackConstants.KEY_SESSION_SELECTED_URL, sessionSelectedUrl.substring(1)); } } finally { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { Object object = authentication.getPrincipal(); if (object != null && object instanceof EngvrUserDetail) { EngvrUserDetail userDetail = (EngvrUserDetail) object; request.setAttribute(EngvrBackConstants.KEY_SESSION_USER, userDetail); } } } } private void invoke(FilterInvocation fi) throws IOException, ServletException { InterceptorStatusToken token = super.beforeInvocation(fi); try { fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } finally { super.finallyInvocation(token); } super.afterInvocation(token, null); } @Override public void destroy() { } @Override public Class<?> getSecureObjectClass() { return FilterInvocation.class; } @Override public SecurityMetadataSource obtainSecurityMetadataSource() { return this.securityMetadataSource; } } <file_sep># spring-security-demo 基于Spring Security权限管理的管理项目demo <file_sep>package com.solvetech.engvr.back.test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * <br/> * create time 2017年4月13日 下午2:55:07 * * @author t0mpi9 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath*:application.xml" }) public class TestBase { } <file_sep>package com.solvetech.engvr.back.test.service; import com.solvetech.engvr.back.test.TestBase; import com.solvetech.engvr.core.back.service.EngvrBackMenuService; import com.solvetech.engvr.core.entity.mybatis.EngvrBackMenu; import com.solvetech.engvr.core.exception.EngvrException; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; /** * <br/> * create time 2017年4月13日 下午2:54:22 * * @author t0mpi9 */ public class TestEngvrBackMenuService extends TestBase{ @Autowired private EngvrBackMenuService engvrBackMenuService; @Test public void testGetMenuListByUsername() throws EngvrException{ List<EngvrBackMenu> menus = engvrBackMenuService.getMenuListByUsername("admin"); System.err.println(menus.size()); } @Test public void testGetRoleMenuList() throws EngvrException{ engvrBackMenuService.getRoleMenuList(); } } <file_sep>package com.solvetech.engvr.back.spring.security.impl; import com.alibaba.fastjson.JSONObject; import com.solvetech.engvr.back.common.constant.EngvrBackConstants; import com.solvetech.engvr.core.back.service.EngvrBackMenuService; import com.solvetech.engvr.core.back.service.EngvrBackUserService; import com.solvetech.engvr.core.common.util.HttpUtils; import com.solvetech.engvr.core.entity.mybatis.EngvrBackMenu; import com.solvetech.engvr.core.exception.EngvrException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.List; @Component public class EngvrAuthenticationSuccessHandler implements AuthenticationSuccessHandler { private static final Logger logger = LoggerFactory.getLogger(EngvrAuthenticationSuccessHandler.class); private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Autowired private EngvrBackUserService engvrBackUserService; @Autowired private EngvrBackMenuService engvrBackMenuService; @Override public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { EngvrUserDetail userDetail = (EngvrUserDetail) authentication.getPrincipal(); logger.info("用户: {}, 登录成功", userDetail.getUsername()); Integer userId = userDetail.getId(); String loginIp = HttpUtils.getIpAddress(httpServletRequest); try { engvrBackUserService.updateLoginInfoById(loginIp, userId); } catch (EngvrException e) { logger.error("更新用户{}登录ip异常", userDetail.getUsername(), e); } HttpSession httpSession = httpServletRequest.getSession(); if(httpSession != null){ List<EngvrBackMenu> menus = null; try { menus = engvrBackMenuService.getMenuListByUsername(userDetail.getUsername()); } catch (EngvrException e) { logger.error("获取用户的菜单异常", e); } httpSession.setAttribute(EngvrBackConstants.KEY_SESSION_MENUS, JSONObject.toJSONString(menus)); } redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, "/index"); } } <file_sep>package com.solvetech.engvr.back.spring.security.impl; import org.springframework.security.authentication.encoding.BasePasswordEncoder; import org.springframework.stereotype.Component; import com.solvetech.engvr.core.common.util.ShaUtils; @Component public class EngvrPasswordEncoder extends BasePasswordEncoder { @Override public String encodePassword(String rawPass, Object salt) { return ShaUtils.SHA1(this.mergePasswordAndSalt(rawPass, salt, false)); } /** * encPass本地密码,rawPass用户输入密码 */ @Override public boolean isPasswordValid(String encPass, String rawPass, Object salt) { return encPass.equals(encodePassword(rawPass, salt)); } @Override protected String mergePasswordAndSalt(String password, Object salt, boolean strict) { return salt + password; } } <file_sep>package com.solvetech.engvr.back.user.vo; import com.solvetech.engvr.core.common.util.StringUtils; import com.solvetech.engvr.core.exception.EngvrException; import java.io.Serializable; /** * 获取角色列表请求VO<br/> * Created on 2017/6/21 22:00. * * @author zhubenle */ public class RoleRequestVO implements Serializable{ private Integer id; private String name; private String description; public void validateParams() throws EngvrException{ if(StringUtils.isEmpty(name) || StringUtils.isEmpty(description)){ throw new EngvrException("参数不能为空!"); } } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } <file_sep>package com.solvetech.engvr.back.user.vo; import java.io.Serializable; /** * back用户列表请求实体<br/> * create time 2017年4月14日 上午11:30:01 * * @author t0mpi9 */ public class BackUserListRequestVO implements Serializable { /** * */ private static final long serialVersionUID = 609973672724186714L; private String phone; private String username; private String realName; private String email; private String startDate; private String endDate; public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } } <file_sep>package com.solvetech.engvr.back.common.constant; /** * 后台常量 * @author zhubenle * */ public class EngvrBackConstants { /** * session中存放的所有菜单列表的key */ public final static String KEY_SESSION_MENUS = "menus"; /** * session存放的用户key */ public final static String KEY_SESSION_USER = "user"; /** * 页面上选择的菜单url的key */ public final static String KEY_SESSION_SELECTED_URL = "selected_url"; /** * 后台添加用户的默认密码 */ public final static String DEFAULT_PASSWORD = "<PASSWORD>"; } <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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.solvetech.engvr</groupId> <artifactId>engvr-back</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>engvr-back Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <jdk-version>1.8</jdk-version> <spring-security-version>4.2.2.RELEASE</spring-security-version> </properties> <dependencies> <dependency> <groupId>org.sitemesh</groupId> <artifactId>sitemesh</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>com.solvetech.engvr</groupId> <artifactId>engvr-core</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>${spring-security-version}</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring-security-version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring-security-version}</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-taglibs</artifactId> <version>${spring-security-version}</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <finalName>engvr-back</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.2.15.v20160210</version> <configuration> <httpConnector> <port>8080</port> <idleTimeout>60000</idleTimeout> </httpConnector> <scanIntervalSeconds>60</scanIntervalSeconds> <webApp> <contextPath>/powermall</contextPath> </webApp> <war>/target/engvr.war</war> <scanTargets> <scanTarget>src/main</scanTarget> <scanTarget>src/test</scanTarget> </scanTargets> <scanTargetPatterns> <scanTargetPattern> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> <excludes> <exclude>**/myspecial.xml</exclude> <exclude>**/myspecial.properties</exclude> </excludes> </scanTargetPattern> <scanTargetPattern> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> <excludes> <exclude>**/myspecial.xml</exclude> <exclude>**/myspecial.properties</exclude> </excludes> </scanTargetPattern> </scanTargetPatterns> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>${jdk-version}</source> <target>${jdk-version}</target> </configuration> </plugin> </plugins> </pluginManagement> </build> </project> <file_sep>package com.solvetech.engvr.back.spring.security.impl; import com.alibaba.fastjson.JSONObject; import com.solvetech.engvr.back.common.constant.EngvrBackConstants; import com.solvetech.engvr.core.back.service.EngvrBackMenuService; import com.solvetech.engvr.core.back.service.EngvrBackUserService; import com.solvetech.engvr.core.common.util.HttpUtils; import com.solvetech.engvr.core.entity.mybatis.EngvrBackMenu; import com.solvetech.engvr.core.exception.EngvrException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.List; /** * <br/> * create time 2017年4月25日 上午10:27:29 * * @author t0mpi9 */ public class EngvrRememberMeServices extends TokenBasedRememberMeServices { private final static Logger logger = LoggerFactory.getLogger(EngvrRememberMeServices.class); @Autowired private EngvrBackUserService engvrBackUserService; @Autowired private EngvrBackMenuService engvrBackMenuService; public EngvrRememberMeServices(String key, UserDetailsService userDetailsService) { super(key, userDetailsService); } @Override protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { UserDetails userDetails = super.processAutoLoginCookie(cookieTokens, httpServletRequest, httpServletResponse); EngvrUserDetail userDetail = (EngvrUserDetail) userDetails; logger.info("用户: {}, 用户通过记住登录成功", userDetail.getUsername()); Integer userId = userDetail.getId(); String loginIp = HttpUtils.getIpAddress(httpServletRequest); try { engvrBackUserService.updateLoginInfoById(loginIp, userId); } catch (EngvrException e) { logger.error("更新用户{}登录ip异常", userDetail.getUsername(), e); } HttpSession httpSession = httpServletRequest.getSession(); if(httpSession != null){ List<EngvrBackMenu> menus = null; try { menus = engvrBackMenuService.getMenuListByUsername(userDetail.getUsername()); } catch (EngvrException e) { logger.error("获取用户的菜单异常", e); } httpSession.setAttribute(EngvrBackConstants.KEY_SESSION_MENUS, JSONObject.toJSONString(menus)); } return userDetails; } } <file_sep>package com.solvetech.engvr.back.spring.security.impl; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.session.SessionAuthenticationException; import org.springframework.stereotype.Component; import com.solvetech.engvr.core.common.constant.EngvrConstants; import com.solvetech.engvr.core.common.vo.EngvrResponseCode; import com.solvetech.engvr.core.common.vo.EngvrResponseVO; @Component public class EngvrAuthenticationFailureHandler implements AuthenticationFailureHandler { private static final Logger logger = LoggerFactory.getLogger(EngvrAuthenticationFailureHandler.class); private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Override public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException authenticationexception) throws IOException, ServletException { logger.info(authenticationexception.getMessage()); HttpSession httpSession = httpServletRequest.getSession(); if (httpSession != null) { if (authenticationexception instanceof UsernameNotFoundException) { httpSession.setAttribute(EngvrConstants.ENGVR_RESPONSE_VO, EngvrResponseVO.failuer(EngvrResponseCode.USERNAME_ERROR)); } else if (authenticationexception instanceof BadCredentialsException) { httpSession.setAttribute(EngvrConstants.ENGVR_RESPONSE_VO, EngvrResponseVO.failuer(EngvrResponseCode.PASSWORD_ERROR)); } else if (authenticationexception instanceof EngvrCapchaErrorException) { httpSession.setAttribute(EngvrConstants.ENGVR_RESPONSE_VO, EngvrResponseVO.failuer(EngvrResponseCode.CAPTCHA_ERROR)); }else if (authenticationexception instanceof SessionAuthenticationException) { httpSession.setAttribute(EngvrConstants.ENGVR_RESPONSE_VO, EngvrResponseVO.failuer(EngvrResponseCode.MAX_SESSION_ERROR)); } } redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, "/login.jsp"); } } <file_sep>package com.solvetech.engvr.back.upload.controller; import com.solvetech.engvr.back.base.controller.BaseController; import com.solvetech.engvr.back.upload.service.UploadService; import com.solvetech.engvr.core.exception.EngvrException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.commons.CommonsMultipartFile; /** * 上传文件控制器<br/> * Created on 2017/6/8 22:15. * * @author zhubenle */ @Controller public class UploadController extends BaseController{ private final static Logger logger = LoggerFactory.getLogger(UploadController.class); @Autowired private UploadService uploadService; @RequestMapping(value = "ajax/upload/picture") @ResponseBody public String uploadPicture(@RequestParam("picture") CommonsMultipartFile picture) { String result = null; try { result = uploadService.uploadPictureToQiNiu(picture); } catch (EngvrException e) { logger.error("上传图片到七牛异常: {}", e); result = e.getMessage(); } return result; } } <file_sep>package com.solvetech.engvr.back.spring.security.impl; import org.springframework.security.core.AuthenticationException; /** * 验证码异常类,在EngvrAuthenticationFailureHandler中能被捕获处理<br/> * create time 2017年4月11日 下午6:16:49 * * @author t0mpi9 */ public class EngvrCapchaErrorException extends AuthenticationException { /** * */ private static final long serialVersionUID = 414165928722022872L; public EngvrCapchaErrorException(String msg) { super(msg); } public EngvrCapchaErrorException(String msg, Throwable t) { super(msg, t); } } <file_sep>package com.solvetech.engvr.back.spring.security.impl; import com.solvetech.engvr.core.common.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * 验证验证码<br/> * create time 2017年4月11日 下午5:12:45 * * @author t0mpi9 */ public class EngvrAuthenticationFilter extends UsernamePasswordAuthenticationFilter { private final static Logger logger = LoggerFactory.getLogger(EngvrAuthenticationFilter.class); public final static String SPRING_SECURITY_FORM_CAPTCHA_KEY = "captcha"; public final static String SPRING_SECURITY_SESSION_CAPTCHA_KEY = "session_captcha"; public static final String SPRING_SECURITY_LAST_USERNAME_KEY = "last_username"; private String captchaParamter = SPRING_SECURITY_FORM_CAPTCHA_KEY; private boolean verifyCaptcha = true; @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { HttpSession httpSession = request.getSession(); logger.info("验证码验证开关状态为: {}", verifyCaptcha); if (verifyCaptcha) { if (StringUtils.isEmpty(obtainRequestCaptcha(request)) || !obtainRequestCaptcha(request).equals(obtainSessionCaptcha(request))) { if (httpSession != null && super.getAllowSessionCreation()) { httpSession.setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY, super.obtainUsername(request)); } throw new EngvrCapchaErrorException("验证码错误"); } } return super.attemptAuthentication(request, response); } protected String obtainRequestCaptcha(HttpServletRequest request) { return request.getParameter(captchaParamter); } protected String obtainSessionCaptcha(HttpServletRequest request) { return (String) request.getSession().getAttribute(SPRING_SECURITY_SESSION_CAPTCHA_KEY); } public String getCaptchaParamter() { return captchaParamter; } /** * 页面中验证码参数名称 * * @param captchaParamter */ public void setCaptchaParamter(String captchaParamter) { this.captchaParamter = captchaParamter; } public boolean isVerifyCaptcha() { return verifyCaptcha; } /** * 是否校验验证码, 默认true * * @param verifyCaptcha */ public void setVerifyCaptcha(boolean verifyCaptcha) { this.verifyCaptcha = verifyCaptcha; } } <file_sep>package com.solvetech.engvr.back.spring.security.impl; import com.solvetech.engvr.core.back.service.EngvrBackRoleService; import com.solvetech.engvr.core.back.service.EngvrBackUserService; import com.solvetech.engvr.core.entity.mybatis.EngvrBackRole; import com.solvetech.engvr.core.entity.mybatis.EngvrBackUser; import com.solvetech.engvr.core.exception.EngvrException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; 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.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Collection; import java.util.List; @Service public class EngvrUserDetailService implements UserDetailsService { private static final Logger logger = LoggerFactory.getLogger(EngvrUserDetailService.class); @Autowired private EngvrBackUserService engvrBackUserService; @Autowired private EngvrBackRoleService engvrBackRoleService; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { EngvrBackUser user; EngvrUserDetail engvrUserDetail = null; Collection<GrantedAuthority> auths = new ArrayList<>(); try { user = engvrBackUserService.getUserByUsername(s); if(user == null){ throw new UsernameNotFoundException("用户" + s + "不存在"); } //创建UserDetail对象,并将EngvrBackUser对象里面属性值copy过去 engvrUserDetail = new EngvrUserDetail(); BeanUtils.copyProperties(user, engvrUserDetail); //遍历本地看获取的角色,添加到spring的角色列表中 List<EngvrBackRole> roles = engvrBackRoleService.getRoleListByUsername(s); for(EngvrBackRole role : roles){ GrantedAuthority authority = new SimpleGrantedAuthority(role.getName()); auths.add(authority); } engvrUserDetail.setAuthorities(auths); } catch (EngvrException e) { logger.error("获取用户 :{} 的信息异常", s, e); } return engvrUserDetail; } }
023c4b14fd795b85fc650f8e95e4d0d3e88fbf24
[ "Markdown", "Java", "Maven POM" ]
16
Java
zhubenle/spring-security-demo
8815475433607de20535df56f9233a5cb9f3517e
46c83f2a5fd563fdc565480ee2a75ba38df27319
refs/heads/master
<file_sep>import static org.junit.jupiter.api.Assertions.*; /** * @author Giovanni * @version 1.0 * @since 06/06/2020 - 20:13 * @category Test */ class PessoaTest { Pessoa pessoa = new Pessoa(); @org.junit.jupiter.api.BeforeEach void setUp() { pessoa.setNome("Giovanni"); pessoa.setIdade(17); } @org.junit.jupiter.api.AfterEach void tearDown() { } @org.junit.jupiter.api.Test void calcularIdade() { assertEquals(204,pessoa.calcularIdade()); } }<file_sep>import java.lang.reflect.Array; /** * @author Giovanni * @version 1.0 * @since 07/06/2020 - 15:44 * @category View */ public class Principal { public static void main(String[] args) { String[] nomes = new String[3]; nomes[0] = "Giovanni"; nomes[1] = "Marcos"; nomes[2] = "Andreia"; /* //foreach / para cada for(String nome : nomes) { System.out.println(nome); } //for for(int indice = 0 ; indice <nomes.length ; indice ++) { System.out.println(nomes[indice]); } */ //inserindo os valores ao criar String[] nomess = {"\nGiovanni", "Não sei", "Não sei 2"}; /* //for for(int indice = 0 ; indice <nomess.length ; indice ++) { System.out.println(nomess[indice]); } Array.set(nomess, 1, "Mario"); //foreach / para cada for(String nome : nomess) { System.out.println(nome); } */ int[] numeros = new int[3]; numeros[0] = 100; numeros[1] = 200; numeros[2] = 300; System.out.println("\nPrimeira Posição: " + numeros[0]); /* //for for(int indice = 0 ; indice <numeros.length ; indice ++) { System.out.println(numeros[indice]); } //foreach for(int numero : numeros) { System.out.println(numero); } //Fim das variáveis unidimensionais. */ //matriz int[][] matriz = new int[3][3]; //quadratica. /* matriz[0][0] = 1; matriz[0][1] = 1; matriz[0][2] = 1; matriz[1][0] = 2; matriz[1][1] = 2; matriz[1][2] = 2; matriz[2][0] = 3; matriz[2][1] = 3; matriz[2][2] = 3; */ // for(int linha = 0 ; linha < 3 ; linha++) { // for(int coluna = 0 ; coluna < 3 ; coluna++) { // matriz[linha] [coluna] = 0; // } // } for (int linha = 0; linha < 3; linha++) { for (int coluna = 0; coluna < 3; coluna++) { //diagonal principal if (linha == coluna) { matriz[linha][coluna] = 1; } else { matriz[linha][coluna] = 0; } } } for(int linha = 0 ; linha < 3 ; linha++) { for(int coluna = 0 ; coluna < 3 ; coluna++) { System.out.print(" " + matriz[linha] [coluna] + " "); } System.out.print("\n"); } /* Coluna Linha 1 1 1 2 2 2 3 3 3 */ } } <file_sep>/** * Author <NAME> * Version 1.0 * Since 01/06/2020 00:35 * Category Model */ public class Aluno { private String nome; private double nota1; private double nota2; public Aluno() { } /** * @param Recebe o nome da pessoa * @param Recebe a nota1 da pessoa * @param Recebe a nota2 da pessoa */ public Aluno(String nome,double nota1, double nota2) { this.nome = nome; this.nota1 = nota1; this.nota2 = nota2; } public String getNome() { return this.nome; } public void setNome(String nome) { this.nome = nome; } public double getNota1() { return this.nota1; } public void setNota1(double nota1) { this.nota1 = nota1; } public double getNota2() { return this.nota2; } public void setNota2(double nota2) { this.nota2 = nota2; } /** * return Retorna a média entre nota1 e nota2; */ public double calcularMediaAritmetica() { return (this.nota1 + this.nota2) /2; } /** * return Retornar Aprovado ou Reprovado de acordo com a média aritmetica */ public String mostrarNotaFinal() { if (this.calcularMediaAritmetica() >=6) { return "Aprovado!"; } return "Reprovado!"; } @Override public String toString() { return "Seu nome: " + this.nome + "\nNota1: " + this.nota1 + "\nNota2: " + this.nota2 + "\nMédia: " + this.calcularMediaAritmetica() + "\nResultado final: " + this.mostrarNotaFinal(); } }<file_sep>import java.util.Scanner; /** * @author Giovanni * @version 1.0 * @since 06/06/2020 - 19:32 * @category View */ public class Principal { //psvm + TAB public static void main(String[] args) { Scanner scanner = new Scanner(System.in); //sout + TAB System.out.println("OI"); Pessoa pessoa = new Pessoa(); System.out.println("Dígite seu nome: "); pessoa.setNome(scanner.nextLine()); System.out.println("Dígite seu nome: "); pessoa.setIdade(scanner.nextInt()); pessoa.calcularIdade(); System.out.println(pessoa); } } <file_sep>import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * A classe de teste MesTest. * * @author Giovanni * @version 1.0 */ public class MesTest { /** * Construtor default para a classe de teste MesTest */ public MesTest() { } Mes mes = new Mes(); @Before public void setUp() { mes.setNumero(1); } /** * Tears down the test fixture. * * Chamado após cada método de teste de caso. */ @After public void tearDown() { } @Test public void testRetornarMeses() { assertEquals("Janeiro", mes.retornarMeses()); mes.setNumero(0); assertEquals("Não encontrado", mes.retornarMeses()); mes.setNumero(2); assertEquals("Fevereiro", mes.retornarMeses()); mes.setNumero(3); assertEquals("Março", mes.retornarMeses()); mes.setNumero(4); assertEquals("Abril", mes.retornarMeses()); mes.setNumero(5); assertEquals("Maio", mes.retornarMeses()); mes.setNumero(6); assertEquals("Junho", mes.retornarMeses()); mes.setNumero(7); assertEquals("Julho", mes.retornarMeses()); mes.setNumero(8); assertEquals("Agosto", mes.retornarMeses()); mes.setNumero(9); assertEquals("Setembro", mes.retornarMeses()); mes.setNumero(10); assertEquals("Outubro", mes.retornarMeses()); mes.setNumero(11); assertEquals("Novembro", mes.retornarMeses()); mes.setNumero(12); assertEquals("Dezembro", mes.retornarMeses()); } } <file_sep>import org.w3c.dom.ls.LSOutput; import java.util.HashSet; import java.util.Set; /** * @author Giovanni * @version 1.0 * @since 07/06/2020 - 17:53 * @category View */ public class Principal { public static void main(String[] args) { Set<String> nomes = new HashSet<>(); nomes.add("Giovanni"); nomes.add("Giovanni"); nomes.add("Davi"); nomes.add("Marquito"); nomes.add("Marquito"); //foreach for(String nome : nomes) { System.out.println(nome); } //JDK8... 9,10, 11, 12 lambda - forma abreviada de fazer as coisas //produtivos... //legivel.. (legitividade abalada de tão abreviado) //pode ser usar IT ao invés de nome //lambda nomes.forEach(nome -> System.out.println(nome)); nomes.forEach(System.out::println); //foreach for(String nome : nomes) { if(nome.contains("o")) { //filtro System.out.println(nome); } } //lambda nomes.stream().filter(nome -> nome.contains("o")).forEach(System.out::println); } } <file_sep># projetos-logica Projetos de Lógica WEBIII <file_sep>/** * @author <NAME> * @version 1.0 * @since 29/05/2020 - 11:42 */ import java.util.Scanner; public class Principal { public static void main(String args[]) { System.out.println("\f"); Scanner scanner = new Scanner(System.in); Mes mes = new Mes(); System.out.println("Dígite o número do mês que procura: "); mes.setNumero(scanner.nextInt()); System.out.println(mes); System.out.println("\nDígite o número do mês que procura: "); int numero = scanner.nextInt(); Mes mes1 = new Mes(numero); System.out.println(mes1); } }
531dfd10ddd59c763924fa21e8059ba8cc65ad7d
[ "Markdown", "Java" ]
8
Java
Giovanni-Flores/projetos-logica
032497c6de751cd23e2578889cdf7735cee59478
8a8c5edf5731fc8dcebe30fb3255ea68444a48d0
refs/heads/master
<file_sep># proj354.oroshi A little website for a school project <file_sep>// Scroll to 'about' $('#view-about').on('click',function(){ const about = $('#about').position().top; $('html, body').animate( { scrollTop: about }, 900 ); }); // Scroll to 'team' $('#view-team').on('click',function(){ const team = $('#team').position().top; $('html, body').animate( { scrollTop: team }, 900 ); }); // Scroll to 'docs' $('#view-docs').on('click',function(){ const docs = $('#docs').position().top; $('html, body').animate( { scrollTop: docs }, 900 ); }); // Scroll button var scrollBtn = document.getElementById('top-btn'); // If user scrolls more than 20px, display button window.onscroll = function () {showButton()}; function showButton() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20){ scrollBtn.style.display = 'block'; } else { scrollBtn.style.display = 'none'; } } // Scroll to top if button clicked $('#top-btn').on('click', function(){ $('html, body').animate( { scrollTop: 0 } ) })
5e2fb61efa11695366ddc40988a8b236650df77e
[ "Markdown", "JavaScript" ]
2
Markdown
muli-ca/proj354.oroshi
759a7ab50fa8f5c8e2ac619a46aa4f7c028d824d
7a74d402d87e89a743d94ada086e53233e52399d
refs/heads/master
<file_sep># ASIA_Unity_106051053_SinEn 亞洲大學-Unity期末-106051053-郭欣恩 <file_sep>using UnityEngine; public class ZombieContrl : MonoBehaviour { #region 欄位區域 public Rigidbody ZombieRidge; public Animator ZombiAnime; [Tooltip("移動速度")][Range(0.1f,10f)] public float speed; [Tooltip("旋轉速度")][Range(0.1f,200f)] public float turnSpeed; #endregion #region 方法區域 /// <summary> /// 跑步方法 /// </summary> private void Run() { if (Input.GetButton("Vertical")) { transform.Translate(0, 0, speed * Input.GetAxis("Vertical") * Time.deltaTime); ZombiAnime.SetFloat("MoveSpeed", Input.GetAxis("Vertical")); } } /// <summary> /// 旋轉方法 /// </summary> private void Turn() { if (Input.GetButton("Horizontal")) { transform.Rotate(0,turnSpeed*Input.GetAxis("Horizontal") * Time.deltaTime, 0); } } /// <summary> /// 攻擊方法 /// </summary> private void Attack() { if (Input.GetButton("Fire1")) { ZombiAnime.SetTrigger("Attack"); Debug.Log("Fire"); } } /// <summary> /// 撿東西方法 /// </summary> private void PickUp() { } #endregion void Update() { Run(); Turn(); Attack(); } }
02c4dc824144aabceddd8509e64754d9b43bf5d5
[ "Markdown", "C#" ]
2
Markdown
law4981006/ASIA_Unity_106051053_SinEn
e49d15b25be8c3bef5f3f8fc150a501b9b49bbb8
cec28608d3c6b514be9eb541a236f21635e34916
refs/heads/main
<repo_name>rodrigowue/spice-arc-extractor<file_sep>/transistor.h #ifndef TRANSISTOR_H #define TRANSISTOR_H #include <iostream> #include <string> using namespace std; class Transistor { string alias; string source; string drain; string gate; string bulk; string type; //PMOS,NMOS,LVT,HVT double diff_width; int fingers; double gate_lenght; int stack; public: Transistor(); Transistor(string alias, string source, string drain, string gate, string bulk, string type, double diff_width, int fingers, double gate_lenght, int stack); void set_alias(string alias); void set_source(string source); void set_drain(string drain); void set_gate(string gate); void set_bulk(string bulk); void set_type(string type); void set_diff_width(double width); void set_fingers(int fingers); void set_gate_lenght(double gate_lenght); void set_stack(int stack); string get_alias(); string get_source(); string get_drain(); string get_gate(); string get_bulk(); string get_type(); double get_diff_width(); int get_fingers(); double get_gate_lenght(); int get_stack(); }; #endif <file_sep>/transistor.cpp #include "transistor.h" #include <string> Transistor::Transistor(string alias, string source, string drain, string gate, string bulk, string type, double diff_width, int fingers, double gate_lenght, int stack){ Transistor::alias = alias; Transistor::source = source; Transistor::drain = drain; Transistor::gate = gate; Transistor::bulk = bulk; Transistor::type = type; Transistor::diff_width = diff_width; Transistor::fingers = fingers; Transistor::gate_lenght = gate_lenght; Transistor::stack = stack; } void Transistor::set_alias(string alias){ Transistor::alias = alias; } void Transistor::set_source(string source){ Transistor::source = source; } void Transistor::set_drain(string drain){ Transistor::drain = drain; } void Transistor::set_gate(string gate){ Transistor::gate = gate; } void Transistor::set_bulk(string bulk){ Transistor::bulk = bulk; } void Transistor::set_type(string type){ Transistor::type = type; } void Transistor::set_diff_width(double width){ Transistor::diff_width = diff_width; } void Transistor::set_fingers(int fingers){ Transistor::fingers = fingers; } void Transistor::set_gate_lenght(double gate_lenght){ Transistor::gate_lenght = gate_lenght; } void Transistor::set_stack(int stack){ Transistor::stack = stack; } string Transistor::get_alias( ){ return Transistor::alias; } string Transistor::get_source( ){ return Transistor::source; } string Transistor::get_drain( ){ return Transistor::drain; } string Transistor::get_gate( ){ return Transistor::gate; } string Transistor::get_bulk( ){ return Transistor::bulk; } string Transistor::get_type( ){ return Transistor::type; } double Transistor::get_diff_width( ){ return Transistor::diff_width; } int Transistor::get_fingers( ){ return Transistor::fingers; } double Transistor::get_gate_lenght( ){ return Transistor::gate_lenght; } int Transistor::get_stack( ){ return Transistor::stack; } <file_sep>/main.cpp #include <iostream> #include <fstream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sstream> #include <vector> #include <iterator> #include <algorithm> #include <unordered_set> #include <bits/stdc++.h> #include "transistor.h" #include "map.h" using namespace std; int main(int argc, char** argv) { string line; string subcircuit; char delim[]=" "; vector<string> power_pins; vector<string> ground_pins; vector<string> pins; vector<string> in_pins; vector<string> out_pins; vector<string> common_nets; vector<string> arcs; vector<Transistor> PDN; vector<Transistor> PUN; if (argc < 1 ){ cout << "call: ./main [*].sp" << endl; } ifstream myfile (argv[1]); if (0==(myfile.is_open())){ cout << "Cannot open file:" << argv[1] << endl; } print_logo(); while(getline(myfile,line)){ stringstream lineStream(line); string token; lineStream >> token; //------------------------------------------------------------------ // IF FIRST LINE TOKEN == "*.pininfo" //------------------------------------------------------------------ //------------------------------------------------------------------ //IF FIRST LINE TOKEN STARTS WITH "M" (Transistor) //------------------------------------------------------------------ if((token == ".SUBCKT") | (token == ".subckt")){ //cout << "--------------------------------------\n" << "Fetching Pinage Information\n"; lineStream >> token; subcircuit = token; cout << "Subcircuit:" << token << endl; while(lineStream >> token) { if ((token == "VDD")|(token == "vdd")|(token == "VPWR")|(token == "VPB")|(token == "VPP")) {; power_pins.push_back(token); //cout << "vdd:" << token << endl; } else if((token == "GND")|(token == "gnd")|(token == "VSS")|(token == "vss")|(token == "VGND")|(token == "VNB")|(token == "VBB")){ ground_pins.push_back(token); //cout << "gnd:" << token << endl; } else { pins.push_back(token); //cout << "pin:" << token << endl; } } } else if((token[0]=='M')|(token[0]=='m')|(token[0]=='X')|(token[0]=='x')){ string alias; string source; string drain; string gate; string bulk; string type; //PMOS,NMOS,LVT,HVT double diff_width; int fingers=0; double gate_lenght; int stack = 1; char * tail; alias = token; lineStream >> token; source = token; lineStream >> token; gate = token; lineStream >> token; drain = token; lineStream >> token; bulk = token; lineStream >> token; type = token; /* cout << "Transistor: " << endl; cout << "Alias:" << alias << endl; cout << "Source:" << source << endl; cout << "Gate:" << gate << endl; cout << "Drain:" << drain << endl; cout << "Bulk:" << bulk << endl; cout << "Type:" << type << endl; */ while(lineStream >> token){ if ((token.find("L=") != string::npos)|token.find("l=") != string::npos) { token.erase(token.begin(),token.begin()+2); gate_lenght = strtod(token.c_str(),&tail); //cout << "Gate Lenght: " << gate_lenght << endl; } else if ((token.find("W=") != string::npos)|(token.find("w=") != string::npos)) { token.erase(token.begin(),token.begin()+2); diff_width = strtod(token.c_str(),&tail); //cout << "Width: " << diff_width << endl; } else if ((token.find("F=") != string::npos)|(token.find("f=") != string::npos)) { token.erase(token.begin(),token.begin()+2); fingers = atoi(token.c_str()); //cout << "Fingers: " << fingers << endl; } } if((type[0]=='P')|(type[0]=='p')|(type.find("pfet") != string::npos)|(type.find("pch") != string::npos)|(type.find("P12") != string::npos)){ Transistor p_transistor(alias, source, drain, gate, bulk, type, diff_width, fingers, gate_lenght, stack); PUN.push_back(p_transistor); //cout << "PMOS ADDED TO PUN LIST" << endl; } else{ Transistor n_transistor(alias, source, drain, gate, bulk, type, diff_width, fingers, gate_lenght, stack); PDN.push_back(n_transistor); //cout << "NMOS ADDED TO PDN LIST" << endl; } } else{ } } /*int x=0; cout << "----------------------------------------" << endl; cout << "PMOS:" << endl; for (auto it = begin(PUN); it != end(PUN); ++it){ cout << x << ":" << it->get_alias() << " " << it->get_source() << " " << it->get_gate() << " " << it->get_drain() << endl; x++; } cout << "NMOS:" << endl; for (auto it = begin(PDN); it != end(PDN); ++it){ cout << x << ":" << it->get_alias() << " " << it->get_source() << " " << it->get_gate() << " " << it->get_drain() << endl; x++; }*/ //Get All PDN and PUN Common Nodes common_nets = fetch_common_nets(PDN,PUN); //Remove Common Nodes from the pin list in_pins = pins; distribute_pins(common_nets, in_pins, out_pins); //Print Inputs and Outputs cout << "----------------------------------------" << endl; cout << "Inputs & Outputs\n" << endl; for (auto it = begin(in_pins); it != end(in_pins); ++it){ cout << "input:" << *it << endl; } for (auto it = begin(out_pins); it != end(out_pins); ++it){ cout << "output:" << *it << endl; } cout << "----------------------------------------" << endl; //circuit columns is the amount of common nets in a circuit int circuit_columns = common_nets.size(); //find the expression for the PUN vector<string> pun_expressions = find_expression(circuit_columns, common_nets, PUN, power_pins, ground_pins); //print results for the pull up network cout << "PUN Expressions:" << endl; for(int i = 0; i < pun_expressions.size(); i++){ cout << common_nets[i] << "=" << pun_expressions[i] << endl; } //find the expression for the PDN vector<string> pdn_expressions = find_expression(circuit_columns, common_nets, PDN, power_pins, ground_pins); //print results for the pull down network cout << "\nPDN Expressions:" << endl; for(int i = 0; i < pdn_expressions.size(); i++){ cout << common_nets[i] << "=" << pdn_expressions[i] << endl; } //Merge PUN and PDN expressions vector<string> expressions; for(int i = 0; i < pun_expressions.size(); i++){ //expressions.push_back("!("+pun_expressions[i]+"*"+pdn_expressions[i]+")"); expressions.push_back("!(" + pdn_expressions[i]+")"); } //Deal with sequetial string expression; if (expressions.size()==1){ expression = expressions.front(); } else{ expression = flatten_expression(common_nets,expressions); } cout << "----------------------------------------" << endl; cout << "Expression After Flattening: \n" << expression << endl; cout << "----------------------------------------" << endl; cout << "TRUTH TABLE:" << endl; truth_table(in_pins, expression); cout << "----------------------------------------" << endl; cout << "ARCS:" << endl; arcs = find_arcs(in_pins, expression); cout << "----------------------------------------" << endl; ofstream out_file(subcircuit + ".arcs"); out_file << in_pins.size() << " "; for (auto it = begin(pins); it != end(pins); ++it){ out_file << *it << " " ; } out_file << endl; for (auto it = begin(arcs); it != end(arcs); ++it){ out_file << *it << endl; } out_file.close(); return 0; } <file_sep>/README.md # LEX - SPICE STD-CELL ARCS EXTRACTOR ``` ____ ___ ____ _ _____ / ___||_ )/ ___| / \ | ____| \___ \ / /| | / _ \ | _| ___) /___| |___ / ___ \| |___ |____/ \____|/_/ \_\_____| SPICE STD-CELL ARCS EXTRACTOR [UNDER DEVELOPMENT] ``` This tool is ment to extract arcs from Pull-Down (PDN) and Pull-up Networks (PUN) while analysing a node-graph representation. To run: ``` make ./s2cae <spice file> ``` or ``` g++ main.cpp map.cpp transistor.cpp ./a.out <spice file> ``` By running the spice_files/nand3.sp example the tool outputs: ``` ====================================== SPICE STD-CELL ARCS EXTRACTOR [UNDER DEVELOPMENT] ====================================== Subcircuit:NAND3D0BWP input:A input:B input:C output:OUT ---------------------------------------- PDN Expression: (C*(A*B)) PUN Expression: (C+(A+B)) ---------------------------------------- Expression: !((C+(A+B))*(C*(A*B))) ---------------------------------------- TRUTH TABLE: 000|1 100|1 010|1 110|1 001|1 101|1 011|1 111|0 ARCS: Number of literals: 3 1 1 F | Rise 1 F 1 | Rise F 1 1 | Rise R 1 1 | Fall 1 R 1 | Fall 1 1 R | Fall ---------------------------------------- ``` A <*>.arcs file is generated as an output. This tool is currently feeding a characterization tool that is being developed under the following repo: https://github.com/rodrigowue/DPAC <file_sep>/map.cpp #include "map.h" #include "transistor.h" #include <unordered_set> #include <bits/stdc++.h> #include <vector> #include <math.h> using namespace std; void print_logo(){ cout << "======================================" << endl; cout << " SPICE STD-CELL TIMING ARCS EXTRACTOR" << endl; cout << " [UNDER DEVELOPMENT]" << endl; cout << "======================================" << endl; }; void print_transistor(Transistor& t1){ cout << "-------------------------" << endl; cout << "Alias:" << t1.get_alias() << endl; cout << "source:" << t1.get_source() << endl; cout << "gate:" << t1.get_gate() << endl; cout << "drain:" << t1.get_drain() << endl; cout << "-------------------------" << endl; }; vector<string> fetch_common_nets(vector<Transistor>& PDN, vector<Transistor>& PUN){ vector<string> common_nets; for (Transistor p_transistor : PUN){ string p_src = p_transistor.get_source(); string p_dra = p_transistor.get_drain(); for (Transistor n_transistor : PDN){ string n_src = n_transistor.get_source(); string n_dra = n_transistor.get_drain(); if (p_src == n_src){ //cout << p_src << "=" << n_src << endl; common_nets.push_back(p_src); } else if(p_src == n_dra){ //cout << p_src << "=" << n_dra << endl; common_nets.push_back(p_src); } else if(p_dra == n_src){ //cout << p_dra << "=" << n_src << endl; common_nets.push_back(p_dra); } else if(p_dra == n_dra){ //cout << p_dra << "=" << n_dra << endl; common_nets.push_back(p_dra); } else{ } } } //Remove Duplicates sort(common_nets.begin(), common_nets.end()); common_nets.erase(std::unique(common_nets.begin(), common_nets.end()), common_nets.end()); return common_nets; } vector<string> remove_pin(vector<string> pin_list, string pin){ for (auto it_rm = begin(pin_list); it_rm != end(pin_list); ){ if (*it_rm == pin){ //cout << "deleting " << *it_rm << " from the list" << endl; pin_list.erase(it_rm); } else{ it_rm++; } } return pin_list; } void distribute_pins(vector<string>& common_nets, vector<string>& in_pins, vector<string>& out_pins){ for (string common_net: common_nets){ for (string pin : in_pins){ if(common_net == pin){ in_pins = remove_pin(in_pins, pin); out_pins.push_back(pin); if (in_pins.size() == 1){ break; } else{ distribute_pins(common_nets, in_pins, out_pins); break; } } } } return; }; // ----------------------------------------------------------------------------------- // CHECKS // ----------------------------------------------------------------------------------- bool check_parallel(Transistor& A, Transistor& B){ if ((( A.get_source() == B.get_source() ) && ( A.get_drain() == B.get_drain())) | (( A.get_drain() == B.get_source() ) && ( A.get_source() == B.get_drain()))){ return true; } else{ return false; } } bool check_common_net(Transistor& T0, string& common_net){ if (((T0.get_source() == common_net)|(T0.get_drain() == common_net))){ return true; } else{ return false; } } bool check_pg_pin(string pin, vector<string> power_pins, vector<string> ground_pins){ for (string power_pin : power_pins){ if(pin == power_pin){ return false; } } for (string ground_pin : ground_pins){ if(pin == ground_pin){ return false; } } return true; } bool check_series(Transistor& A, Transistor& B, vector<string> power_pins, vector<string> ground_pins){ string a_src = A.get_source(); string b_src = B.get_source(); string a_dra = A.get_drain(); string b_dra = B.get_drain(); if ( (( a_src == b_src ) & (check_pg_pin(a_src, power_pins, ground_pins)) & (a_dra != b_dra)) | (( a_src == b_dra ) & (check_pg_pin(a_src, power_pins, ground_pins)) & (a_dra != b_src)) | (( a_dra == b_src ) & (check_pg_pin(a_dra, power_pins, ground_pins)) & (a_src != b_dra)) | (( a_dra == b_dra ) & (check_pg_pin(a_dra, power_pins, ground_pins)) & (a_src != a_src)) ){ return true; } else{ return false; } } // ----------------------------------------------------------------------------------- // FLATTENING // ----------------------------------------------------------------------------------- Transistor merge_parallel(Transistor& A, Transistor& B){ string type = ""; string alias = ""; string bulk = ""; string source = ""; string drain = ""; int fingers = 0; double diff_width = 0.0; double gate_lenght = 0.0; int stack = A.get_stack(); alias.append("("); alias.append(A.get_gate()); alias.append("+"); alias.append(B.get_gate()); alias.append(")"); source = A.get_source(); drain = A.get_drain(); Transistor group_transistor(alias, source , drain, alias, bulk, type, diff_width, fingers, gate_lenght, stack); return group_transistor; } Transistor merge_series(Transistor& A, Transistor& B, vector<string>& power_pins, vector<string>& ground_pins){ string type = ""; string alias = ""; string source = ""; string bulk = ""; string drain = ""; int fingers=0; double diff_width = 0.0; double gate_lenght = 0.0; int stack = A.get_stack() + B.get_stack(); string a_src = A.get_source(); string b_src = B.get_source(); string a_dra = A.get_drain(); string b_dra = B.get_drain(); //set alias for the new gate alias.append("("); alias.append(A.get_gate()); alias.append("*"); alias.append(B.get_gate()); alias.append(")"); //Find the connecting point and preserve the connection if ( a_src == b_src){ source = a_dra; drain = b_dra; } else if(a_src == b_dra){ source = b_src; drain = a_dra; } else if(a_dra == b_src){ source = a_src; drain = b_dra; } else{ source = a_src; drain = b_src; } Transistor group_transistor(alias, source, drain, alias, bulk, type, diff_width, fingers, gate_lenght, stack); return group_transistor; } vector<Transistor> collapse_parallel(int circuit_columns, vector<Transistor>& transistor_network){ for (int i = 0; i < transistor_network.size() - 1; i++) { Transistor& t1 = transistor_network[i]; for (int j = i + 1; j < transistor_network.size(); j++) { Transistor& t2 = transistor_network[j]; if ((check_parallel(t1,t2))){ Transistor group_transistor = merge_parallel(t1, t2); transistor_network.push_back(group_transistor); // insert the merged item transistor_network.erase(transistor_network.begin() + j); transistor_network.erase(transistor_network.begin() + i); if(transistor_network.size() == circuit_columns){ return transistor_network; } else{ i = -1; break; } } } } return transistor_network; } vector<Transistor> collapse_series(int circuit_columns, vector<Transistor>& transistor_network, vector<string>& power_pins, vector<string>& ground_pins){ for (int i = 0; i < transistor_network.size() - 1; i++) { Transistor& t1 = transistor_network[i]; for (int j = i + 1; j < transistor_network.size(); j++) { Transistor& t2 = transistor_network[j]; if ((check_series(t1, t2, power_pins, ground_pins))){ Transistor group_transistor = merge_series(t1, t2, power_pins, ground_pins); transistor_network.push_back(group_transistor); // insert the merged item transistor_network.erase(transistor_network.begin() + j); transistor_network.erase(transistor_network.begin() + i); if(transistor_network.size() == circuit_columns){ return transistor_network; } else{ i = -1; break; } } } } return transistor_network; } vector<string> find_expression(int circuit_columns, vector<string> common_nets, vector<Transistor> transistor_network, vector<string>& power_pins, vector<string>& ground_pins){ vector<string> expressions; vector<Transistor> temp_transistor_network = transistor_network; //collapse until its is done int it_count = 0; while ((temp_transistor_network.size() > circuit_columns) & (it_count < 1000)){ //Find Parrallel Transistors and Collapse them into Pseudo Transistors collapse_parallel(circuit_columns, temp_transistor_network); //If the number of pseudo transistors is the same as the amount of common nets if(temp_transistor_network.size() == circuit_columns){ break; } else{ //Find Series Transistors and Collapse them into Pseudo Transistors collapse_series(circuit_columns, temp_transistor_network, power_pins, ground_pins); } it_count++; } for(string common_net: common_nets){ for(int i = 0; i < temp_transistor_network.size(); i++){ //print_transistor(temp_transistor_network[i]); //cout << common_net << endl; if(check_common_net(temp_transistor_network[i], common_net)){ temp_transistor_network[i].set_alias(temp_transistor_network[i].get_gate()); expressions.push_back(temp_transistor_network[i].get_alias()); } } } return expressions; } string flatten_expression(vector<string> common_nets, vector<string> expressions){ string expression = expressions.front(); if (expressions.size() > 1){ for (int i = 0 ; i < common_nets.size(); i++){ for (int j = 0; j < expressions.size(); ++j){ if(expressions[j].find(common_nets[i]) != string::npos){ //cout << "j:" << expressions[j] << endl; //cout << "exp:" << expressions.at(i) << endl; //cout << "commo:" << common_nets.at(i) << endl; string temp = expressions[j]; string what_it_is = common_nets.at(i); string what_it_will_be = expressions.at(i); replace_all(temp, what_it_is, what_it_will_be); expressions.erase(expressions.begin() + j); expressions.erase(expressions.begin() + i); expressions.push_back(temp); return flatten_expression(common_nets, expressions); } } } } return expression; } // ----------------------------------------------------------------------------------- // SOLVER // ----------------------------------------------------------------------------------- int solve_boolean_expression(string expression){ if (expression.size() > 1){ replace_all(expression, "0+0", "0"); replace_all(expression, "0+1", "1"); replace_all(expression, "1+0", "1"); replace_all(expression, "1+1", "1"); replace_all(expression, "0*0", "0"); replace_all(expression, "0*1", "0"); replace_all(expression, "1*0", "0"); replace_all(expression, "1*1", "1"); replace_all(expression, "!1", "0"); replace_all(expression, "!(1)", "0"); replace_all(expression, "!0", "1"); replace_all(expression, "!(0)", "1"); replace_all(expression, "(0)", "0"); replace_all(expression, "(1)", "1"); return solve_boolean_expression(expression); } else{ return atoi(expression.c_str()); } return atoi(expression.c_str()); } void replace_all( std::string& s, std::string const& toReplace, std::string const& replaceWith ) { std::string buf; std::size_t pos = 0; std::size_t prevPos; // Reserves rough estimate of final size of string. buf.reserve(s.size()); while (true) { prevPos = pos; pos = s.find(toReplace, pos); if (pos == std::string::npos) break; buf.append(s, prevPos, pos - prevPos); buf += replaceWith; pos += toReplace.size(); } buf.append(s, prevPos, s.size() - prevPos); s.swap(buf); } // ----------------------------------------------------------------------------------- // ARC FINDER // ----------------------------------------------------------------------------------- vector<string> find_arcs(vector<string> in_pins, string expression){ vector<string> arcs; string expr = expression; unordered_set<char> literals; char temp_input = 'A'; for(string pin: in_pins){ replace_all(expr, pin, string(1,temp_input)); literals.insert(temp_input); temp_input++; } int numLiterals = literals.size(); cout << "Number of literals: " << numLiterals << endl; int maxVal = 1 << numLiterals; bool values[numLiterals]; for (int i = 0; i < maxVal; i++) { // Set the values of the literals int t = i; int j = 0; for (char c : literals) { values[j++] = t & 1; t >>= 1; } // Evaluate the boolean expression string local_expression = expr; for (size_t i = 0; i < local_expression.size(); ++i) { int it = 0; for (char c : literals) { if (local_expression[i] == char(c)) { local_expression.replace(i, 1, to_string(values[it])); } it++; } } bool result = solve_boolean_expression(local_expression); //bool result = !((values[0] + values[1]) * (values[0] * values[1])); // Check for transition arcs int k = 0; for (char c : literals) { int t = i ^ (1 << k); int l = 0; for (char d : literals) { values[l++] = t & 1; t >>= 1; } string local_expression = expr; for (size_t i = 0; i < local_expression.size(); ++i) { int it = 0; for (char c : literals) { if (local_expression[i] == char(c)) { local_expression.replace(i, 1, to_string(values[it])); } it++; } } //cout << local_expression << endl; bool newResult = solve_boolean_expression(local_expression); if (newResult != result) { int counter = 0; string arc = ""; for(char c1: literals){ if(c1 == c){ if (values[k]) { cout << "F"; arc += "F"; } else { cout << "R"; arc += "R"; } } else{ cout << values[counter]; if (values[counter] == 1){ arc += "1"; } else{ arc += "0"; } } counter++; cout << " " ; } cout << " | "; if (newResult) { cout << "Fall"; arc += "F"; } else { cout << "Rise"; arc += "R"; } arcs.push_back(arc); cout << endl; } k++; } } return arcs; } vector<string> truth_table(vector<string> in_pins, string expression){ vector<string> arcs; int counter = 0; int amount_of_inputs = pow(2,(in_pins.size())); while (counter < amount_of_inputs){ string local_expression = expression; for (auto it = begin(in_pins); (it != end(in_pins)); ++it){ int index = it - in_pins.begin(); int teste = (counter >> index) & 1; replace_all(local_expression, *it, to_string(teste)); cout << teste; } if (solve_boolean_expression(local_expression) == 1){ cout << "|" << 1 << endl; } else{ cout << "|" << 0 << endl; } counter++; } return arcs; }<file_sep>/map.h #ifndef MAP_H #define MAP_H #include "transistor.h" #include <vector> using namespace std; //------------------------- CLI ------------------------------------------- void print_logo(); void print_transistor(Transistor& t1); //------------------------- Pin Related ----------------------------------- vector<string> fetch_common_nets(vector<Transistor>& PDN, vector<Transistor>& PUN); vector<string> remove_pin(vector<string> pin_list, string pin); void distribute_pins(vector<string>& common_nets, vector<string>& in_pins, vector<string>& out_pins); //-------------------------Checks------------------------------------------ bool check_parallel(Transistor& A, Transistor& B); bool check_common_net(Transistor& T0, string& common_net); bool check_pg_pin(string pin, vector<string> power_pins, vector<string> ground_pins); bool check_series(Transistor& A, Transistor& B, vector<string> power_pins, vector<string> ground_pins); //------------------------- Flattening ------------------------------------ //-- find and merge parallel Transistor merge_parallel(Transistor& A, Transistor& B); vector<Transistor> collapse_parallel(int circuit_columns, vector<Transistor>& transistor_network); //-- find and merge parallel Transistor merge_series(Transistor& A, Transistor& B, vector<string>& power_pins, vector<string>& ground_pins); vector<Transistor> collapse_series(int circuit_columns, vector<Transistor>& transistor_network, vector<string>& power_pins, vector<string>& ground_pins); // find the expression. vector<string> find_expression(int circuit_columns, vector<string> common_nets, vector<Transistor> transistor_network, vector<string>& power_pins, vector<string>& ground_pins); string flatten_expression(vector<string> common_nets, vector<string> expressions); //------------------------- Boolean Solver -------------------------------- int solve_boolean_expression(string expression); // ------------------------- Truth Table --------------------------------- vector<string> truth_table(vector<string> in_pins, string expression); // ------------------------- Finding ARCS --------------------------------- vector<string> find_arcs(vector<string> in_pins, string expression); // ------------------------- Misc --------------------------------- void replace_all(std::string& s, std::string const& toReplace, std::string const& replaceWith); #endif <file_sep>/Makefile CXX := g++ CXX_FLAGS := -std=c++17 -ggdb BIN := bin SRC := src INCLUDE := include LIBRARIES := map.cpp transistor.cpp EXECUTABLE := s2cae all: $(EXECUTABLE) run: ./$(EXECUTABLE) $(EXECUTABLE): *.cpp $(CXX) $(CXX_FLAGS) main.cpp $(LIBRARIES) -o $(EXECUTABLE) clean: -rm $(EXECUTABLE)
cb0e672bbe0b43756b2d59f40925fecefd076bc2
[ "Markdown", "Makefile", "C++" ]
7
C++
rodrigowue/spice-arc-extractor
c30729ce7af9357a9f1deb13017deea959548743
58c66360ac29ba33f409749beb26f70dea522a3e
refs/heads/master
<file_sep><?php $this->layout = 'photoalbum'; $thumbs_params = array("format" => "jpg", "height" => 150, "width" => 150, "class" => "thumbnail inline"); function array_to_table($array) { $saved_error_reporting = error_reporting(0); echo "<table class='info'>"; foreach ($array as $key => $value) { if ($key != 'class') { if ($key == 'url' || $key == 'secure_url') { $display_value = '"' . $value . '"'; } else { $display_value = json_encode($value); } echo "<tr><td>" . $key . ":</td><td>" . $display_value . "</td></tr>"; } } echo "</table>"; error_reporting($saved_error_reporting); } ?> <script type='text/javascript'> $(function () { $('.toggle_info').click(function () { $(this).closest('.photo').toggleClass('show_more_info'); return false; }); }); </script> <h1>Welcome!</h1> <p> This is the main demo page of the PhotoAlbum sample PHP application of Cloudinary.<br /> Here you can see all images you have uploaded to this PHP application and find some information on how to implement your own PHP application storing, manipulating and serving your photos using Cloudinary! </p> <p> All of the images you see here are transformed and served by Cloudinary. For instance, the logo and the poster frame. They are both generated in the cloud using the Cloudinary shortcut functions: fetch_image_tag and facebook_profile_image_tag. These two pictures weren't even have to be uploaded to Cloudinary, they are retrieved by the service, transformed, cached and distributed through a CDN. </p> <h1>Your Images</h1> <div class="photos"> <p> Following are the images uploaded by you. You can also upload more pictures. You can click on each picture to view its original size, and see more info about and additional transformations. <?php echo $this->Html->link('Upload Images...', array('controller' => 'photos', 'action' => 'upload'), array('class' => 'upload_link')); ?> </p> <?php if (sizeof($photos) == 0) { ?> <p>No images were uploaded yet.</p> <?php } foreach ($photos as $photo) { ?> <div class="photo"> <a href="<?php echo cloudinary_url($photo["Photo"]["cloudinaryIdentifier"]) ?>" target="_blank" class="public_id_link"> <?php echo "<div class='public_id'>" . $photo["Photo"]["cloudinaryIdentifier"] . "</div>"; echo cl_image_tag($photo["Photo"]["cloudinaryIdentifier"], array_merge($thumbs_params, array("crop" => "fill"))); ?> </a> <div class="less_info"> <a href="#" class="toggle_info">More transformations...</a> </div> <div class="more_info"> <a href="#" class="toggle_info">Hide transformations...</a> <table class="thumbnails"> <?php $thumbs = array( array("crop" => "fill", "radius" => 10), array("crop" => "scale"), array("crop" => "fit", "format" => "png"), array("crop" => "thumb", "gravity" => "face"), array("override" => true, "format" => "png", "angle" => 20, "transformation" => array("crop" => "fill", "gravity" => "north", "width" => 150, "height" => 150, "effect" => "sepia") ), ); foreach($thumbs as $params) { $merged_params = array_merge((\Cloudinary::option_consume($params, "override")) ? array() : $thumbs_params, $params); echo "<td>"; echo "<div class='thumbnail_holder'>"; echo "<a target='_blank' href='" . cloudinary_url($photo["Photo"]["cloudinaryIdentifier"], $merged_params) . "'>" . cl_image_tag($photo["Photo"]["cloudinaryIdentifier"], $merged_params) . "</a>"; echo "</div>"; echo "<br/>"; array_to_table($merged_params); echo "</td>"; } ?> </table> <div class="note"> Take a look at our documentation of <a href="http://cloudinary.com/documentation/image_transformations" target="_blank">Image Transformations</a> for a full list of supported transformations. </div> </div> </div> <?php } ?> </div> <file_sep><?php App::uses('ModelBehavior', 'Model'); class CloudinaryBehavior extends ModelBehavior { public $settingsDefaults = array( "fields" => array(), "changeModelDefaults" => true ); public function setup(Model $Model, $settings = array()) { if (!isset($this->settings[$Model->alias])) { $this->settings[$Model->alias] = $this->settingsDefaults; } $this->settings[$Model->alias] = array_merge( $this->settings[$Model->alias], (array)$settings ); if ($this->settings[$Model->alias]['changeModelDefaults']) { $this->changeModelDefaults($Model); } } /// Callbacks /// public function afterFind(Model $Model, $results, $primary = false) { $fieldNames = $this->relevantFields($Model); if (!$fieldNames) { return $results; } foreach ($results as &$result) { foreach ($fieldNames as $fieldName) { $this->updateCloudinaryField($Model, $fieldName, $result); } } return $results; } public function beforeSave(Model $Model, $options = array()) { foreach ($this->relevantFields($Model, $options) as $fieldName) { $this->saveCloudinaryField($Model, $fieldName); } return true; } public function beforeValidate(Model $Model, $options = array()) { foreach ($this->relevantFields($Model, $options) as $fieldName) { $field = @$Model->data[$Model->alias][$fieldName]; if (is_string($field) && $field) { if (!(new CloudinaryField($field))->verify()) { $Model->invalidate($fieldName, "Bad cloudinary signature!"); return false; } } } return true; } /// Public Methods /// public function cloudinaryFields(Model $Model) { return $this->settings[$Model->alias]['fields']; } /// Private Methods /// private function createCloudinaryField(Model $Model, $fieldName, $source=NULL) { $source = $source ? $source : $Model->data; return new CloudinaryField(isset($source[$Model->alias][$fieldName]) ? $source[$Model->alias][$fieldName] : ""); } private function updateCloudinaryField(Model $Model, $fieldName, &$data=NULL) { $source =& $data ? $data : $Model->data; if (isset($source[$Model->alias][$fieldName]) && $source[$Model->alias][$fieldName] instanceof CloudinaryField) { return; } $source[$Model->alias][$fieldName] = $this->createCloudinaryField($Model, $fieldName, $source); } private function saveCloudinaryField(Model $Model, $fieldName) { $field = @$Model->data[$Model->alias][$fieldName]; $ret = NULL; if ($field instanceof CloudinaryField) { return; } elseif (!$field) { $ret = new CloudinaryField(); } elseif (is_string($field)) { $ret = new CloudinaryField($field); // $ret->verify(); - Validate only in beforeValidate } elseif (is_array($field) && isset($field['tmp_name'])) { $ret = new CloudinaryField(); $ret->upload($field['tmp_name']); } else { // TODO - handle file object? throw new \Exception("Couldn't save cloudinary field '" . $Model->alias . ":" . $fieldName . "' - unknown input: " . gettype($field)); } $Model->data[$Model->alias][$fieldName] = $ret; } private function relevantFields(Model $Model, $options = array()) { $cloudinaryFields = $this->settings[$Model->alias]['fields']; if (!(isset($options['fieldList']) && $options['fieldList'])) { return $cloudinaryFields; } return array_intersect($cloudinaryFields, $options['fieldList']); } private static function modifyPropertyUsingForce($instance, $property, $newValue) { if (version_compare(PHP_VERSION, '5.3.0') >= 0) { $myClassReflection = new ReflectionClass(get_class($instance)); $secret = $myClassReflection->getProperty($property); $secret->setAccessible(true); $secret->setValue($instance, $newValue); } } private function changeModelDefaults(Model $Model) { $schema = $Model->schema(); foreach ($this->relevantFields($Model) as $fieldName) { $schema[$fieldName] = new CloneOnAccessArray($schema[$fieldName]); $schema[$fieldName]['default'] = new CloudinaryField(); } self::modifyPropertyUsingForce($Model, "_schema", $schema); } } class CloneOnAccessArray extends ArrayObject { public function offsetGet($offset) { $ret = parent::offsetGet($offset); return (is_object($ret)) ? clone $ret : $ret; } } /* Simplest usage: Model: class Photo extends AppModel { public $actsAs = array('CloudinaryCake.Cloudinary' => array('fields' => array('cloudinaryIdentifier'))); } Controller: Find: $photo = $this->Photo->find('first', $options); // returns CloudinaryField in Modify: $photo['Photo']['cloudinaryIdentifier'].upload($new_file); Delete: $photo['Photo']['cloudinaryIdentifier'].delete($new_file); Save: Photo->save($photo); Save (from form): Photo->save($this->request->data); // should work with file upload or identifier * Validate identifier upon save * */ <file_sep>Cloudinary Cake PHP Sample Project ============================= Included in this folder is sample project for demonstrating the common Cloudinary's usage with Cake PHP. ## Photo Album This sample demonstrate the usage of the Cloudinary CakePHP plugin. It provides very similar functionalities as the basic Photo Album. This samples requires CakePHP to be installed. You can follow our directions in [the `README.md` file](https://github.com/cloudinary/cloudinary_cake_php/tree/master) using either the manual method or Composer for the installation. When you finish: * Setup database config (You can use `Config/database.php.default` as reference by copying it into `Config/database.php` and modifying the relevant fields. See the [CakePHP Cookbook](http://book.cakephp.org/2.0/en/index.html) for more information) * Create the database table (`cake schema create`) You can now access the sample through http://YOUR\_SERVER/PATH\_TO\_CLOUDINARY\_PHP/samples/PhotoAlbumCake *If you use Composer - Please note:* You do not need to bake a new project if you want just to try out the sample. If you do bake one, you'll have to remove the `.htaccess` from your app root directory in order to be able to access the sample in `APP_ROOT/Vendor/cloudinary/cloudinary_php/samples/PhotoAlbumCake`. Another option is available if you are using PHP 5.4 or higher. Go to the `samples` directory and run - If you're using a Bourne compatibly shell (sh, bash, zsh): NO_REWRITE=1 php -S localhost:8001 On Windows command prompt: set NO_REWRITE=1 php -S localhost:8001 Then you can simply browse to: http://localhost:8001/PhotoAlbumCake/index.php/ <file_sep><?php App::uses("CakeLog", "Log"); class CloudinaryCakeLoader { static function load() { self::fixAutoload(); self::loadPlugin(); self::configureCloudinary(); } private static function configureCloudinary() { try { Configure::load('CloudinaryPrivate'); \Cloudinary::config(Configure::read('cloudinary')); } catch (Exception $e) { CakeLog::notice("Couldn't find Config/CloudinaryPrivate.php file"); } } private static function loadPlugin() { CakePlugin::load('CloudinaryCake', array('bootstrap' => true, 'routes' => false, 'path' => __DIR__ . DS . 'CloudinaryCake' . DS)); } private static function fixAutoload() { // Remove and re-prepend CakePHP's autoloader as composer thinks it is the most important. // See https://github.com/composer/composer/commit/c80cb76b9b5082ecc3e5b53b1050f76bb27b127b spl_autoload_unregister(array('App', 'load')); spl_autoload_register(array('App', 'load'), true, true); } } <file_sep><?php App::uses('FormHelper', 'View/Helper'); class CloudinaryHelper extends FormHelper { public $helpers = array('Html'); public $cloudinaryFunctions = array( "cl_image_tag", "fetch_image_tag", "facebook_profile_image_tag", "gravatar_profile_image_tag", "twitter_profile_image_tag", "twitter_name_profile_image_tag", "cloudinary_js_config", "cloudinary_url", "cl_sprite_url", "cl_sprite_tag", "cl_upload_url", "cl_upload_tag_params", "cl_image_upload_tag", "cl_form_tag" ); public $cloudinaryJSIncludes = array( "jquery.ui.widget", "jquery.iframe-transport", "jquery.fileupload", "jquery.cloudinary", ); public function __call($name, $args) { if (in_array($name, $this->cloudinaryFunctions)) { return call_user_func_array($name, $args); } return parent::__call($name, $args); } /// Automatically detect cloudinary fields on models that have declared them. public function input($fieldName, $options = array()) { $this->setEntity($fieldName); $model = $this->_getModel($this->model()); $fieldKey = $this->field(); if (!@$options['type'] && $model->hasMethod('cloudinaryFields') && in_array($fieldKey, $model->cloudinaryFields())) { $options['type'] = 'file'; } return parent::input($fieldName, $options); } public function cloudinary_includes($options = array()) { foreach ($this->cloudinaryJSIncludes as $include) { echo $this->Html->script($include, $options); } } /// Called for input() when type => direct_upload public function direct_upload($fieldName, $options = array()) { $modelKey = $this->model(); $fieldKey = $this->field(); $options = @$options["cloudinary"] ? $options["cloudinary"] : array(); return \cl_image_upload_tag("data[" . $modelKey . "][" . $fieldKey . "]", $options); } } <file_sep><?php $this->layout = 'photoalbum'; # Include jQuery echo $this->Html->script('//code.jquery.com/jquery-1.10.1.min.js'); # Include cloudinary_js dependencies (requires jQuery) echo $this->Form->cloudinary_includes(); # Setup cloudinary_js using the current cloudinary_php configuration echo cloudinary_js_config(); ?> <!-- A standard form for sending the image data to your server --> <div id='backend_upload'> <h1>Upload through your server</h1> <?php echo $this->Form->create('Photo', array('type' => 'file')); ?> <?php echo $this->Form->input('cloudinaryIdentifier', array("label" => "", "accept" => "image/gif, image/jpeg, image/png")); ?> </fieldset> <?php echo $this->Form->end(__('Upload')); ?> </div> <!-- A form for direct uploading using a jQuery plug-in. The cl_image_upload_tag PHP function generates the required HTML and JavaScript to allow uploading directly frm the browser to your Cloudinary account --> <div id='direct_upload'> <h1>Direct upload from the browser</h1> <?php echo $this->Form->create('Photo', array('type' => 'file')); # The callback URL is set to point to an HTML file on the local server which works-around restrictions # in older browsers (e.g., IE) which don't full support CORS. echo $this->Form->input('cloudinaryIdentifier', array("type" => "direct_upload", "label" => "", "cloudinary" => array("callback" => $cors_location, "html" => array( "multiple" => true, "accept" => "image/gif, image/jpeg, image/png")))); # A simple $this->Form->input('cloudinaryIdentifier', array("type" => "direct_upload")) # should be sufficient in most cases echo $this->Form->end(); ?> <!-- status box --> <div class="status"> <h2>Status</h2> <span class="status_value">Idle</span> </div> <div class="uploaded_info_holder"> </div> </div> <?php echo $this->Html->link('Back to list...', array('controller' => 'photos', 'action' => 'list_photos'), array('class' => 'back_link')); ?> <script> function prettydump(obj) { ret = "" $.each(obj, function(key, value) { ret += "<tr><td>" + key + "</td><td>" + value + "</td></tr>"; }); return ret; } $(function() { $('.cloudinary-fileupload') .fileupload({ dropZone: '#direct_upload', start: function () { $('.status_value').text('Starting direct upload...'); }, progress: function () { $('.status_value').text('Uploading...'); }, }) .on('cloudinarydone', function (e, data) { $('.status_value').text('Updating backend'); $.post(this.form.action, $(this.form).serialize(), function () { $('.status_value').text('Idle'); }); var info = $('<div class="uploaded_info"/>'); $(info).append($('<div class="data"/>').append(prettydump(data.result))); $(info).append($('<div class="image"/>').append( $.cloudinary.image(data.result.public_id, { format: data.result.format, width: 150, height: 150, crop: "fill" }) )); $('.uploaded_info_holder').append(info); }); }); </script> <file_sep><?php App::uses('AppModel', 'Model'); /** * photo Model * */ class Photo extends AppModel { public $actsAs = array('CloudinaryCake.Cloudinary' => array('fields' => array('cloudinaryIdentifier'))); } <file_sep><?php /** * * PHP 5 * * @link http://cakephp.org CakePHP(tm) Project * @package app.View.Layouts * @since CakePHP(tm) v 0.10.0.1076 */ ?> <!DOCTYPE html> <html> <head> <?php echo $this->Html->charset(); ?> <title>PhotoAlbum - <?php echo $title_for_layout; ?></title> <?php echo $this->Html->meta('favicon', cloudinary_url("http://cloudinary.com/favicon.png", array("type" => "fetch")), array('type' => 'icon')); echo $this->Html->script('//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js'); echo $this->Html->css('photoalbum'); echo $this->fetch('meta'); echo $this->fetch('css'); echo $this->fetch('script'); ?> </head> <body> <div id="container"> <div id="header"> <div id="logo"> <!-- This will render the image fetched from a remote HTTP URL using Cloudinary --> <?php echo fetch_image_tag("http://cloudinary.com/images/logo.png") ?> </div> <div id="posterframe"> <!-- This will render the fetched Facebook profile picture using Cloudinary according to the requested transformations --> <?php echo facebook_profile_image_tag("officialchucknorrispage", array( "format" => "png", "transformation" => array( array("height" => 95, "width" => 95, "crop" => "thumb", "gravity" => "face", "effect" => "sepia", "radius" => 20 ), array("angle" => 10) ))); ?> </div> </div> <div id="content"> <?php echo $this->Session->flash(); ?> <?php echo $this->fetch('content'); ?> </div> </div> </body> </html>
c8075456eb997840651228662fea5ae79eed93d4
[ "Markdown", "PHP" ]
8
PHP
cloudinary/cloudinary_cake_php
d43de98e6e90aa4038847629ee80215b2ce958e9
ad9d2e73d9900b0b9c88e0a6bfa41c2294e364c9
refs/heads/master
<repo_name>dechenwangmo/develop<file_sep>/database/seeds/tblEmpProfileSeeder.php <?php use Illuminate\Database\Seeder; use App\UserProfile; class tblEmpProfileSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $prof = new UserProfile(); $prof->empID="1"; $prof->name="Karma"; $prof->dob="06/12/1985"; $prof->designation="HR"; $prof->address="Changangkha"; $prof->contact="17895656"; $prof->userPic="kkkk.jpg"; $prof->usrID="1"; $prof->save(); $prof = new UserProfile(); $prof->empID="2"; $prof->name="Pema"; $prof->dob="06/12/1982"; $prof->designation="ICT"; $prof->address="Changangkha"; $prof->contact="17892656"; $prof->userPic="d.jpg"; $prof->usrID="2"; $prof->save(); $prof = new UserProfile(); $prof->empID="3"; $prof->name="Dechen"; $prof->dob="06/12/1982"; $prof->designation="ICT"; $prof->address="Changjiji"; $prof->contact="17892656"; $prof->userPic="p.jpg"; $prof->usrID="3"; $prof->save(); $prof = new UserProfile(); $prof->empID="4"; $prof->name="Kezang"; $prof->dob="06/12/1982"; $prof->designation="ICT"; $prof->address="Olakha"; $prof->contact="17892656"; $prof->userPic="we.jpg"; $prof->usrID="4"; $prof->save(); } } <file_sep>/app/UserResp.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class UserResp extends Model { protected $table='tblUserResponsibility'; protected $fillable = [ 'respID','respName' ]; } <file_sep>/database/seeds/tblUserRespSeeder.php <?php use Illuminate\Database\Seeder; use App\UserResp; class tblUserRespSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $res = new UserResp(); $res->respName="CEC Chairman"; $res->save(); $res = new UserResp(); $res->respName="CEC Member Secretary"; $res->save(); $res = new UserResp(); $res->respName="CEC Member"; $res->save(); $res = new UserResp(); $res->respName="CM Chairman"; $res->save(); $res = new UserResp(); $res->respName="CM Member"; $res->save(); } } <file_sep>/app/Http/routes.php <?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ /*-------------Default login page-------------------*/ Route::get('/', [ 'uses' => 'AdminUserController@getLogin', 'as' => 'user.login' ]); /*-------------user login---------------------------*/ Route::post('/login', [ 'uses' => 'AdminUserController@postLogin', 'as' => 'user.login' ]); Route::get('Dashboard/{userTypeID}',[ 'uses' => 'AdminUserController@getDashboard', 'as' => 'user.dashboard' ]); /*------------Logout user---------------------------*/ Route::get('/',['as' =>'logoutuser', function(){ Auth::logout(); Session::forget('UserTypeID'); Session::forget('lurRoleID'); return view('auth.login'); }]); /*---------------------------get UI--------------------------------------------*/ Route::get('ui/UserManagement/{ui}', [ 'uses' =>'AdminUserController@getUI', 'as' => 'getUI' ]); /*---------------------Ajax check user existence---------------------------------*/ Route::post('/check_email', array('as' => 'emailexistcheck', 'uses' => 'AdminUserController@check_email')); <file_sep>/app/UserRole.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class UserRole extends Model { protected $table='pltblrole'; // public function AdminUser(){ // return $this->belongsToMany('App\AdminUser','linkuserrole', 'lurUserID','lurRoleID'); // } } <file_sep>/database/migrations/2016_04_25_161943_create_linkUserRole_create.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateLinkUserRoleCreate extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('linkUserRole', function (Blueprint $table) { $table->increments('lurID'); $table->integer('lurUserID')->unsigned(); $table->foreign('lurUserID')->references('id')->on('tblUser')->onUpdate('cascade')->onDelete('cascade'); $table->integer('lurRoleID')->unsigned(); $table->foreign('lurRoleID')->references('roID')->on('pltblRole')->onUpdate('cascade')->onDelete('cascade'); $table->integer('lurRespID')->unsigned(); $table->foreign('lurRespID')->references('respID')->on('tbluserresponsibility')->onUpdate('cascade')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('linkUserRole'); } } <file_sep>/database/seeds/tblUserSeeder.php <?php use Illuminate\Database\Seeder; use App\AdminUser; class tblUserSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $user = new AdminUser(); $user->usName="Chairperson"; $user->email="<EMAIL>"; $user->password=bcrypt('<PASSWORD>'); $user->usUserTypeID= 1; $user->save(); $user = new AdminUser(); $user->usName="Commissioner"; $user->email="<EMAIL>"; $user->password=bcrypt('<PASSWORD>'); $user->usUserTypeID= 2; $user->save(); $user = new AdminUser(); $user->usName="Director"; $user->email="<EMAIL>"; $user->password=bcrypt('<PASSWORD>'); $user->usUserTypeID= 3; $user->save(); $user = new AdminUser(); $user->usName="Chief"; $user->email="<EMAIL>"; $user->password=bcrypt('<PASSWORD>'); $user->usUserTypeID= 4; $user->save(); $user = new AdminUser(); $user->usName="Investigator"; $user->email="<EMAIL>"; $user->password=bcrypt('<PASSWORD>'); $user->usUserTypeID= 5; $user->save(); $user = new AdminUser(); $user->usName="Complaints Registration"; $user->email="<EMAIL>"; $user->password=bcrypt('<PASSWORD>'); $user->usUserTypeID= 6; $user->save(); $user = new AdminUser(); $user->usName="Administrator"; $user->email="<EMAIL>"; $user->password=bcrypt('<PASSWORD>'); $user->usUserTypeID= 7; $user->save(); } } <file_sep>/database/seeds/tblUserRoleSeeder.php <?php use Illuminate\Database\Seeder; use App\UserRole; class tblUserRoleSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $role = new UserRole; $role->roName="Complaints Registration"; $role->save(); $role = new UserRole; $role->roName="Complaints Evaluation"; $role->save(); $role = new UserRole; $role->roName="Investigation"; $role->save(); $role = new UserRole; $role->roName="Followup Member"; $role->save(); $role = new UserRole; $role->roName="Administration"; $role->save(); } } <file_sep>/app/UserType.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class UserType extends Model { protected $table='pltblusertype'; //// -------------UserType and User-----------chief can have many users--- // public function AdminUser() // { // return $this->belongsToMany('App\AdminUser','utID'); // } } <file_sep>/app/UserProfile.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class UserProfile extends Model { protected $table='tblempprofile'; protected $fillable = [ 'empID','dob','designation','address','contact' ]; } <file_sep>/database/seeds/tblUserTypeSeeder.php <?php use Illuminate\Database\Seeder; use App\UserType; class tblUserTypeSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $usertype = new UserType(); $usertype->utName="Chairperson"; $usertype->save(); $usertype = new UserType(); $usertype->utName="Commissioner"; $usertype->save(); $usertype = new UserType(); $usertype->utName="Director"; $usertype->save(); $usertype = new UserType(); $usertype->utName="Chief"; $usertype->save(); $usertype = new UserType(); $usertype->utName="Investigator"; $usertype->save(); $usertype = new UserType(); $usertype->utName="Complaints Officer"; $usertype->save(); $usertype = new UserType(); $usertype->utName="Administrator"; $usertype->save(); } } <file_sep>/app/Http/Controllers/AdminUserController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use Illuminate\Support\Facades\Auth; use App\AdminUser; use Illuminate\Support\Facades\Session; use DB; class AdminUserController extends Controller { public function getLogin(){ return view('auth.login'); } public function check_email(Request $request){ if(AdminUser::where('email','=',$request->input('email'))->exists()) { return "true"; }else { return "false"; } } public function postLogin(Request $request){ $this->validate($request, [ 'email' => 'required|email', 'password' => '<PASSWORD>|' ]); //check email existence in the database $email = AdminUser::where(['email'=>$request['email']])->first(); if($email) { if (!Auth::attempt(['email' => $request['email'], 'password' => $request['password']])) { return redirect()->back()->with(['fail' => 'Your email or password did not match']); } }else{ return redirect()->back()->with(['fail'=>'Email address not registered']); } //check existence of user role $user = DB::table('linkuserrole') ->where('lurUserID','=',$email->id)->get(); foreach($user as $users){ $roleID[]=$users->lurRoleID; } Session::put('lurRoleID', $roleID); // Session::put('usUserTypeID',$email->usUserTypeID); //dd(Session::get('lurRoleID')); return redirect()->route('user.dashboard',['userTypeID'=>$email->usUserTypeID]); } public function getDashboard($userTypeID){ // serve dashboard according to usertype if(!Auth::check()) { return redirect()->back(); } Session::put('UserTypeID', $userTypeID); // Chairperson Dashboard if($userTypeID === "1") { return view('dashboards.cpDashboard'); } // Commissioner Dashboard if($userTypeID === "2") { return view('dashboards.comDashboard'); } // Director Dashboard if($userTypeID === "3") { return view('dashboards.directorDashboard'); } // ChiefDashboard if($userTypeID === "4") { return view('dashboards.chiefDashboard'); } // Investigator Dashboard if($userTypeID === "5") { return view('dashboards.invDashboard'); } // Complaint Registration Dashboard if($userTypeID === "6") { return view('dashboards.complaintRegDashboard'); } // Administrator Dashboard if($userTypeID === "7") { return view('dashboards.adminDashboard'); } } public function getLoggedOut(){ if(Auth::check()) { Auth::logout(); return redirect()->route('auth.login'); } } public function getUI($ui){ if(!Auth::check()) { return redirect()->back(); } if($ui == "2") { return view('ui.complaintRegistration'); }else if($ui == "3") { return view('ui.complaintEvaluation'); } else if($ui == "4") { return view('ui.followUp'); } else if($ui == "5") { return view('ui.report'); }else if($ui == "6") { return view('ui.investigation'); }else if($ui == "7") { return view('ui.userManagement'); }else if($ui == "8") { return view('ui.masterRecords'); }else if($ui == "9") { return view('ui.peSettings'); } else{ return "Cannot find page!"; } } }
7b3d2a2e0da19ec6d39dd8fb0656d2789b5628f2
[ "PHP" ]
12
PHP
dechenwangmo/develop
9e9ab3c7c66e529cd54697cfea1343334ac628c3
65b7673f29503593346705f65ad248d30e8b5eb9
refs/heads/master
<file_sep>// // Constraints.h // userDefault-偏好设置 // // Created by AppleUser on 16/3/8. // Copyright © 2016年 AppleUser. All rights reserved. // #ifndef Constraints_h #define Constraints_h #define OFFICER @"offer" #define RANK @"rank" #define CODE @"code" #define ENGINE @"engine" #define WRAP @"wrap" #endif /* Constraints_h */ <file_sep># IOS-Repository iOS Development
51f77e1c8c28c7a45d3f24156e3a9f36499219ee
[ "Markdown", "C" ]
2
C
wangjiansheng21/IOS-Repository
6d35b2b70774a8d9cefed5188734f4ef50539f1e
2a21bde28e2db58766f59de5b87d2d662ab76313
refs/heads/master
<repo_name>jbane11/examples<file_sep>/tgt_yield.sh #!bin/bash set -x tgt=$1 if [ $1 -eq "-h"] || [ $1 -eq "-help" ] || [ $1 -eq "h" ] || [ $1 == "help" ] then echo "::::::Help::::::::" echo "arguments are tgt, start, end, bins, clean, model, and suf" exit fi if [[ $# -ge 2 ]] then strt=$2 else strt=1 fi if [[ $# -ge 3 ]] then end=$3 else end=5 fi if [[ $# -ge 4 ]] then bins=$4 else bins=50 fi if [[ $# -ge 5 ]] then clean=$5 else clean=0 fi if [[ $# -ge 6 ]] then model=$6 else model=0 fi if [[ $# -ge 7 ]] then suf=$7 else suf="1" fi pwd=$PWD cuttype="tightcut/" if [ -e "/home/jbane/tritium/Tri_offline/MC_comparison/yield_output/$cuttype" ] then echo "Good on cut dir" else cd "/home/jbane/tritium/Tri_offline/MC_comparison/yield_output/" mkdir -v $cuttype cd $pwd fi if [ -e "/home/jbane/tritium/Tri_offline/MC_comparison/yield_output/$cuttype/${bins}bins" ] then echo "good" else cd "/home/jbane/tritium/Tri_offline/MC_comparison/yield_output/$cuttype/" mkdir -v ${bins}bins cd ${bins}bins mkdir xbj mkdir theta cd $pwd fi if [ "MCyield_test_C.so" -ot "MCyield_test.C" -o "MCYield_test_C.so" -ot "/home/jbane/headers/rootalias.h" -o "MCYield_test_C.so" -ot "/home/jbane/headers/inc1.h" -o "MCYield_test_C.so" -ot "/home/jbane/header/SQLanalysis.h" ] then echo "make s0 file" analyzer -b -q -l .x "make_so.C" fi x=$strt while [[ ${x} -le $end ]] do analyzer -b -l -q .x "CY_preload.C(\"${tgt}\",\"$x\",\"$suf\",$bins,$clean,$model,3)" (( x++ )) done
ed6d9f2d14b74d9a85440bf10cc27a013ef04471
[ "Shell" ]
1
Shell
jbane11/examples
1ff306da8f072bf6611c60d0fdabd8e518291441
adf87590fe4433a5103c03ba5391102bc44ab325
refs/heads/master
<repo_name>HaoTruong/Python_FinalProject<file_sep>/FinalProject_MineSweeper.py import pygame, random, time, sys # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) # This sets the WIDTH and HEIGHT of each grid location WIDTH = 20 HEIGHT = 20 # This sets the margin between each cell MARGIN = 5 numGrid = 10 #Number of mines is 15% of number of grid mineNum = (15/100)*(numGrid**2) # Create a 2 dimensional array. A two dimensional # array is simply a list of lists. grid = [] opened = [] flagged = [] for row in range(numGrid): # Add an empty array that will hold each cell # in this row grid.append([]) opened.append([]) flagged.append([]) for column in range(numGrid): grid[row].append(0) # Append a cell opened[row].append(0) flagged[row].append(0) #Random mine count = 0 while (count < mineNum): i = random.randrange(numGrid) j = random.randrange(numGrid) if (grid[i][j] != 10): count += 1 grid[i][j] = 10 opened[i][j] = 1 #Setting number of mines around free squares def countSurrounding(): global grid, numGrid for row in range(numGrid): for column in range(numGrid): if grid[row][column] != 10: mineCount = 0 i = -1 while i < 2: j =-1 while j < 2: if (i+row >= 0 and i+row <= numGrid-1 and j+column >= 0 and j+column <= numGrid-1): if (grid[row+i][column+j] == 10): mineCount +=1 j += 1 i += 1 grid[row][column] = mineCount # Initialize pygame pygame.init() # Set the HEIGHT and WIDTH of the screen WINDOW_SIZE = [500, 500] winSize = 500 screen = pygame.display.set_mode(WINDOW_SIZE) # Set title of screen pygame.display.set_caption("MineSweeper") #Game over message def game_over(): my_font = pygame.font.SysFont('times new roman',50) result = "Game over!" game_over_surf = my_font.render(result, True, RED) game_over_rect = game_over_surf.get_rect() game_over_rect.midtop = (winSize /2 , winSize /2) screen.fill(WHITE) screen.blit(game_over_surf, game_over_rect) pygame.display.flip() time.sleep(3) pygame.quit() sys.exit(0) def game_won(): my_font = pygame.font.SysFont('times new roman',50) result = "You won!" game_over_surf = my_font.render(result, True, RED) game_over_rect = game_over_surf.get_rect() game_over_rect.midtop = (winSize /2 , winSize /2) screen.fill(WHITE) screen.blit(game_over_surf, game_over_rect) pygame.display.flip() time.sleep(3) pygame.quit() sys.exit(0) done = False def reveal(row, col,flagged): global grid, opened if (flagged[row][col] != 0): pygame.draw.rect(screen, WHITE,[(MARGIN + WIDTH) * col + MARGIN, (MARGIN + HEIGHT) * row + MARGIN, WIDTH, HEIGHT]) screen.blit(digit_text[grid[row][col]],[(MARGIN + WIDTH) * col + MARGIN, (MARGIN + HEIGHT) * row + MARGIN, WIDTH, HEIGHT]) opened[row][col] = 1 if (grid[row][col] == 0 ): i = -1 while i < 2: j =-1 while j < 2: if (i != 0 or j != 0): if (i+row >= 0 and i+row <= numGrid-1 and j+col >= 0 and j+col <= numGrid-1): if (opened[row+i][col+j] == 0): reveal(row+i, col+j, flagged) j += 1 i += 1 #Use to putting number into each grid clock = pygame.time.Clock() font = pygame.font.SysFont('times new roman',20) text1 = font.render('1', True, BLACK) text2 = font.render('2', True, BLACK) text3 = font.render('3', True, BLACK) text4 = font.render('4', True, BLACK) text5 = font.render('5', True, BLACK) text6 = font.render('6', True, BLACK) text7 = font.render('7', True, BLACK) text8 = font.render('8', True, BLACK) text0 = font.render('0', True, BLACK) textF = font.render('F', True, BLACK) rect1 = text1.get_rect() rect2 = text2.get_rect() rect3 = text3.get_rect() rect4 = text4.get_rect() rect5 = text5.get_rect() rect6 = text6.get_rect() rect7 = text7.get_rect() rect8 = text8.get_rect() digit_text = {1:text1, 2:text2, 3:text3, 4:text4, 5:text5, 6:text6, 7:text7, 8:text8, 0:text0} # -------- Main Program Loop ----------- # Set the screen background screen.fill(BLACK) # Draw the grid: for row in range(numGrid): for column in range(numGrid): color = WHITE ''' if (grid[row][column] == 10): color = RED ''' pygame.draw.rect(screen, color,[(MARGIN + WIDTH) * column + MARGIN, (MARGIN + HEIGHT) * row + MARGIN, WIDTH, HEIGHT]) first = True wincond = 0 countSurrounding() # Loop until the user clicks the close button. while not done: #check win condition if (wincond == mineNum): done = True for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop elif event.type == pygame.MOUSEBUTTONDOWN: # User clicks the mouse. Get the position pos = pygame.mouse.get_pos() # Change the x/y screen coordinates to grid coordinates column = pos[0] // (WIDTH + MARGIN) row = pos[1] // (HEIGHT + MARGIN) if (event.button == 1): if (first): if grid[row][column] == 10: mineNum -= 1 grid[row][column] = 0 first = False countSurrounding() if (grid[row][column] == 10): game_over() elif (grid[row][column] != 0): screen.blit(digit_text[grid[row][column]],[(MARGIN + WIDTH) * column + MARGIN, (MARGIN + HEIGHT) * row + MARGIN, WIDTH, HEIGHT]) else: reveal(row, column, flagged) elif (event.button == 3): if flagged[row][column] == 0: if (grid[row][column] == 10): wincond += 1 grid[row][column] = 11 pygame.draw.rect(screen, WHITE,[(MARGIN + WIDTH) * column + MARGIN, (MARGIN + HEIGHT) * row + MARGIN, WIDTH, HEIGHT]) screen.blit(textF,[(MARGIN + WIDTH) * column + MARGIN, (MARGIN + HEIGHT) * row + MARGIN, WIDTH, HEIGHT]) elif grid[row][column] == 11: wincond -= 1 grid[row][column] = 10 pygame.draw.rect(screen, WHITE,[(MARGIN + WIDTH) * column + MARGIN, (MARGIN + HEIGHT) * row + MARGIN, WIDTH, HEIGHT]) else: screen.blit(textF,[(MARGIN + WIDTH) * column + MARGIN, (MARGIN + HEIGHT) * row + MARGIN, WIDTH, HEIGHT]) flagged[row][column] = 1 else: flagged[row][column] = 0 pygame.draw.rect(screen, WHITE,[(MARGIN + WIDTH) * column + MARGIN, (MARGIN + HEIGHT) * row + MARGIN, WIDTH, HEIGHT]) # Limit to 60 frames per second clock.tick(60) # Go ahead and update the screen with what we've drawn. pygame.display.flip() game_won() pygame.quit()
105ffbc0b80d34d40bf40e898494417c45519a28
[ "Python" ]
1
Python
HaoTruong/Python_FinalProject
4dd13d6e477d68bf364940bbd9400bb734b60a2f
e1bda17ae98e76935bed26daa5bac7bdbbac9c9e
refs/heads/main
<file_sep><?php require 'fungsi.php'; // cek tombol submit if (isset($_POST["submit"])) { if(tambah($_POST)>0) { echo " <script> alert('data berhasil ditambah'); document.location.href='index.php'; </script> "; }else{ echo " <script> alert('data gagal ditambah'); document.location.href='index.php'; </script> "; } } ?> <!DOCTYPE html> <html> <head> <title>tambah data produk</title> </head> <body> <h1>tambah data produk</h1> <form action="" method="post"> <ul> <li> <label for="nama">nama produk:</label> <input type="text" name="nama"id="nama" required> </li> <li> <label for="keterangan">keterangan:</label> <input type="text" name="keterangan" id="keterangan"> </li> <li> <label for="harga">harga:</label> <input type="text" name="harga" id="harga"> </li> <li > <label for="jumlah">jumlah</label> <input type="text" name="jumlah" id="jumlah"> </li> <li> <button type="submit"name="submit">tambah</button> </li> </ul> </form> </body> </html><file_sep><?php $conn=mysqli_connect("localhost","root","","fazztrack") ; function query($query){ global $conn; $result= mysqli_query($conn,$query); $rows=[]; while($row=mysqli_fetch_assoc($result)){ $rows[]=$row; }return $rows; } function tambah($data){ global $conn; // htmlspesialchars pengaman elemen html $nama=htmlspecialchars($data["nama"]); $keterangan=htmlspecialchars($data["keterangan"]); $harga=htmlspecialchars($data["harga"]); $jumlah=htmlspecialchars($data["jumlah"]); $query="INSERT INTO produk VALUES('','$nama','$keterangan','$harga','$jumlah')"; mysqli_query($conn,$query); return mysqli_affected_rows($conn); }function hapus($id){ global $conn; mysqli_query($conn,"DELETE FROM produk WHERE id=$id"); return mysqli_affected_rows($conn); }function ubah($data){ global $conn; // htmlspesialchars pengaman elemen html $id=$data["id"]; $nama= htmlspecialchars($data["nama"]); $keterangan= htmlspecialchars($data["keterangan"]); $harga= htmlspecialchars($data["harga"]); $jumlah= htmlspecialchars($data["jumlah"]); $query="UPDATE produk SET nama_produk='$nama', keterangan='$keterangan', harga='$harga', jumlah='$jumlah' WHERE id=$id"; mysqli_query($conn,$query); return mysqli_affected_rows($conn); } ?><file_sep><?php require 'fungsi.php'; $produk=query("SELECT *FROM produk"); // ambil data (fetch) berdasarkan tipe array: // 1.my sqli_fetch_row/ mengembalikan array numerik // 2." "_assoc/mengembalikan array nama // 3." "_array/mengembalikan array numerik dan asosiatif // 4." "_object/ tidak mengembalikan array numerik dan asosiatif // contoh array object mysqli_fetch_object($result->produk); ?> <!DOCTYPE html> <html> <head> <title>halaman admin</title> </head> <body> <h1>daftar produk</h1> <a href="tambah.php">tambah produk</a> <form> <table border="1" cellpadding="10" cellspacing="0"> <tr> <th>no</th> <th>aksi</th> <th>nama produk</th> <th>keterangan</th> <th>harga</th> <th>jumlah</th> </tr> <?php $i=1?> <?php foreach ($produk as $row ):?> <tr> <td><?=$i; ?></td> <td> <a href="ubah.php?id=<?= $row["id"]; ?>">ubah</a> <a href="hapus.php?id=<?= $row["id"]; ?>" onclick="return confirm('yakin?');">hapus</a> </td> <td><?=$row["nama_produk"] ?></td> <td><?=$row["keterangan"] ?></td> <td><?=$row["harga"] ?></td> <td><?=$row["jumlah"] ?></td> </tr> </form> <?php $i++; ?> <?php endforeach; ?> </body> </html> <file_sep><?php require 'fungsi.php'; // ambil data di url $id=$_GET["id"]; // query data sesuai id $produk=query("SELECT * FROM produk WHERE id=$id")[0]; // mengecek tombol if (isset($_POST["submit"])) { if (ubah($_POST)>0) { echo " <script> alert('data berhasil diubah'); document.location.href='index.php'; </script> "; }else{ echo " <script> alert('data gagal diubah'); document.location.href='index.php'; </script> "; } } ?> <!DOCTYPE html> <html> <head> <title>ubah daftar produk</title> </head> <body> <h1>ubah daftar produk</h1> <form action="" method="post"> <input type="hidden" name="id" value="<?=$produk["id"];?>"> <ul> <li> <!-- required berfungsi membuat form jadi not null --> <label for="nama">nama produk:</label> <input type="text" name="nama" id="nama" required value="<?=$produk["nama_produk"];?>"> </li> <li> <label for="keterangan">keterangan:</label> <input type="text" name="keterangan" id="keterangan" value="<?=$produk["keterangan"];?>"> </li> <li> <label for="harga">harga:</label> <input type="text" name="harga" id="harga" value="<?=$produk["harga"];?>"> </li> <li> <label for="jumlah">jumlah:</label> <input type="text" name="jumlah" id="jumlah"value="<?=$produk["jumlah"];?>"> </li> <li> <button type="submit" name="submit">ubah</button> </li> </ul> </form> </body> </html>
969d105aca284e4d0e617f185a9bcc12215ba114
[ "PHP" ]
4
PHP
tanxcypro/ok
36cb01555d7837cb2ea255dc5172a7a9fa2da950
a9c656de119b64f16145a505f1ec745dbb784ffe
refs/heads/master
<repo_name>onebuck1503/BackgroundCheck<file_sep>/Software41.BackgroundCheck.Repository.EF/EFApplicantRepository.cs using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using Software41.BackgroundCheck.Repository; using Software41.BackgroundCheck.Domain; namespace Software41.BackgroundCheck.Repository.EF { public class EFApplicantRepository:IApplicantRepository { private BackgroundCheckContext _context; /// <summary> /// We can probably get rid of this but I left it for now /// </summary> public EFApplicantRepository(IUnitOfWork context) { this._context = (BackgroundCheckContext) context; } public IEnumerable<Applicant> GetAll() { return this._context.Set<Applicant>(); } public IEnumerable<Applicant> FindBy(System.Linq.Expressions.Expression<Func<Applicant, bool>> predicate) { return this._context.Set<Applicant>().Where(predicate) as IEnumerable<Applicant>; } public Applicant FindById(int id) { return this._context.Set<Applicant>().Where(a => a.Id == id).FirstOrDefault(); } public void Save(Applicant applicant) { bool applicantIsNew = (applicant.Id == null || applicant.Id == 0) ? true:false; if (applicantIsNew) { this._context.Set<Applicant>().Add(applicant); } else { this._context.Entry(applicant).State = EntityState.Modified; } } public void Delete(Applicant applicant) { this._context.Set<Applicant>().Remove(applicant); } } } <file_sep>/Software41.BackgroundCheck.Domain/EducationHistory.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Software41.BackgroundCheck.Domain { public class EducationHistory { public int EducationHistoryId { get; set; } public String SchoolName { get; set; } public SchoolType SchoolType { get; set; } public DateTime AttendedFrom { get; set; } public DateTime AttendedTo { get; set; } public bool Graduated { get; set; } public DegreeType DegreeType { get; set; } } } <file_sep>/Software41.BackgroundCheck.Repository.EF.Tests/Applicant_Tests.cs using System; using System.Data; using System.Data.Entity; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Software41.BackgroundCheck.Domain; using Software41.BackgroundCheck.Repository; using Software41.BackgroundCheck.Repository.EF; using Moq; namespace Software41.BackgroundCheck.Repository.EF.Tests { [TestClass] public class Applicant_Tests { [TestMethod,Ignore] public void CanSaveNewApplicant_ExpectSuccess() { //Arrange string firstName = "David_1"; string middleName = "Michael"; string lastname = "OBrien"; IUnitOfWork context = new BackgroundCheckContext(); IApplicantRepository repository = new EFApplicantRepository(context); var applicant = DomainHelper.CreateApplicant(firstName, middleName, lastname); Applicant savedApplicant = null; //Act try { repository.Save(applicant); context.Commit(); savedApplicant = repository.FindBy(a => a.FirstName == applicant.FirstName).FirstOrDefault(); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex.Message); System.Diagnostics.Debug.Write(ex.StackTrace); } //Assert Assert.IsNotNull(savedApplicant); Assert.AreEqual(savedApplicant.FirstName, firstName); Assert.AreEqual(savedApplicant.MiddleName, middleName); Assert.AreEqual(savedApplicant.LastName, lastname); } [TestMethod,Ignore] public void CanUpdateExistingApplicant_ExpectSuccess() { //Arrange int id = 6; string firstName = "David_1_UpdatedAgain"; string middleName = "Michael"; string lastname = "OBrien"; IUnitOfWork context = new BackgroundCheckContext(); IApplicantRepository repository = new EFApplicantRepository(context); var applicant = repository.FindById(id); applicant.FirstName = firstName; Applicant updatedApplicant = null; //Act try { repository.Save(applicant); context.Commit(); updatedApplicant = repository.FindById(id); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex.Message); System.Diagnostics.Debug.Write(ex.StackTrace); } //Assert Assert.IsNotNull(updatedApplicant); Assert.AreEqual(updatedApplicant.FirstName, firstName); Assert.AreEqual(updatedApplicant.MiddleName, middleName); Assert.AreEqual(updatedApplicant.LastName, lastname); } [TestMethod,Ignore] public void CanSaveApplicantEmploymentHistory_ExpectSuccess() { //Arrange string firstName = "David_2"; string middleName = "Michael"; string lastname = "OBrien"; string employerName = "Benesyst2"; string jobTitle = "Programmer"; IUnitOfWork context = new BackgroundCheckContext(); IApplicantRepository repository = new EFApplicantRepository(context); var applicant = DomainHelper.CreateApplicant(firstName, middleName, lastname); Applicant savedApplicant = null; applicant.EmploymentHistory.Add( new EmploymentHistory { EmployerName = employerName, JobTitle = jobTitle, Salary = 110000, StartDate = new DateTime(2005, 2, 5), EndDate = new DateTime(2006, 6, 5) }); try { //Act repository.Save(applicant); context.Commit(); savedApplicant = repository.FindBy(a => a.FirstName == firstName).FirstOrDefault(); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex.Message); System.Diagnostics.Debug.Write(ex.StackTrace); } //Assert Assert.IsNotNull(savedApplicant); Assert.AreEqual(applicant.EmploymentHistory.Count, 1); Assert.AreEqual(applicant.EmploymentHistory[0].EmployerName, employerName); Assert.AreEqual(applicant.EmploymentHistory[0].JobTitle, jobTitle); } [TestMethod] public void CanUpdateApplicantEmploymentHistory_ExpectSuccess() { //Arrange int applicantId = 7; double newSalary = 125000; IUnitOfWork context = new BackgroundCheckContext(); IApplicantRepository repository = new EFApplicantRepository(context); Applicant applicant = repository.FindById(applicantId); Applicant updatedApplicant = null; if (applicant != null) { if(applicant.EmploymentHistory[0] != null) { applicant.EmploymentHistory[0].Salary = newSalary; } } try { //Act repository.Save(applicant); context.Commit(); updatedApplicant = applicant = repository.FindById(applicantId); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex.Message); System.Diagnostics.Debug.Write(ex.StackTrace); } //Assert Assert.IsNotNull(updatedApplicant); Assert.AreEqual(updatedApplicant.EmploymentHistory[0].Salary,newSalary); } [TestMethod, Ignore] public void CanSaveApplicantEducationHistory__ExpectSuccess() { //Arrange string firstName = "David_3"; string middleName = "Michael"; string lastname = "OBrien"; string firstRecordAddress = "377 Colborne Street"; string secondRecordAddress = "661 Ivy Falls Court"; IUnitOfWork context = new BackgroundCheckContext(); IApplicantRepository repository = new EFApplicantRepository(context); var applicant = DomainHelper.CreateApplicant(firstName, middleName, lastname); Applicant savedApplicant = null; applicant.AddressHistory.Add(new AddressHistory { Address1 = firstRecordAddress, Address2 = "", City = "Saint Paul", State = "MN", Zip = "55102", FromDate = "2003/10/31", ToDate = "Current" }); applicant.AddressHistory.Add(new AddressHistory { Address1 = secondRecordAddress, Address2 = "", City = "Mendota Heights", State = "MN", Zip = "55118", FromDate = "2000/4/5", ToDate = "2003/10/31" }); try { //Act repository.Save(applicant); context.Commit(); savedApplicant = repository.FindBy(a => a.FirstName == firstName).FirstOrDefault(); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex.Message); System.Diagnostics.Debug.Write(ex.StackTrace); } //Assert Assert.IsNotNull(savedApplicant); Assert.AreEqual(savedApplicant.AddressHistory.Count, 2); Assert.AreEqual(savedApplicant.AddressHistory[0].Address1, firstRecordAddress); Assert.AreEqual(savedApplicant.AddressHistory[1].Address1, secondRecordAddress); } [TestMethod,Ignore] public void CanSaveApplicantWithAllHistoriesPopulated_ExpectSuccess() { //Arrange string firstName = "David_X"; string middleName = "Michael"; string lastname = "OBrien"; IUnitOfWork context = new BackgroundCheckContext(); IApplicantRepository repository = new EFApplicantRepository(context); var applicant = DomainHelper.CreateApplicant(firstName, middleName, lastname); DomainHelper.AddAddressHistory(applicant, 2); DomainHelper.AddEducationHistory(applicant, 3); DomainHelper.AddEmploymentHistory(applicant, 3); //Act try { repository.Save(applicant); context.Commit(); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex.Message); System.Diagnostics.Debug.Write(ex.StackTrace); } Applicant savedApplicant = repository.FindBy(a => a.FirstName == firstName).FirstOrDefault(); //Assert NOTE: I am not testing too much here as I've run out of time. Will compare //built up domain object with saved object soon Assert.IsNotNull(savedApplicant); Assert.AreEqual(savedApplicant.FirstName, firstName); Assert.AreEqual(savedApplicant.MiddleName, middleName); Assert.AreEqual(savedApplicant.LastName, lastname); } /// <summary> /// Just go and manually inspect the history records associated with this; /// we'll build History repositories later if needed /// </summary> [TestMethod] public void CanRemoveApplicantAndHistory_ExpectSuccess() { //Arrange string nameToFind = "David_X"; IUnitOfWork context = new BackgroundCheckContext(); IApplicantRepository repository = new EFApplicantRepository(context); Applicant applicant = repository.FindBy(a => a.FirstName == nameToFind).FirstOrDefault(); if (applicant == null) throw new ArgumentNullException("Applicant Not Found"); //Act try { repository.Delete(applicant); context.Commit(); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex.Message); System.Diagnostics.Debug.Write(ex.StackTrace); } var savedApplicant = repository.FindBy(a => a.FirstName == nameToFind).FirstOrDefault(); //Assert Assert.IsNull(savedApplicant); } } } <file_sep>/Software41.BackgroundCheck.Domain/EmploymentHistory.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Software41.BackgroundCheck.Domain { public class EmploymentHistory { public int EmploymentHistoryId { get; set; } public String EmployerName { get; set; } public String JobTitle { get; set; } public Double Salary { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } } } <file_sep>/Software41.BackgroundCheck.Web/TestingFakes/FakeApplicantRepository.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using Software41.BackgroundCheck.Repository; using Software41.BackgroundCheck.Domain; namespace Software41.BackgroundCheck.Web.TestingFakes { public class FakeApplicantRepository : IApplicantRepository { private static List<Applicant> applicants = new List<Applicant>() { new Applicant { Id = 1, FirstName = "Ben", LastName = "Runchey", MiddleName = "John"}, new Applicant { Id =2, FirstName = "David", LastName = "O'Brien", MiddleName = "Something Irish?"} }; public List<Applicant> GetAll() { return applicants; } public void Save(Applicant applicant) { applicants[applicants.FindIndex(a => a.Id == applicant.Id)] = applicant; } public Applicant FindBy(System.Linq.Expressions.Expression<Func<Applicant, bool>> predicate) { return applicants.AsQueryable().Where(predicate).FirstOrDefault(); } public void Add(Applicant applicant) { throw new NotImplementedException(); } public void Update(Applicant applicant) { throw new NotImplementedException(); } public void Delete(Applicant applicant) { throw new NotImplementedException(); } IEnumerable<Applicant> IApplicantRepository.GetAll() { throw new NotImplementedException(); } IEnumerable<Applicant> IApplicantRepository.FindBy(System.Linq.Expressions.Expression<Func<Applicant, bool>> predicate) { throw new NotImplementedException(); } public Applicant FindById(int id) { throw new NotImplementedException(); } } }<file_sep>/Software41.BackgroundCheck.Repository.EF/BackgroundCheckContext.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Data.Entity; using System.Data.Entity.Infrastructure; using Software41.BackgroundCheck.Domain; using Software41.BackgroundCheck.Repository; namespace Software41.BackgroundCheck.Repository.EF { public class BackgroundCheckContext:DbContext, IUnitOfWork { public BackgroundCheckContext() : base("Software41.BackgroundCheckDb") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); //The following apparently can also be accomplished by using the commented out line of code, //but I like the explicit table naming. //modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); modelBuilder.Entity<Applicant>().ToTable("Applicant"); modelBuilder.Entity<AddressHistory>().ToTable("AddressHistory"); modelBuilder.Entity<EmploymentHistory>().ToTable("EmploymentHistory"); modelBuilder.Entity<EducationHistory>().ToTable("EducationHistory"); //Keys modelBuilder.Entity<Applicant>().HasKey(a => a.Id); //References modelBuilder.Entity<Applicant>() .HasMany<AddressHistory>(c => c.AddressHistory) .WithOptional() .WillCascadeOnDelete(true); //References modelBuilder.Entity<Applicant>() .HasMany<EmploymentHistory>(c => c.EmploymentHistory) .WithOptional() .WillCascadeOnDelete(true); //References modelBuilder.Entity<Applicant>() .HasMany<EducationHistory>(c => c.EducationHistory) .WithOptional() .WillCascadeOnDelete(true); } public void Commit() { this.SaveChanges(); } } } <file_sep>/Software41.BackgroundCheck.Domain/DegreeType.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Software41.BackgroundCheck.Domain { public enum DegreeType { HighSchoolDiploma, AssociateOfArts, BachelorOfScience, BachelorOfArts, Masters, Phd } } <file_sep>/Software41.BackgroundCheck.Web/App_Start/ContainerConfiguration.cs using Autofac; using Autofac.Integration.Mvc; using Autofac.Integration.WebApi; using Software41.BackgroundCheck.Repository; using Software41.BackgroundCheck.Repository.EF; using Software41.BackgroundCheck.Web.Controllers; using Software41.BackgroundCheck.Web.TestingFakes; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; using System.Web.Mvc; using System.Web.Http; namespace Software41.BackgroundCheck.Web { public class ContainerConfiguration { public static void Configure() { var builder = new ContainerBuilder(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterType<BackgroundCheckContext>().As<IUnitOfWork>().InstancePerHttpRequest(); builder.RegisterType<EFApplicantRepository>().As<IApplicantRepository>(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); } } }<file_sep>/Software41.BackgroundCheck.Repository/IApplicantRepository.cs using System; using System.Collections.Generic; using System.Linq; using Software41.BackgroundCheck.Domain; namespace Software41.BackgroundCheck.Repository { public interface IApplicantRepository { IEnumerable<Applicant> GetAll(); IEnumerable<Applicant> FindBy(System.Linq.Expressions.Expression<Func<Applicant, bool>> predicate); Applicant FindById(int id); void Save(Applicant applicant); void Delete(Applicant applicant); } } <file_sep>/Software41.BackgroundCheck.Repository.EF/Migrations/201408032349516_InitialMigration.cs namespace Software41.BackgroundCheck.Repository.EF.Migrations { using System; using System.Data.Entity.Migrations; public partial class InitialMigration : DbMigration { public override void Up() { CreateTable( "dbo.AddressHistory", c => new { AddressHistoryId = c.Int(nullable: false, identity: true), Address1 = c.String(), Address2 = c.String(), City = c.String(), State = c.String(), Zip = c.String(), FromDate = c.String(), ToDate = c.String(), Applicant_Id = c.Int(), }) .PrimaryKey(t => t.AddressHistoryId) .ForeignKey("dbo.Applicant", t => t.Applicant_Id, cascadeDelete: true) .Index(t => t.Applicant_Id); CreateTable( "dbo.Applicant", c => new { Id = c.Int(nullable: false, identity: true), FirstName = c.String(), LastName = c.String(), MiddleName = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.EducationHistory", c => new { EducationHistoryId = c.Int(nullable: false, identity: true), SchoolName = c.String(), SchoolType = c.Int(nullable: false), AttendedFrom = c.DateTime(nullable: false), AttendedTo = c.DateTime(nullable: false), Graduated = c.Boolean(nullable: false), DegreeType = c.Int(nullable: false), Applicant_Id = c.Int(), }) .PrimaryKey(t => t.EducationHistoryId) .ForeignKey("dbo.Applicant", t => t.Applicant_Id, cascadeDelete: true) .Index(t => t.Applicant_Id); CreateTable( "dbo.EmploymentHistory", c => new { EmploymentHistoryId = c.Int(nullable: false, identity: true), EmployerName = c.String(), JobTitle = c.String(), Salary = c.Double(nullable: false), StartDate = c.DateTime(nullable: false), EndDate = c.DateTime(nullable: false), Applicant_Id = c.Int(), }) .PrimaryKey(t => t.EmploymentHistoryId) .ForeignKey("dbo.Applicant", t => t.Applicant_Id, cascadeDelete: true) .Index(t => t.Applicant_Id); } public override void Down() { DropForeignKey("dbo.EmploymentHistory", "Applicant_Id", "dbo.Applicant"); DropForeignKey("dbo.EducationHistory", "Applicant_Id", "dbo.Applicant"); DropForeignKey("dbo.AddressHistory", "Applicant_Id", "dbo.Applicant"); DropIndex("dbo.EmploymentHistory", new[] { "Applicant_Id" }); DropIndex("dbo.EducationHistory", new[] { "Applicant_Id" }); DropIndex("dbo.AddressHistory", new[] { "Applicant_Id" }); DropTable("dbo.EmploymentHistory"); DropTable("dbo.EducationHistory"); DropTable("dbo.Applicant"); DropTable("dbo.AddressHistory"); } } } <file_sep>/Software41.BackgroundCheck.Web/app/views/applicantList.html <div class="panel-heading">Applicant Summary</div> <div class="alert alert-danger" ng-show="isError"> Error ({{isError.status}}). The product data was not loaded. <a href="/app.html" class="alert-link">Click here to try again</a> </div> <div class="panel-body"> <table class="table table-striped table-condensed"> <thead> <tr><th>First Name</th><th>Last Name</th><th>Middle Name</th><th></th></tr> </thead> <tbody> <tr ng-repeat='applicant in applicants | orderBy:"LastName"'> <td>{{applicant.FirstName}}</td> <td>{{applicant.LastName}}</td> <td>{{applicant.MiddleName}}</td> <td> <a href='#/applicant/{{applicant.Id}}'>edit</a> </td> </tr> </tbody> </table> <button type="Add" class="btn btn-primary">Add New</button> </div><file_sep>/Software41.BackgroundCheck.Domain/Applicant.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Software41.BackgroundCheck.Domain { public class Applicant { public Applicant() { this.EmploymentHistory = new List<EmploymentHistory>(); this.AddressHistory = new List<AddressHistory>(); this.EducationHistory = new List<EducationHistory>(); } public int Id { get; set; } public String FirstName { get; set; } public String LastName { get; set; } public String MiddleName { get; set; } public virtual List<AddressHistory> AddressHistory { get; set; } public virtual List<EducationHistory> EducationHistory { get; set; } public virtual List<EmploymentHistory> EmploymentHistory { get; set; } } } <file_sep>/Software41.BackgroundCheck.Web/app/services/applicantService.js  backgroundCheckApp .factory('applicantService', ['$http', function ($http) { var applicantSvc = {}; applicantSvc.getApplicants = function () { return $http({ method: 'GET', url: '../applicant' }); } applicantSvc.getApplicantDetails = function (id) { return $http({ method: 'GET', url: '../applicant/' + id }); } applicantSvc.create = function (applicant) { return $http({ method: "POST", url: '../applicant/', data: applicant }); } applicantSvc.update = function (applicant) { return $http({ method: "PUT", url: '../applicant/' + applicant.Id, data: applicant }); } return applicantSvc; }]); <file_sep>/Software41.BackgroundCheck.Web/Controllers/ApplicantController.cs using Software41.BackgroundCheck.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Software41.BackgroundCheck.Repository; namespace Software41.BackgroundCheck.Web.Controllers { public class ApplicantController : Controller { private IApplicantRepository appRepo; private IUnitOfWork unitOfWork; public ApplicantController (IApplicantRepository applicantRepo, IUnitOfWork unitOfWork) { this.appRepo = applicantRepo; this.unitOfWork = unitOfWork; } // // GET: /Applicant/ public ActionResult Index() { var applicants = this.appRepo.GetAll(); return View(applicants); } public ActionResult Applicant(int Id) { return View(this.appRepo.FindById(Id)); } [HttpPost] public ActionResult Applicant(Applicant applicant) { this.appRepo.Save(applicant); this.unitOfWork.Commit(); return RedirectToAction("Index"); } } }<file_sep>/Software41.BackgroundCheck.Repository.EF.Tests/DomainHelper.cs using System; using System.Collections; using Software41.BackgroundCheck.Domain; namespace Software41.BackgroundCheck.Repository.EF.Tests { public static class DomainHelper { #region Private Convenience Methods public static Applicant CreateApplicant(string firstName,string middleName,string lastName,int id=0) { return new Applicant { Id = id, FirstName = firstName, LastName = lastName, MiddleName = middleName }; } public static void AddEmploymentHistory(Applicant applicant,int numRecords) { for (int i = 1; i <= numRecords;i++ ) { applicant.EmploymentHistory.Add( new EmploymentHistory { EmployerName = "Benesyst_" + i.ToString(), JobTitle = "Programmer_" + i.ToString(), Salary = 90000 * i, StartDate = new DateTime(2005, 2, 5), EndDate = new DateTime(2006, 6, 5) }); } } public static void AddEducationHistory(Applicant applicant,int numRecords) { if (numRecords > 5) throw new ArgumentException("Who do you think you are, Einstein?"); int attendedSeed = 1980; for(int i=1;i<=numRecords;i++) { applicant.EducationHistory.Add(new EducationHistory { SchoolName = "School_" + i.ToString(), SchoolType = GetSchoolType(i), DegreeType = GetDegreeType(i), Graduated = true, AttendedFrom = new DateTime(attendedSeed +i,8,30), AttendedTo = new DateTime(attendedSeed + (i+1),6,15) }); } } public static void AddAddressHistory(Applicant applicant, int numRecords) { for (int i = 1; i <= numRecords;i++) { applicant.AddressHistory.Add(new AddressHistory { Address1 = "123" + i.ToString() + " Main Street", Address2 = "", City = "Mendota Heights", State = "MN", Zip = "55118", FromDate = "200" + i.ToString() + "/4/4", ToDate = "200" + i+1.ToString() + "/4/4", }); } } private static SchoolType GetSchoolType(int seed) { SchoolType retType; switch(seed) { case 1: retType = SchoolType.HighSchool; break; case 2: retType = SchoolType.TechnicalSchool; break; case 3: case 4: case 5: retType = SchoolType.University; break; default: retType = SchoolType.HighSchool; break; } return retType; } private static DegreeType GetDegreeType(int seed) { DegreeType retType; switch(seed) { case 1: retType = DegreeType.HighSchoolDiploma; break; case 2: retType = DegreeType.AssociateOfArts; break; case 3: retType = DegreeType.BachelorOfArts; break; case 4: retType = DegreeType.Masters; break; case 5: retType = DegreeType.Phd; break; default: retType = DegreeType.HighSchoolDiploma; break; } return retType; } #endregion } } <file_sep>/Software41.BackgroundCheck.Web/app/controllers/applicantController.js  backgroundCheckApp.controller('applicantsController', function ($scope, applicantService) { $scope.applicants = {}; //todo - add search filter here for results applicantService.getApplicants() .success(function (data) { $scope.applicants = data; }) .error(function (error) { $scope.isError = error; }); }); backgroundCheckApp.controller('applicantController', function ($scope, $routeParams, $location, applicantService) { $scope.id = $routeParams.Id; $scope.applicant; $scope.saveApplicant = function () { if ($scope.id == '') { applicantService.create($scope.applicant); } else { applicantService.update($scope.applicant); } $location.path('/'); }; if ($scope.id != ''){ applicantService.getApplicantDetails($scope.id) .success(function (data) { $scope.applicant = data; }) .error(function (error) { $scope.isError = error; }); }; }); <file_sep>/Software41.BackgroundCheck.Web/Api/ApplicantController.cs using Software41.BackgroundCheck.Domain; using Software41.BackgroundCheck.Repository; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; namespace Software41.BackgroundCheck.Web.Api { public class ApplicantController : ApiController { private IApplicantRepository appRepo; private IUnitOfWork unitOfWork; public ApplicantController(IApplicantRepository appRepo, IUnitOfWork unitOfWork) { this.appRepo = appRepo; this.unitOfWork = unitOfWork; } // GET api/<controller> [Route("applicant")] [HttpGet] public IEnumerable<Applicant> GetAll() { return appRepo.GetAll(); } // GET api/<controller>/5 [Route("applicant/{id}")] [HttpGet] public Applicant Get(int id) { return appRepo.FindById(id); } // POST <controller> [Route("applicant")] [HttpPost] public void Create(Applicant applicant) { this.appRepo.Save(applicant); this.unitOfWork.Commit(); HttpContext.Current.Response.AddHeader("Location", "applicant/" + applicant.Id); } [Route("applicant/{id}")] [HttpPut] public void Update(int id, Applicant applicant) { this.appRepo.Save(applicant); this.unitOfWork.Commit(); } } }<file_sep>/readme.md # Background Check <file_sep>/Software41.BackgroundCheck.Web.Tests/ApplicantControllerTests.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Software41.BackgroundCheck.Web.Controllers; using Software41.BackgroundCheck.Repository; using Software41.BackgroundCheck.Domain; using System.Collections.Generic; using System.Web.Mvc; using System.Linq.Expressions; namespace Software41.BackgroundCheck.Web.Tests { [TestClass] public class ApplicantControllerTests { [TestMethod] public void GetIndex_ExpectSuccess() { //arrange var mockApplicantRepo = new Mock<IApplicantRepository>(); var mockUnitOfWork = new Mock<IUnitOfWork>(); var applicantList = new List<Applicant>() { new Applicant { Id = 1, FirstName = "Ben", LastName = "Runchey", MiddleName = "John"}, new Applicant { Id =2, FirstName = "David", LastName = "O'Brien", MiddleName = "Something Irish?"} }; mockApplicantRepo.Setup(m => m.GetAll()).Returns(applicantList); var appController = new ApplicantController(mockApplicantRepo.Object, mockUnitOfWork.Object); //act var result = appController.Index() as ViewResult; // Assert Assert.IsNotNull(result, "Should have returned a ViewResult"); Assert.AreEqual("", result.ViewName, "View name should have been blank"); var applicants = result.ViewData.Model; Assert.AreSame(applicantList, applicants); } [TestMethod] public void GetApplicant_ExpectSuccess() { //arrange var mockApplicantRepo = new Mock<IApplicantRepository>(); var mockUnitOfWork = new Mock<IUnitOfWork>(); var expectedApplicant = new Applicant { Id = 1, FirstName = "Ben", LastName = "Runchey", MiddleName = "John"}; mockApplicantRepo.Setup(m => m.FindById(It.IsAny<int>())).Returns(expectedApplicant); var appController = new ApplicantController(mockApplicantRepo.Object, mockUnitOfWork.Object); //act var result = appController.Applicant(1) as ViewResult; //Assert var applicant = result.ViewData.Model; Assert.AreSame(expectedApplicant, applicant); } [TestMethod] public void GetApplicant_DoesNotExist_ExpectSuccess() { //arrange var mockApplicantRepo = new Mock<IApplicantRepository>(); var mockUnitOfWork = new Mock<IUnitOfWork>(); Applicant nullApplicant = null; mockApplicantRepo.Setup(m => m.FindById(It.IsAny<int>())).Returns(nullApplicant); var appController = new ApplicantController(mockApplicantRepo.Object, mockUnitOfWork.Object); //act var result = appController.Applicant(1) as ViewResult; //Assert var applicant = result.ViewData.Model; Assert.IsNull(applicant); } [TestMethod] public void TestPostApplicant_ExpectSuccess() { //arrange var mockApplicantRepo = new Mock<IApplicantRepository>(); var mockUnitOfWork = new Mock<IUnitOfWork>(); mockApplicantRepo.Setup(m => m.Save(It.IsAny<Applicant>())); var appController = new ApplicantController(mockApplicantRepo.Object, mockUnitOfWork.Object); //act var applicantToUpdate = new Applicant(){Id=2, FirstName="George", LastName="McFly", MiddleName="X"}; var result = appController.Applicant(applicantToUpdate) as RedirectToRouteResult; //assert Assert.AreEqual("Index", result.RouteValues["action"]); } [TestMethod, Ignore] public void TestPostApplicant_DoesNotExist_ExpectException() { } } } <file_sep>/Software41.BackgroundCheck.Web/TestingFakes/FakeUnitOfWork.cs using Software41.BackgroundCheck.Repository; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Software41.BackgroundCheck.Web.TestingFakes { public class FakeUnitOfWork : IUnitOfWork { public void Commit() { //nothing } } }<file_sep>/Software41.BackgroundCheck.Repository/IApplicantContext.cs using System; using System.Data.Entity; using Software41.BackgroundCheck.Domain; namespace Software41.BackgroundCheck.Repository { public interface IApplicantContext { IDbSet<Applicant> Applicant {get;} IDbSet<AddressHistory> AddressHistory { get;} IDbSet<EmploymentHistory> EmploymentHistory { get;} IDbSet<EducationHistory> EducationHistory { get;} } } <file_sep>/Software41.BackgroundCheck.Domain/AddressHistory.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Software41.BackgroundCheck.Domain { public class AddressHistory { public int AddressHistoryId { get; set; } public String Address1 { get; set; } public String Address2 { get; set; } public String City { get; set; } public String State { get; set; } public String Zip { get; set; } public String FromDate { get; set; } public String ToDate { get; set; } } }
11fc83457c501a20accbb42a83250352bd106197
[ "JavaScript", "C#", "HTML", "Markdown" ]
22
C#
onebuck1503/BackgroundCheck
0597ca7ce15e74adbc7765f77517f213bc048860
090bd1bf7a5343ec986af943fc078aba677b3635
refs/heads/master
<repo_name>jhsir/redissonhash<file_sep>/src/main/java/redisson/RedisFactory.java package redisson; import org.redisson.Redisson; import org.redisson.api.RedissonClient; import org.redisson.config.Config; public class RedisFactory { //単节点客户端 private static RedissonClient rediscli ; //哨兵客户端 private static RedissonClient redisSencli; private RedisFactory() { } /** * 单节点单例 * @return */ public static RedissonClient getRedis() { if (rediscli == null) { synchronized(RedisFactory.class) { if(rediscli == null) { Config config = new Config(); //config.setTransportMode(TransportMode.EPOLL); config.useSingleServer().setAddress("redis://www.jhcoder.top:6379").setPassword("<PASSWORD>"); RedissonClient cli = Redisson.create(config); rediscli = cli; } } } return rediscli; } /** * 哨兵单例 * @return */ public static RedissonClient getSenRedis() { if (redisSencli == null) { synchronized(RedisFactory.class) { if(redisSencli == null) { Config config = new Config(); config.useSentinelServers() .setMasterName("mymaster") .addSentinelAddress("redis://www.jhcoder.top:16301","redis://www.jhcoder.top:16302","redis://www.jhcoder.top:16303") .setPassword("<PASSWORD>"); RedissonClient cli = Redisson.create(config); redisSencli = cli; } } } return redisSencli; } } <file_sep>/src/main/java/redisson/RunLock.java package redisson; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class RunLock { public static void main(String[] args) throws InterruptedException { RedissonClient client = RedisFactory.getRedis(); ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); //新建一个公平锁 RLock rlock = client.getFairLock("jhcoder_lock001"); // 等待10s后释放锁 rlock.tryLock(100, 10, TimeUnit.SECONDS); //线程每1s检查锁是否打开 executor.scheduleAtFixedRate(new TrySout(rlock), 1, 1, TimeUnit.SECONDS); } } class TrySout implements Runnable { RLock rlock = null; public TrySout(RLock rlock) { this.rlock = rlock; } public void run() { if(rlock.isLocked()) { System.out.println("锁了"); }else { System.out.println("没锁"); } } }
88e6095ae604b28bc369930d239d0cccbd708b26
[ "Java" ]
2
Java
jhsir/redissonhash
df1589be9aa4044a3098da479ded58d734085b41
01855f4cd965f95e9aca9ad71cd4ae74b229abce
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package csvintxt; /** * * @author alexandrelerario */ public class CsvInTxt { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here // System.out.println("CSV file name:"); // String csvfile = new java.util.Scanner(System.in).nextLine(); // new br.CsvReader().print("/Users/alexandrelerario/Desktop/a/CSVmergeTXT/CsvInTxt/src/relac.csv", ";"); //System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); //System.out.println(new br.TxtReader().Reader("/Users/alexandrelerario/Desktop/a/CSVmergeTXT/CsvInTxt/src/texTrad.tex")); String troca = new br.Replacer().Replace("/Users/alexandrelerario/Desktop/a/CSVmergeTXT/CsvInTxt/src/texTrad.tex", "/Users/alexandrelerario/Desktop/a/CSVmergeTXT/CsvInTxt/src/relac.csv", ";"); // System.out.println(troca); new br.TxtReader().Save("/Users/alexandrelerario/Desktop/a/CSVmergeTXT/CsvInTxt/src/pronto.tex", troca); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author alexandrelerario */ public class Replacer { public String Replace(String txtFile, String csvFile, String separator){ String vfinal=null; //int trocas=0; String txtInicial=new br.TxtReader().Reader(txtFile); vfinal=txtInicial; java.util.ArrayList<String[]> kw = new br.CsvReader().Reader(csvFile, separator); for (String[] strings : kw) { //vfinal.replaceAll(strings[0], "zz "+ strings[1]); System.out.println("Subst: " + strings[0]); CharSequence c1, c2; c1 = strings[0]; c2 = strings[1]; vfinal = vfinal.replace(c1, c2); //trocas++; } return vfinal; } }
2e431eebc7cc2fd665421a6cd0c2702a474aba32
[ "Java" ]
2
Java
alerario/CSVmergeTXT
38a3c0d660749589466f4f950987796c96743182
1b39f000e9c048ffb065a0cd47faf736feb0ffd4
refs/heads/master
<repo_name>thinkful-ei-iguana/Anthony-Harrison-Day-1-JS<file_sep>/function-2.js 'use strict'; function jediName(firstName, lastName) { return lastName.slice(0, 3) + firstName.slice(0, 2); } console.log(jediName('Anthony', 'Bostic')); function beyond(num) { if (num === Infinity) { console.log('And beyond'); } else if (num !== Infinity && num > 0) { console.log('To infinity'); } else if (num !== Infinity && num < 0) { console.log('To negative infinity'); } else if (num === 0) { console.log('Staying home'); } } beyond(6 / 0); function decode(word) { let newArr = word.split(''); for (let i of newArr) { if (i === 'a') { return newArr[1]; } else if (i === 'b') { return newArr[2]; } else if (i === 'c') { return newArr[3]; } else if (i === 'd') { return newArr[4]; } else { return ' '; } } } console.log(decode('droop')); function daysInAMonth(month, leapYear) { switch (month) { case 'January': case 'March': case 'May': case 'July': case 'August': case 'October': case 'December': console.log(`The ${month} has 31 days`); break; case 'April': case 'June': case 'September': case 'November': console.log(`The ${month} has 30 days`); break; case 'Febuary': if (leapYear === true) { console.log(`The ${month} has 29 days`); } else { console.log(`The ${month} has 28 days`); } break; default: console.log('Must provide a valid month'); } } console.log(daysInAMonth('Febuary', false)); function rockPaper(num) { const rock = 1; const paper = 2; const scissors = 3; const randomNo = Math.floor(Math.random() * 3) + 1; if (num > 3 || num < 1) { return new Error('Input must be a number 1 - 3'); } switch (num) { case 1: console.log('rock'); if (randomNo === 2) { console.log('You Lost'); } else if (randomNo === 3) { console.log('You Win'); } break; case 2: console.log('paper'); if (randomNo === 3) { console.log('You Lost'); } else if (randomNo === 1) { console.log('You Win'); } break; case 3: console.log('scissors'); if (randomNo === 1) { console.log('You Lost'); } else if (randomNo === 2) { console.log('You Win'); } break; } } console.log(rockPaper(3));
450a300f7741dc08f5b75c1a57d1bd2d41f7a2f0
[ "JavaScript" ]
1
JavaScript
thinkful-ei-iguana/Anthony-Harrison-Day-1-JS
077f585b29d259dfe57ae30a7ce11e0a14e2dca3
6daa3df0cba822ddd1762e9f9c1b26e5c2aacb59
refs/heads/master
<repo_name>danchelsea/Scrips-Oracle<file_sep>/StoreProcedure.sql -- Hiển thị thông tin phòng ban khi nhập mã phòng ban create or replace procedure thongtinphongban(v_mapb number, ten out PhongBan.tenpb%type) as begin select tenpb into ten from PhongBan where mapb=v_mapb; dbms_output.put_line('Ten phong ban: '||ten); exception when no_data_found then dbms_output.put_line('Khong co phong ban'); end; set serveroutput on declare ten PhongBan.tenpb%type; begin DEPT_INFO(&v_mapb, ten); end; -- xóa nhân viên khi nhập mã nhân viên create or replace procedure xoanv(manhanvien number) as begin delete from NhanVien where manv=manhanvien; dbms_output.put_line('Da xoa'||manhanvien||'thanh cong!'); end; <file_sep>/Function.sql -- tính tổng lương của phòng ban khi nhập mã phòng Create or replace function tongluong(maphongban in number) return number as v_luong number; begin select sum(luong) into v_luong from NhanVien where mapb=maphongban; return v_luong; exception when no_data_found then return('Du lieu khong tim thay'); when others then return('loi ham'); end; set serveroutput on show error; select column_name, data_type, data_length from user_tab_columns where table_name='NhanVien'; SELECT mapb FROM PhongBan; set serveroutput on set verify off execute dbms_output.put_line('Tong luong la: '||tongluong(&maphongban)); <file_sep>/DQL.sql SELECT * FROM NhanVien; -- SELECT MaNV,TenNV,NgaySinh From NhanVien Where DiaChi = 'Hà Nội' or Diachi='Hưng Yên' ; -- Select * From NhanVien Where TenNV like '%D%'; -- Select nv.mapb, pb.tenpb, count(*) from(select mapb from NhanVien) nv inner join (select mapb,tenpb from PhongBan) pb on nv.mapb= pb.mapb group by nv.mapb, pb.tenpb;<file_sep>/DML.sql --insert data INSERT INTO PhongBan values('GPPM1','Giải pháp phần mềm 1','Nguyễn Văn A'); INSERT INTO PhongBan values('GPPM2','Giải pháp phần mềm 2','Nguyễn Văn B'); INSERT INTO NhanVien(TenNV,NgaySinh,Gioitinh,diachi,Mapb) values('<NAME>','06-NOV-1998','Nam','Hưng Yên','GPPM1'); INSERT INTO NhanVien(TenNV,NgaySinh,Gioitinh,diachi,Mapb) values('<NAME>','24/JUN/1998','Nam','Hưng Yên','GPPM2'); --update data UPDATE NhanVien set DiaChi = 'Hà Nội' where MaNV= 2 ; --Delete data DELETE FROM NhanVien NV where NV.MAPB = 'GPPM2' ; Commit;<file_sep>/DDL.sql -- create table (id auto_increment) Create table PhongBan( MaPB varchar2(20) CONSTRAINT pk_MaPB PRIMARY KEY, TenPB varchar2(100) not null ); Create table NhanVien( MaNV NUMBER GENERATED ALWAYS AS IDENTITY, TenNV varchar2(100) not null, NgaySinh Date not null, GioiTinh varchar2(5) not null, DiaChi varchar2(150) not null, MaPB varchar2(20) not null, CONSTRAINT fk_mapb FOREIGN KEY (MaPB) REFERENCES PhongBan(MaPB) ); --alter table alter table PhongBan add TruongPhong varchar2(100) not null; alter table NhanVien add Luong float(20) not null; alter table NhanVien modify DiaChi varchar2(200); -- Drop table DROP TABLE NhanVien <file_sep>/Package.sql --thủ tục cho biết thông tin lương của nhân viên và tổng lương của phòng ban khi nhập mã nhân viên mã phòng ban . create or replace package thongtinluong as procedure luongnv(v_manv NhanVien.manv%TYPE); function tongluong (mapb PhongBan.mapb%TYPE) return number; end; -- create or replace package body thongtinluong as procedure luongnv(v_manv NhanVien.manv%TYPE) as v_luong NhanVien.luong%TYPE; begin select luong into v_luong from NhanVien where manv= v_manv; dbms_output.put_line('luong cua nhan vien nay la:' || v_luong); exception when no_data_found then dbms_output.put_line('ko tim thay nhan vien nay'); end luongnv; function tongluong(v_mapb PhongBan.mapb%TYPE) return number as tongluongpb number; begin select sum(luong) into tongluongpb from NhanVien where mapb=v_mapb; return tongluongpb; exception when no_data_found then dbms_output.put_line('ko tim thay phong ban'); end tongluongpb; end thongtinluong;
6fe44aa7d77d67efaf6ba842107a5888841188d7
[ "SQL" ]
6
SQL
danchelsea/Scrips-Oracle
3d48f7fe5c2daa29e86beb2d7dab8a199efcd245
d4f806e8c6ccc019e946c3d85564cdd3192fca44
refs/heads/master
<repo_name>cellargalaxy/wallPaperPlay<file_sep>/requirements.txt altgraph==0.17 future==0.18.2 pefile==2019.4.18 Pillow==7.2.0 pydub==0.24.1 pyinstaller==4.0 pyinstaller-hooks-contrib==2020.7 pywin32==228 pywin32-ctypes==0.2.0 simpleaudio==1.0.4 <file_sep>/README.md # wallPaperPlay 这是一个动态壁纸播放器(替换器),会监控窗口焦点。如果没有窗口焦点则会播放壁纸,否则停止。停止后可播放一段音频。 This is a live wallpaper player (replacer) that monitors the window focus. If there is no window focus, the wallpaper will be played, otherwise it will stop. After stopping, a piece of audio can be played. 不依赖于ffmpeg,但是或许需要ffmpeg来处理视频和音频。 Does not depend on ffmpeg, but may need ffmpeg to handle video and audio. ```batch ffmpeg -i "E:/bt/视频/video.mkv" -vf "drawtext=fontsize=15:fontcolor=gray:text='%{pts\:hms}'" -r 4 -q:v 2 -f image2 "E:/bt/视频/images/%05d.jpeg" ffmpeg -i "E:/bt/视频/video.mkv" -ac 2 "E:/bt/视频/audio.wav" ``` 在可执行文件目录下创建一个名为`wall_paper_play.json`的文件保存配置。 Create a file named `wall_paper_play.json` in the executable file directory to save the configuration of json. ```json { "blankSpace": [ //wall_paper_play会检测当前焦点所在的窗口名称,配置某些窗口名称,使得壁纸进行播放 [ null, "program manager" ] ], "imageFolderPath": "E:/bt/视频/images", //使用ffmpeg生成的图片的文件夹 "imageIndex": 8000, //当前播放到图片的下标 "frameRate": 4, //每秒多少帧,与ffmpeg的-r参数一致 "audioPath": "E:/bt/视频/audio.wav", //音频路径,为空则不播放音频 "audioVolume": -10, //音频音量调整 "audioLength": 10000, //音频播放毫秒 "audioFadeIn": 3000, //音频渐入毫秒 "audioFadeOut": 4000, //音频渐出毫秒 "noWindowPlayTime": 3, //多少秒无窗口焦点则播放 "checkWindowTime": 1, //间隔多久监听一次窗口焦点 "logPath": "E:/bt/视频/wall_paper.log", //日志路径 "currentWallPaperPath": "E:/bt/视频/current_wall_paper.jpg", //保存当前壁纸路径,为空则不保存 "currentBlackWallPaperPath": "E:/bt/视频/current_black_wall_paper.jpg", //保存当前黑遮罩壁纸路径,为空则不保存 "blackConcentration": 230 //黑遮罩壁纸黑程度 } ``` <file_sep>/wall_paper_play.py import json import logging import os import shutil import time from ctypes import * from threading import Thread from time import sleep import win32api import win32con import win32gui import pywintypes from PIL import Image, ImageDraw from pydub import AudioSegment from pydub.playback import play # ffmpeg -i "E:/bt/视频/video.mkv" -vf "drawtext=fontsize=15:fontcolor=gray:text='%{pts\:hms}'" -r 4 -q:v 2 -f image2 "E:/bt/视频/images/%05d.jpeg" # ffmpeg -i "E:/bt/视频/video.mkv" -ac 2 "E:/bt/视频/audio.wav" # pydub只支持一通道或者两通道的音频 user32 = windll.user32 kernel32 = windll.kernel32 psapi = windll.psapi CONFIG_FILE_PATH = 'wall_paper_play.json' DEFAULT_CONFIG = { "blankSpace": [ [None, "program manager"] ], "imageFolderPath": "images", "imageIndex": 0, "frameRate": 4, "audioPath": "", "audioVolume": -10, "audioLength": 10000, "audioFadeIn": 3000, "audioFadeOut": 4000, "noWindowPlayTime": 3, "checkWindowTime": 1, "logPath": "wall_paper.log", "currentWallPaperPath": "", "currentBlackWallPaperPath": "", "blackConcentration": 230, } DEFAULT_CONFIG_JSON_STRING = json.dumps(DEFAULT_CONFIG) CONFIG = None AUDIO_SONG = None def load_config(): if not os.path.exists(CONFIG_FILE_PATH): print('加载配置,配置文件不存在') return None config_json_string = None try: with open(CONFIG_FILE_PATH, 'r', encoding='utf-8') as f: config_json_string = f.read() except: print('读取配置文件失败') return None # print('配置文件读取配置: ', config_json_string) try: config = json.loads(config_json_string) # print('反序列化配置: ', config) except: print('反序列化配置失败') return None return config def flush_config(): new_config = load_config() if new_config == None: return global CONFIG, DEFAULT_CONFIG if CONFIG == None: init_log(new_config) init_audit(new_config) else: if 'logPath' in new_config and new_config['logPath'] != CONFIG['logPath']: init_log(new_config) if 'audioPath' in new_config and new_config['audioPath'] != CONFIG['audioPath']: init_audit(new_config) for key, value in DEFAULT_CONFIG.items(): if key not in new_config: new_config[key] = value CONFIG = new_config logging.info('刷新配置: %r', CONFIG) def save_config(config): if config == None: logging.error('配置对象为空,保存对象失败') return try: config_json_string = json.dumps(config, indent=2) logging.info('序列化配置: %r', config_json_string) except: logging.error('序列化配置对象失败') return if not os.path.exists(CONFIG_FILE_PATH): logging.error('保存配置,配置文件不存在') return try: with open(CONFIG_FILE_PATH, 'w', encoding='utf-8') as f: f.write(config_json_string) except: logging.error('保存配置到文件失败') return logging.info('配置文件保存成功') def init_log(config): logging.basicConfig( filename=config['logPath'], level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%y-%m-%d %H:%M:%S', ) console = logging.StreamHandler() console.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console) logging.info('初始化日志完成') def copy_current_wall_paper(wall_paper_path, config): logging.info('开始复制当前壁纸') if wall_paper_path == None or wall_paper_path == '': logging.info('壁纸路径为空,不进行当前壁纸替换') return current_wall_paper_path = config['currentWallPaperPath'] if current_wall_paper_path == None or current_wall_paper_path == '': logging.info('当前壁纸路径为空,不进行当前壁纸替换') return shutil.copyfile(wall_paper_path, current_wall_paper_path) logging.info('成功复制当前壁纸') def black_current_wall_paper(wall_paper_path, config): logging.info('开始黑遮罩当前壁纸') if wall_paper_path == None or wall_paper_path == '': logging.info('壁纸路径为空,不进行当前壁纸黑遮罩') return current_black_wall_paper_path = config['currentBlackWallPaperPath'] if current_black_wall_paper_path == None or current_black_wall_paper_path == '': logging.info('当前黑遮罩壁纸路径为空,不进行当前壁纸黑遮罩') return black_concentration = config['blackConcentration'] image = Image.open(wall_paper_path) image = image.convert("RGBA") black_image = Image.new("RGBA", image.size, (0, 0, 0, 0)) draw = ImageDraw.Draw(black_image) draw.rectangle(((0, 0), image.size), fill=(0, 0, 0, black_concentration)) image = Image.alpha_composite(image, black_image) image = image.convert("RGB") image.save(current_black_wall_paper_path) logging.info('成功黑遮罩当前壁纸') def init_audit(config): global AUDIO_SONG if "audioPath" not in config or config["audioPath"] == None or config["audioPath"] == '': logging.info('无音频配置') AUDIO_SONG = None return AUDIO_SONG = AudioSegment.from_file(config["audioPath"]) def play_audio(config): global AUDIO_SONG if AUDIO_SONG == None: logging.info('无音频对象') return millisecond = config["imageIndex"] / config["frameRate"] * 1000 song = AUDIO_SONG[millisecond: millisecond + config["audioLength"]] song = song + config["audioVolume"] song = song.fade_in(config["audioFadeIn"]).fade_out(config["audioFadeOut"]) play(song) def init_wall_paper(): logging.info('开始配置壁纸注册表') # 打开指定注册表路径 reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) # 最后的参数:2拉伸,0居中,6适应,10填充,0平铺 win32api.RegSetValueEx(reg_key, "WallpaperStyle", 0, win32con.REG_SZ, "2") # 最后的参数:1表示平铺,拉伸居中等都是0 win32api.RegSetValueEx(reg_key, "TileWallpaper", 0, win32con.REG_SZ, "0") logging.info('成功配置壁纸注册表') def set_wall_paper(image_path): win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, image_path, win32con.SPIF_SENDWININICHANGE) class WallPaperTask: def __init__(self, config): self._running = True self.config = config self.sleep_time = 1.0 / self.config['frameRate'] def interrupt(self): self._running = False # 让调用方停一停,等本线程的run的sleep过了结束 time.sleep(self.sleep_time * 2) play_audio(self.config) def run(self): image_folder_path = self.config['imageFolderPath'] image_index = self.config['imageIndex'] wall_paper_path = '' while self._running: if not os.path.exists(image_folder_path): logging.error('文件夹不存在: %r', image_folder_path) break files = os.listdir(image_folder_path) if files == None or len(files) == 0: logging.error('文件夹没有文件') break if image_index < 0 or image_index >= len(files): logging.info('重置图片下标为0, image_index: %r', image_index) image_index = 0 for index in range(image_index, len(files)): wall_paper_path = os.path.join(image_folder_path, files[index]) set_wall_paper(wall_paper_path) image_index = image_index + 1 time.sleep(self.sleep_time) if not self._running: break self.config['imageIndex'] = image_index copy_current_wall_paper(wall_paper_path, self.config) black_current_wall_paper(wall_paper_path, self.config) logging.info('结束壁纸更换线程') def get_process_name(): hwnd = user32.GetForegroundWindow() pid = c_ulong(0) user32.GetWindowThreadProcessId(hwnd, byref(pid)) executable = create_string_buffer(512) h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid) psapi.GetModuleBaseNameA(h_process, None, byref(executable), 512) window_title = create_string_buffer(512) user32.GetWindowTextA(hwnd, byref(window_title), 512) kernel32.CloseHandle(hwnd) kernel32.CloseHandle(h_process) return [executable.value.decode('gbk'), window_title.value.decode('gbk')] def check_focus(): no_window_time = 0 wall_paper_task = None names = [[None, None], [None, None]] while True: check_window_time = CONFIG['checkWindowTime'] no_window_play_time = CONFIG['noWindowPlayTime'] blank_space = CONFIG['blankSpace'] name = get_process_name() names.pop(0) names.append(name) if names == None or len(names) != 2 or \ names[0] == None or len(names[0]) != 2 or \ names[1] == None or len(names[1]) != 2: logging.error('非法窗口结构') sleep(check_window_time) continue is_blank_space = False for blank_name in blank_space: if blank_name == None or len(blank_name) != 2: logging.error('空窗口名长度不为2: %r', blank_name) continue black1 = blank_name[0] == None or name[0].lower() == blank_name[0].lower() black2 = blank_name[1] == None or name[1].lower() == blank_name[1].lower() is_blank_space = black1 and black2 if is_blank_space: break if names[0][0] != names[1][0] or names[0][1] != names[1][1]: logging.info('焦点窗口变更为: %r', names[1]) if is_blank_space: logging.info('空桌面') if is_blank_space: no_window_time = no_window_time + check_window_time if no_window_time > no_window_play_time and wall_paper_task == None: logging.info('创建并启动线程') flush_config() wall_paper_task = WallPaperTask(CONFIG) thead = Thread(target=wall_paper_task.run, daemon=True) thead.start() elif wall_paper_task != None: logging.info('非空桌面,销毁线程') wall_paper_task.interrupt() save_config(wall_paper_task.config) no_window_time = 0 wall_paper_task = None sleep(check_window_time) def main(): flush_config() init_wall_paper() check_focus() if __name__ == '__main__': main()
68dac5d49a1bf1e32ae6a2d03f77de4c94860f06
[ "Markdown", "Python", "Text" ]
3
Text
cellargalaxy/wallPaperPlay
d664d524b6b5461d9bab96878652eb7965aa4f50
d16ccc6778930acbc343a2230f7baaccfc5f90c7
refs/heads/main
<file_sep>using System; using System.Drawing; using System.Windows.Forms; using System.Drawing.Drawing2D; using System.ComponentModel; /// <summary> /// Use this for drawing custom graphics and text with transparency. /// Inherit from DrawingArea and override the OnDraw method. /// </summary> public class TransparentLabel : Control { private string _text = "TransparentLabel"; private Point _textPosition = new Point(0, 0); private System.Drawing.Text.TextRenderingHint _TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; [Description("Text to show"), Category("Data")] public string TransparentText { get { return _text; } set { _text = value; Refresh(); } } [Description("Text position"), Category("Data")] public Point TextPosition { get { return _textPosition; } set { _textPosition = value; Refresh(); } } public System.Drawing.Text.TextRenderingHint TextRenderingHint { get { return _TextRenderingHint; } set { _TextRenderingHint = value; Refresh(); } } public System.Drawing.Drawing2D.InterpolationMode GraphicsInterpolationMode { get; set; } = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear; public System.Drawing.Drawing2D.PixelOffsetMode GraphicsPixelOffsetMode { get; set; } = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; public System.Drawing.Drawing2D.SmoothingMode GraphicsSmoothingMode { get; set; } = System.Drawing.Drawing2D.SmoothingMode.HighQuality; protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ExStyle |= 0x00000020; //WS_EX_TRANSPARENT return cp; } } public TransparentLabel() { base.SetStyle(ControlStyles.SupportsTransparentBackColor, true); } protected override void OnPaintBackground(PaintEventArgs pevent) { pevent.Graphics.FillRectangle(new SolidBrush(BackColor), 0, 0, this.Width, this.Height); } protected override void OnPaint(PaintEventArgs e) { // Update the private member so we can use it in the OnDraw method Graphics graphics = e.Graphics; // Set the best settings possible (quality-wise) graphics.TextRenderingHint = _TextRenderingHint; // System.Drawing.Text.TextRenderingHint.ClearTypeGridFit graphics.InterpolationMode = GraphicsInterpolationMode; // System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear; graphics.PixelOffsetMode = GraphicsPixelOffsetMode; // System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; graphics.SmoothingMode = GraphicsSmoothingMode; // System.Drawing.Drawing2D.SmoothingMode.HighQuality; TransparentLabel.DrawText(graphics, _text, this.Font, new SolidBrush(this.ForeColor), _textPosition); } static public void DrawText(Graphics graphics, string text, Font font, Brush color, Point position) { SizeF textSizeF = graphics.MeasureString(text, font); int width = (int)Math.Ceiling(textSizeF.Width); int height = (int)Math.Ceiling(textSizeF.Height); Size textSize = new Size(width, height); Rectangle rectangle = new Rectangle(position, textSize); graphics.DrawString(text, font, color, rectangle); } }<file_sep>using System; using System.ComponentModel.Design; using System.Drawing; using System.Windows.Forms; using System.Windows.Forms.Design; using CommandID = System.ComponentModel.Design.CommandID; using MenuCommand = System.ComponentModel.Design.MenuCommand; namespace RoboRemoPC { class MenuService : System.ComponentModel.Design.MenuCommandService { public delegate void OpenMenu(int x, int y); OpenMenu openMenuHandler; public MenuService(IServiceProvider serviceProvider, OpenMenu openMenuHandler) : base(serviceProvider) { this.openMenuHandler = openMenuHandler; } public override void ShowContextMenu(CommandID menuID, int x, int y) { openMenuHandler(x, y); } } } <file_sep>/* * Created by SharpDevelop. * User: Microsan84 * Date: 2017-05-06 * Time: 17:13 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; namespace RoboRemoPC { /// <summary> /// Description of VBWin. /// </summary> public abstract class VBWin_JAVAsrc { public static int bgColor; public static VBColorTheme colorTheme; private static String debugString = BuildConfig.VERSION_NAME; public static UiTextLog debugTextLog = null; public static float density; public static int h; public static MainActivity mainActivity = null; public static int masterColor; protected static Paint p = null; public static float scaledPixelDensity; public static int w; protected Context ct; public abstract void backPressed(); public abstract void paint(Canvas canvas); public VBWin() { super(mainActivity); LayoutParams params = new LayoutParams(-1, -1); params.weight = 0.0f; setLayoutParams(params); setBackgroundColor(colorTheme.bgColor); setOrientation(1); setWillNotDraw(false); postInvalidate(); this.ct = mainActivity; } public void onTick() { } public void pointerPressed(int x, int y) { } public void pointerReleased(int x, int y) { } public void pointerDragged(int x, int y) { } public boolean onTouchEvent(MotionEvent event) { int action = event.getActionMasked(); int x = (int) event.getX(); int y = (int) event.getY(); if (action == 0) { pointerPressed(x, y); } if (action == 2) { pointerDragged(x, y); } if (action == 1) { pointerReleased(x, y); } return true; } public void onDraw(Canvas cnv) { paint(cnv); } public void show() { MainActivity.win = this; repaint(); } public void repaint() { mainActivity.repaint(); } protected static int mcol(int br) { int col = masterColor; int red = (((col >> 16) & FT_4222_Defines.CHIPTOP_DEBUG_REQUEST) * br) / FT_4222_Defines.CHIPTOP_DEBUG_REQUEST; int green = (((col >> 8) & FT_4222_Defines.CHIPTOP_DEBUG_REQUEST) * br) / FT_4222_Defines.CHIPTOP_DEBUG_REQUEST; int blue = ((col & FT_4222_Defines.CHIPTOP_DEBUG_REQUEST) * br) / FT_4222_Defines.CHIPTOP_DEBUG_REQUEST; if (red > FT_4222_Defines.CHIPTOP_DEBUG_REQUEST) { red = FT_4222_Defines.CHIPTOP_DEBUG_REQUEST; } if (green > FT_4222_Defines.CHIPTOP_DEBUG_REQUEST) { green = FT_4222_Defines.CHIPTOP_DEBUG_REQUEST; } if (blue > FT_4222_Defines.CHIPTOP_DEBUG_REQUEST) { blue = FT_4222_Defines.CHIPTOP_DEBUG_REQUEST; } return (((((FT_4222_Defines.CHIPTOP_DEBUG_REQUEST << 8) + (red & FT_4222_Defines.CHIPTOP_DEBUG_REQUEST)) << 8) + (green & FT_4222_Defines.CHIPTOP_DEBUG_REQUEST)) << 8) + (blue & FT_4222_Defines.CHIPTOP_DEBUG_REQUEST); } public static int max(int a, int b) { return a > b ? a : b; } public static int min(int a, int b) { return a < b ? a : b; } public static int textW(String text) { Rect bounds = new Rect(); p.getTextBounds(text, 0, text.length(), bounds); return bounds.width(); } public static void debug(String st) { if (debugTextLog != null) { debugTextLog.append("\n" + st, true); debugTextLog.onChanged(); } } public static String getDebugString() { return debugString; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace RoboRemoPC { public partial class DebugLogForm : Form { public DebugLogForm() { InitializeComponent(); } } public static class Debug { public static DebugLogForm logForm; public static void AddLine(string text) { if (logForm == null) { logForm = new DebugLogForm(); logForm.Show(); } logForm.rtxt.AppendText(text + "\n"); } } } <file_sep>/* * Created by SharpDevelop. * User: Microsan84 * Date: 2017-05-06 * Time: 17:13 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; namespace RoboRemoPC { /// <summary> /// Description of Ui. /// </summary> public class Ui : VBWin_JAVAsrc { static int defaultTextSize; public static int fontAscent; public static int fontH; public static double gridSize = 0.1d; public static Paint paint; public static int textOffsetY; public String bgColor; public int charDelay; public String charDelayString; public String commandEnding; public String connectAction; public Vector<UiItem> items; public String name; private Vector pointers; public RelativeLayout rell = new RelativeLayout(VBWin.mainActivity); private String version; public Ui(Vector items) { addView(this.rell); this.name = BuildConfig.VERSION_NAME; this.connectAction = BuildConfig.VERSION_NAME; this.charDelayString = BuildConfig.VERSION_NAME; this.bgColor = "FFFFFFFF"; onBgColorChanged(); this.version = VBWin.mainActivity.getVersionName(); this.charDelay = MainActivity.charDelay; this.commandEnding = "\n"; this.pointers = new Vector(); paint = new Paint(); paint.setColor(-16777216); paint.setTextAlign(Align.CENTER); paint.setStrokeCap(Cap.ROUND); paint.setAntiAlias(true); setDefaultTextSize(); if (items == null) { this.items = new Vector(); UiButton menuButton = new UiButton(0.02f, 0.02f, 0.2f, 0.15f, "menu"); menuButton.local = true; menuButton.releaseAction = "menu"; this.items.add(menuButton); } else { this.items = items; } setFocusable(true); setFocusableInTouchMode(true); } public static void setTextSize(float textSize) { paint.setTextSize(VBWin.scaledPixelDensity * textSize); textOffsetY = (-((int) (paint.getFontMetrics().ascent + paint.getFontMetrics().descent))) / 2; fontAscent = (int) paint.getFontMetrics().ascent; fontH = (int) (paint.descent() - paint.ascent()); } public static float getDefaultTextSize() { return 15.0f; } public static void setDefaultTextSize() { setTextSize(getDefaultTextSize()); } public void clear() { this.items = new Vector(); UiButton menuButton = new UiButton(0.02f, 0.02f, 0.2f, 0.15f, "menu"); menuButton.local = true; menuButton.releaseAction = "menu"; this.items.add(menuButton); this.commandEnding = "\n"; this.connectAction = BuildConfig.VERSION_NAME; this.name = BuildConfig.VERSION_NAME; this.bgColor = "FFFFFFFF"; onBgColorChanged(); } public void onBgColorChanged() { setBackgroundColor((int) (Long.parseLong(this.bgColor, 16) & -1)); } public void paint(Canvas cnv) { int itemCount = this.items.size(); if (MainActivity.win == this && itemCount == 1) { drawHintText(cnv, (((BuildConfig.VERSION_NAME + "Welcome to " + MainActivity.appName + "\n\n") + "To start, click\n") + "menu > edit ui, or\n") + "menu > interface > import", w / 2, h / 2, -8355712); } for (int i = 0; i < itemCount; i++) { ((UiItem) this.items.elementAt(i)).paint(cnv); } if (itemCount == 2 && (MainActivity.win instanceof UiEditor)) { ((UiItem) this.items.elementAt(1)).paintMoveResizeHint(cnv, -1); } } public void stop() { int itemCount = this.items.size(); for (int i = 0; i < itemCount; i++) { ((UiItem) this.items.elementAt(i)).stop(); } MainActivity mainActivity = VBWin.mainActivity; MainActivity.saveInterface(); VBAcc.stop(); } public void start() { int i; onCharDelayStringChanged(); int itemCount = this.items.size(); String currentVersion = VBWin.mainActivity.getVersionName(); if (!this.version.equals(currentVersion)) { for (i = 0; i < itemCount; i++) { ((UiItem) this.items.elementAt(i)).updateFromVersion(this.version); } this.version = currentVersion; } for (i = 0; i < itemCount; i++) { ((UiItem) this.items.elementAt(i)).start(); } if (this.commandEnding.length() == 0) { VBWin.mainActivity.showAlertCommandEndingEmptyString(); } } public void updateProcessingItems() { int itemCount = this.items.size(); for (int i = 0; i < itemCount; i++) { UiItem item = (UiItem) this.items.elementAt(i); if (item instanceof UiProcessingItem) { ((UiProcessingItem) item).updateAction(); } } } public void backPressed() { if (!MainActivity.backDisabledWhenConnected || MainActivity.con == null) { VBWin.mainActivity.finish(); } else { VBWin.mainActivity.makeToast("first disconnect"); } } public static void paintFill(boolean fill) { if (fill) { paint.setStyle(Style.FILL); } else { paint.setStyle(Style.STROKE); } } public boolean onTouchEvent(MotionEvent event) { int pointerCount; float minDist; int i; float dist; int actionMasked = event.getActionMasked(); if (actionMasked == 0) { float x = event.getX() / ((float) w); float y = event.getY() / ((float) h); VBPointer p = new VBPointer(); p.x0 = x; p.x = x; p.y0 = y; p.y = y; this.pointers.add(p); onPointerDown(x, y); } if (actionMasked == 5) { int index = event.getActionIndex(); x = event.getX(index) / ((float) w); y = event.getY(index) / ((float) h); p = new VBPointer(); p.x0 = x; p.x = x; p.y0 = y; p.y = y; this.pointers.add(p); onPointerDown(x, y); } if (actionMasked == 1) { x = event.getX() / ((float) w); y = event.getY() / ((float) h); pointerCount = this.pointers.size(); if (pointerCount != 1) { VBWin.debug("err: ACTION_UP with pointerCount = " + pointerCount); } if (pointerCount > 0) { p = (VBPointer) this.pointers.elementAt(0); p.x = x; p.y = y; onPointerUp(p.x, p.y, p.x0, p.y0); this.pointers.remove(p); } } if (actionMasked == 6) { index = event.getActionIndex(); x = event.getX(index) / ((float) w); y = event.getY(index) / ((float) h); pointerCount = this.pointers.size(); minDist = 1000000.0f; for (i = 0; i < pointerCount; i++) { p = (VBPointer) this.pointers.elementAt(i); dist = ((p.x - x) * (p.x - x)) + ((p.y - y) * (p.y - y)); if (dist < minDist) { minDist = dist; } } for (i = 0; i < pointerCount; i++) { p = (VBPointer) this.pointers.elementAt(i); if (((p.x - x) * (p.x - x)) + ((p.y - y) * (p.y - y)) == minDist) { p.x = x; p.y = y; onPointerUp(p.x, p.y, p.x0, p.y0); this.pointers.remove(p); break; } } } if (actionMasked == 2) { int eventPointerCount = event.getPointerCount(); for (int j = 0; j < eventPointerCount; j++) { x = event.getX(j) / ((float) w); y = event.getY(j) / ((float) h); pointerCount = this.pointers.size(); minDist = 1000000.0f; for (i = 0; i < pointerCount; i++) { p = (VBPointer) this.pointers.elementAt(i); dist = ((p.x - x) * (p.x - x)) + ((p.y - y) * (p.y - y)); if (dist < minDist) { minDist = dist; } } for (i = 0; i < pointerCount; i++) { p = (VBPointer) this.pointers.elementAt(i); if (((p.x - x) * (p.x - x)) + ((p.y - y) * (p.y - y)) == minDist) { p.x = x; p.y = y; onPointerMoved(p.x, p.y, p.x0, p.y0); break; } } } } return true; } public void onPointerDown(float x, float y) { if (this.items != null) { UiItem item = getItem(x, y); if (item != null) { item.onPointerDown(x, y); } repaint(); } } public void onPointerMoved(float x, float y, float x0, float y0) { if (this.items != null) { UiItem item = getItem(x0, y0); if (item != null) { item.onPointerMoved(x, y, x0, y0); } repaint(); } } public void onPointerUp(float x, float y, float x0, float y0) { if (this.items != null) { UiItem item = getItem(x0, y0); if (item != null) { item.onPointerUp(x, y, x0, y0); } repaint(); } } private UiItem getItem(float x, float y) { if (this.items == null) { return null; } int itemCount = this.items.size(); if (itemCount == 0) { return null; } int i; for (i = 0; i < itemCount; i++) { UiItem item = (UiItem) this.items.elementAt(i); if (item.isInteractive && item.containsPoint(x, y)) { return item; } } if (!false) { float minDist = 10000.0f; for (i = 0; i < itemCount; i++) { item = (UiItem) this.items.elementAt(i); if (item.isInteractive) { float dist = item.distTo(x, y); if (dist < minDist) { minDist = dist; } } } for (i = 0; i < itemCount; i++) { item = (UiItem) this.items.elementAt(i); if (item.isInteractive && item.distTo(x, y) == minDist) { return item; } } } return null; } public String toString() { VBDataStore store = new VBDataStore(); int itemCount = this.items.size(); store.putInt("itemCount", itemCount); store.putString("name", this.name); store.putString("commandEnding", this.commandEnding); store.putString("connectAction", this.connectAction); store.putString("charDelay", this.charDelayString); store.putString("bgColor", this.bgColor); store.putString("version", this.version); for (int i = 0; i < itemCount; i++) { store.putUiItem(BuildConfig.VERSION_NAME + i, (UiItem) this.items.elementAt(i)); } return store.toString(); } public static Ui fromString(String st) { Ui ui = new Ui(null); ui.items = new Vector(); VBDataStore store = VBDataStore.fromString(st); int itemCount = store.getInt("itemCount", 0); for (int i = 0; i < itemCount; i++) { UiItem item = store.getUiItem(BuildConfig.VERSION_NAME + i, null); if (item != null) { ui.addItem(item); } else { Log.d("Ui fromString err", "item==null"); } } ui.name = store.getString("name", BuildConfig.VERSION_NAME); ui.commandEnding = store.getString("commandEnding", "\n"); ui.connectAction = store.getString("connectAction", BuildConfig.VERSION_NAME); ui.charDelayString = store.getString("charDelay", ui.charDelayString); ui.bgColor = store.getString("bgColor", ui.bgColor); ui.onBgColorChanged(); ui.version = store.getString("version", BuildConfig.VERSION_NAME); return ui; } public boolean onCharDelayStringChanged() { if (this.charDelayString.length() == 0) { this.charDelay = MainActivity.charDelay; return true; } try { this.charDelay = Integer.parseInt(this.charDelayString); if (this.charDelay >= 0) { return true; } VBWin.mainActivity.showError("charDelay error", "value can not be negative."); return false; } catch (Exception e) { VBWin.mainActivity.showError("charDelay parse error", e.toString()); return false; } } public void addItem(UiItem item) { this.items.add(item); item.ui = this; } public void addItem(int index, UiItem item) { this.items.add(index, item); item.ui = this; } public boolean hasNoItems() { if (this.items == null || this.items.size() == 0) { return true; } return false; } public int getItemCount() { if (this.items == null) { return 0; } return this.items.size(); } public UiItem getItem(int index) { return (UiItem) this.items.elementAt(index); } public void remove(UiItem item) { this.items.remove(item); } public void send(String st) { VBConnection con = MainActivity.con; if (con != null && con.ready) { con.charDelay = this.charDelay; con.send(st + this.commandEnding); } } public void send(String[] st) { VBConnection con = MainActivity.con; if (con != null && con.ready) { String s = BuildConfig.VERSION_NAME; for (int i = 0; i < st.length; i++) { if (st[i].length() > 0) { s = s + st[i] + this.commandEnding; } } con.charDelay = this.charDelay; con.send(s); } } public void sendBytes(byte[] ba, int offset, int len) { VBConnection con = MainActivity.con; if (con != null && con.ready) { con.charDelay = this.charDelay; con.sendBytes(ba, offset, len); } } public void sendWithoutCmdEnding(String st) { VBConnection con = MainActivity.con; if (con != null && con.ready) { con.charDelay = this.charDelay; con.send(st); } } public Ui clone() { try { Class<?> c = getClass(); String st = toString(); return (Ui) c.getDeclaredMethod("fromString", new Class[]{String.class}).invoke(null, new Object[]{st}); } catch (Exception e) { return null; } } public void unlockEditAll() { Iterator i$ = this.items.iterator(); while (i$.hasNext()) { ((UiItem) i$.next()).isEditLocked = false; } } public static void drawHintText(Canvas cnv, String text, int x, int y, int color) { paint.setStyle(Style.STROKE); paint.setTextAlign(Align.CENTER); paint.setStrokeWidth(0.0f); paint.setColor(color); setTextSize(22.0f); String[] textRows = text.split("\n"); int n = textRows.length; int x0 = w / 2; int y0 = (int) (((float) (h / 2)) - ((((float) (fontH * n)) + 0.5f) / 2.0f)); for (int i = 0; i < n; i++) { cnv.drawText(textRows[i], (float) x0, (float) ((fontH * i) + y0), paint); } setDefaultTextSize(); } } } <file_sep>using System; using System.Text; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Collections.Generic; using System.Windows.Forms; using Microsan; using System.ComponentModel.Design; using System.ComponentModel; namespace RoboRemoPC { public class UiItem { public string Type = ""; public VBDataStore vbds; public static Bitmap Img_UiTouchStopper_Vertical; public static Bitmap Img_UiTouchStopper_Horizontal; public Control control = null; public UiItem(TypeValuePair tvp) { Type = tvp.Type; vbds = new VBDataStore(tvp.Value); } public UiItem(string type, string str) { Type = type; vbds = new VBDataStore(str); } public Control CreateNewUiControl(IDesignerHost idh)//, Control container) { if (Type == "UiButton") control = (Button)idh.CreateComponent(typeof(Button));// new Button(); else if (Type == "UiSlider" || Type == "UiIndicator") { control = (CustomSlider2)idh.CreateComponent(typeof(CustomSlider2));//new CustomSlider(); string ori = vbds.getString("ori", "v"); if (ori == "h") ((CustomSlider2)control).Orientation = Orientation.Horizontal; else ((CustomSlider2)control).Orientation = Orientation.Vertical; ((CustomSlider2)control).isHandleVisible = (Type == "UiSlider"); } else if (Type == "UiTextField") { control = (TransparentLabel)idh.CreateComponent(typeof(TransparentLabel));//new TextBox(); ((TransparentLabel)control).TextPosition = new Point(6, 3); } else if (Type == "UiTextLog") { control = (TextBox)idh.CreateComponent(typeof(TextBox));//new TextBox(); ((TextBox)control).Multiline = true; ((TextBox)control).ReadOnly = true; ((TextBox)control).BackColor = System.Drawing.Color.FromName("LightSkyBlue"); } else if (Type == "UiTouchStopper") { control = (Panel)idh.CreateComponent(typeof(Panel));//new Panel(); ((Panel)control).BackgroundImageLayout = ImageLayout.Tile; ((Panel)control).BorderStyle = BorderStyle.None; ((Panel)control).Paint += touchStopper_Paint; } else { control = (Button)idh.CreateComponent(typeof(Button));//new Button(); ((Button)control).FlatStyle = FlatStyle.Flat; } control.Margin = new Padding(0); UserControl uc = (UserControl)idh.RootComponent; UpdateUiControl(uc); uc.Controls.Add(control); control.Tag = this; return control; } //TODO: seperate UpdateOrGetNew_Control into two functions //GetNew and Update /// <summary> /// /// </summary> /// <param name="container">the container of the ui item</param> public void UpdateUiControl(Control container) { if (control != null) { control.Left = (int)(vbds.getFloat("x", 0.0f) * ((float)container.Width)); control.Top = (int)(vbds.getFloat("y", 0.0f) * ((float)container.Height)); control.Width = (int)(vbds.getFloat("w", 0.0f) * ((float)container.Width)); control.Height = (int)(vbds.getFloat("h", 0.0f) * ((float)container.Height)); } if (Type == "UiButton") { Button btn = (Button)control; btn.BackColor = System.Drawing.Color.LightGray; btn.Text = vbds.getString("text", "button"); } else if (Type == "UiSlider" || Type == "UiIndicator") { CustomSlider2 slider = (CustomSlider2)control; if (Type == "UiSlider") { slider.ValueMin = vbds.getInt("minVal", 0); slider.ValueMax = vbds.getInt("maxVal", 0); slider.Value = vbds.getInt("val", 0); slider.Text = vbds.getString("label", ""); } else if (Type == "UiIndicator") { slider.ValueMin = Convert.ToInt32(vbds.getFloat("minVal", 0.0f)); slider.ValueMax = Convert.ToInt32(vbds.getFloat("maxVal", 0.0f)); slider.Value = Convert.ToInt32(vbds.getFloat("val", 0.0f)); } /* */ if (slider.Height > slider.Width) { slider.Orientation = Orientation.Vertical; vbds.putString("ori", "v"); } else { slider.Orientation = Orientation.Horizontal; vbds.putString("ori", "h"); } slider.BackColor = System.Drawing.Color.Gray; string color = vbds.getString("color", "y"); if (color == "r") slider.SliderBarColor = System.Drawing.Color.Red; else if (color == "g") slider.SliderBarColor = System.Drawing.Color.Green; else if (color == "b") slider.SliderBarColor = System.Drawing.Color.Blue; else if (color == "y") slider.SliderBarColor = System.Drawing.Color.FromName("Gold"); } else if (Type == "UiTextField") { TransparentLabel txt = (TransparentLabel)control; txt.TransparentText = vbds.getString("text", "TextField"); int bgColor = int.Parse(vbds.getString("bgColor", "FFFFFFFF"), System.Globalization.NumberStyles.HexNumber); txt.BackColor = System.Drawing.Color.FromArgb(bgColor); int textColor = int.Parse(vbds.getString("textColor", "FF000000"), System.Globalization.NumberStyles.HexNumber); txt.ForeColor = System.Drawing.Color.FromArgb(textColor); } else if (Type == "UiTextLog") { ((TextBox)control).Text = vbds.getString("text", "TextLog"); } else if (Type == "UiTouchStopper") { if (control.Height > control.Width) control.BackgroundImage = Img_UiTouchStopper_Vertical; else control.BackgroundImage = Img_UiTouchStopper_Horizontal; } else { Button btn = (Button)control; if (Type == "UiLed") { string color = vbds.getString("color", "y"); bool onState = vbds.getBoolean("on", false); if (color == "r") { if (onState) btn.BackColor = System.Drawing.Color.FromArgb(255, 89, 89); else btn.BackColor = System.Drawing.Color.FromArgb(106, 0, 0); } else if (color == "g") { if (onState) btn.BackColor = System.Drawing.Color.FromArgb(18, 255, 18); else btn.BackColor = System.Drawing.Color.FromArgb(0, 105, 0); } else if (color == "b") { if (onState) btn.BackColor = System.Drawing.Color.FromArgb(89, 89, 255); else btn.BackColor = System.Drawing.Color.FromArgb(0, 0, 106); } else if (color == "y") { if (onState) btn.BackColor = System.Drawing.Color.FromArgb(255, 252, 19); else btn.BackColor = System.Drawing.Color.FromArgb(106, 105, 0); } } else btn.BackColor = System.Drawing.Color.LightGray; btn.Text = vbds.getString("text", Type); } } void touchStopper_Paint(object s, PaintEventArgs e) { CustomDraw.DrawRectangle(e.Graphics, ((Panel)s).ClientRectangle, 2.0f, Color.Red, DashStyle.Solid); /*Panel panel = (Panel)s; Rectangle rect = panel.ClientRectangle; //rect.Inflate(-1, -1); Pen pen = new Pen(Color.Red, 2); pen.DashStyle = DashStyle.Dot; pen.Alignment = PenAlignment.Inset; //<-- this e.Graphics.DrawRectangle(pen, rect);*/ } public void setX(float val) { vbds.putFloat("x", snapToGrid(val, 0.02f)); } public void setY(float val) { vbds.putFloat("y", snapToGrid(val, 0.02f)); } public void setW(float val) { val = snapToGrid(val, 0.01f); if (val == 0.0f) val = 0.01f; vbds.putFloat("w", val); } public void setH(float val) { val = snapToGrid(val, 0.02f); if (val == 0.0f) val = 0.02f; vbds.putFloat("h", val); } private float snapToGrid(float val, float gridSize) { float result; if (val > 0.0f) { result = ((float)((int)(((double)(val / gridSize)) + 0.5d))) * gridSize; } else { result = ((float)((int)(((double)(val / gridSize)) - 0.5d))) * gridSize; } result *= 1.0E7f; if (val > 0.0f) { result = (float)((int)(((double)result) + 0.5d)); } else { result = (float)((int)(((double)result) - 0.5d)); } return result / 1.0E7f; } } } <file_sep>/* * Created by SharpDevelop. * User: Microsan84 * Date: 2017-05-06 * Time: 13:21 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Text; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Collections.Generic; using System.Windows.Forms; using Microsan; namespace RoboRemoPC { public class TypeValuePair { public string Type; public string Value; public TypeValuePair(string type, string value) { Type = type; Value = value; } } /// <summary> /// Description of VBDataStore. /// </summary> public class VBDataStore { public List<string> keys; public List<string> types; public List<string> values; public DataTable dt; public VBDataStore() { keys = new List<string>(); types = new List<string>(); values = new List<string>(); } public VBDataStore(string fromString) { keys = new List<string>(); types = new List<string>(); values = new List<string>(); FromString(fromString); } public void FromString(string st) { keys.Clear(); types.Clear(); values.Clear(); while (true) { string[] q = splitEntry(st); if (q == null) { GenerateDataTable(); return; } keys.Add(q[0]); q = splitEntry(q[1]); types.Add(q[0]); q = splitEntry(q[1]); values.Add(q[0]); st = q[1]; } } public void RemoveItems(int startIndex, int count) { keys.RemoveRange(startIndex, count); types.RemoveRange(startIndex, count); values.RemoveRange(startIndex, count); } public void UpdateValueFromDataTableToStore(int itemIndex) { object value = dt.Rows[itemIndex][2]; if (value.GetType() == typeof(DBNull)) value = ""; values[itemIndex] = (string)value; } public void GenerateDataTable() { string dtName = this.GetHashCode().ToString("X4"); dt = new DataTable(dtName); dt.Columns.Add("key", typeof(string)); dt.Columns.Add("type", typeof(string)); dt.Columns.Add("value", typeof(string)); for (int i = 0; i < keys.Count; i++) { if (types[i].StartsWith("Ui")) dt.Rows.Add(keys[i], types[i], "(click to show)"); // don't show value of Ui Items here else dt.Rows.Add(keys[i], types[i], values[i]); } } public override string ToString() { StringBuilder sb = new StringBuilder(); int size = keys.Count; for (int i = 0; i < size; i++) { sb.Append(keys[i].Length + " "); sb.Append(keys[i] + " "); sb.Append(types[i].Length + " "); sb.Append(types[i] + " "); sb.Append(values[i].Length + " "); sb.Append(values[i] + " "); } return sb.ToString(); } public static string[] splitEntry(string st) { int a, len; if (st.NullOrEmpty()) return null; if (!st.TryGetIndexOf(' ', out a)) return null; if (!int.TryParse(st.Substring(0, a), out len)) return null; String[] res = new String[2]; res[0] = st.Substring(a + 1, len); res[1] = st.Substring(((a + 1) + len) + 1); return res; } public void putBoolean(string key, bool value) { int ii = keys.IndexOf(key); if (ii == -1) { keys.Add(key); types.Add("boolean"); values.Add(/*BuildConfig.VERSION_NAME+*/ value.ToString()); } else { types[ii] = "boolean"; values[ii] = /*BuildConfig.VERSION_NAME+*/ value.ToString(); dt.Rows[ii][1] = types[ii]; dt.Rows[ii][2] = values[ii]; } } public bool getBoolean(string key, bool defValue) { int ii = keys.IndexOf(key); if (ii == -1) return defValue; else return bool.Parse(values[ii]); } public void putFloat(string key, float value) { int ii = keys.IndexOf(key); if (ii == -1) { keys.Add(key); types.Add("float"); values.Add(value.ToString(System.Globalization.CultureInfo.InvariantCulture)); } else { types[ii] = "float"; values[ii] = value.ToString(System.Globalization.CultureInfo.InvariantCulture); dt.Rows[ii][1] = types[ii]; dt.Rows[ii][2] = values[ii]; } } public float getFloat(string key, float defValue) { int ii = keys.IndexOf(key); if (ii == -1) return defValue; else return float.Parse(values[ii], System.Globalization.CultureInfo.InvariantCulture); } public void putInt(string key, int value) { int ii = keys.IndexOf(key); if (ii == -1) { keys.Add(key); types.Add("int"); values.Add(value.ToString()); } else { types[ii] = "int"; values[ii] = value.ToString(); dt.Rows[ii][1] = types[ii]; dt.Rows[ii][2] = values[ii]; } } public int getInt(String key, int defValue) { int ii = keys.IndexOf(key); if (ii == -1) return defValue; else return int.Parse(values[ii]); } public void putLong(string key, long value) { int ii = keys.IndexOf(key); if (ii == -1) { keys.Add(key); types.Add("long"); values.Add(value.ToString()); } else { types[ii] = "long"; values[ii] = value.ToString(); dt.Rows[ii][1] = types[ii]; dt.Rows[ii][2] = values[ii]; } } public long getLong(String key, long defValue) { int ii = keys.IndexOf(key); if (ii == -1) return defValue; else return long.Parse(values[ii]); } public void putString(string key, string value) { int ii = keys.IndexOf(key); if (ii == -1) { keys.Add(key); types.Add("String"); values.Add(value); } else { types[ii] = "String"; values[ii] = value; dt.Rows[ii][1] = types[ii]; dt.Rows[ii][2] = values[ii]; } } public void putUIitem(string key,string type, string value) { int ii = keys.IndexOf(key); if (ii == -1) { keys.Add(key); types.Add(type); values.Add(value); dt.Rows.Add(key, type, "(click to show)"); } else { types[ii] = type; values[ii] = value; dt.Rows[ii][1] = types[ii]; dt.Rows[ii][2] = "(click to show)"; } } public String getString(string key, string defValue) { int ii = keys.IndexOf(key); if (ii == -1) return defValue; else return values[ii]; } public TypeValuePair getUiItem(string key) { int ii = keys.IndexOf(key); if (ii == -1) return new TypeValuePair("", ""); else return new TypeValuePair(types[ii], values[ii]); } public string getType(string key) { int ii = keys.IndexOf(key); if (ii == -1) return ""; else return types[ii]; } public void RemoveUiItem(string key) { int ii = keys.IndexOf(key); keys.RemoveAt(ii); types.RemoveAt(ii); values.RemoveAt(ii); int startIndex = int.Parse(key); for (int i = ii; i < keys.Count; i++) { keys[i] = startIndex.ToString(); startIndex++; } } } } <file_sep># RoboRemoPCeditor Editor for RoboRemo for Android ![Main](/Main.png)<file_sep>/* * Created by SharpDevelop. * User: Microsan84 * Date: 2017-05-08 * Time: 18:05 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; namespace RoboRemoPC { /// <summary> /// Description of Test_Button_Region. /// </summary> public class Test_Button_Region { public Test_Button_Region() { } private bool Button1_MouseDown = false; void button1_Paint(object sender, PaintEventArgs e) { GraphicsPath myGraphicsPath = new GraphicsPath(); Point[] myPointArray = { new Point(5, 30), new Point(20, 40), new Point(50, 30)}; FontFamily myFontFamily = new FontFamily("Courier New"); PointF myPointF = new PointF(20, 20); StringFormat myStringFormat = new StringFormat(); myGraphicsPath.AddArc(0, 0, 30, 20, -90, 180); myGraphicsPath.StartFigure(); myGraphicsPath.AddCurve(myPointArray); myGraphicsPath.AddString("button", myFontFamily, (int)FontStyle.Bold, 32, myPointF, myStringFormat); myGraphicsPath.AddPie(button1.Width - 40, 10, 40, 40, 40, 110); Region newRegion = new System.Drawing.Region(myGraphicsPath); if (Button1_MouseDown) newRegion.Translate(2.0f, 2.0f); button1.Region = newRegion; } void button1_MouseDown(object sender, MouseEventArgs e) { Button1_MouseDown = true; } void button1_MouseUp(object sender, MouseEventArgs e) { Button1_MouseDown = false; } } } <file_sep>using System; using System.Drawing; using System.Windows.Forms; using System.Drawing.Drawing2D; using System.ComponentModel; /// <summary> /// Use this for drawing custom graphics and text with transparency. /// Inherit from DrawingArea and override the OnDraw method. /// </summary> public class CustomSlider2 : Control { private string _label = "Label"; private Point _textPosition = new Point(0, 0); private System.Drawing.Text.TextRenderingHint _TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; private Rectangle bar; public bool setLabelToCurrentValue = true; public bool isHandleVisible = true; public int handleSize = 30; private Rectangle drawArea = Rectangle.Empty; [Description("Text to show"), Category("Data")] public override string Text { get { return _label; } set { _label = value; Refresh(); } } public System.Drawing.Text.TextRenderingHint TextRenderingHint { get { return _TextRenderingHint; } set { _TextRenderingHint = value; Refresh(); } } public System.Drawing.Drawing2D.InterpolationMode GraphicsInterpolationMode { get; set; } = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear; public System.Drawing.Drawing2D.PixelOffsetMode GraphicsPixelOffsetMode { get; set; } = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; public System.Drawing.Drawing2D.SmoothingMode GraphicsSmoothingMode { get; set; } = System.Drawing.Drawing2D.SmoothingMode.HighQuality; protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ExStyle |= 0x00000020; //WS_EX_TRANSPARENT return cp; } } public CustomSlider2() { Init(); RoboRemoPC.Debug.AddLine(this.GetHashCode() + ":" +Environment.StackTrace + "\n"); } public void Init() { base.SetStyle(ControlStyles.SupportsTransparentBackColor, true); this.KeyUp += this_KeyUp; this.Resize += this_Resize; this.MouseEnter += this_MouseEnter; this.MouseMove += this_MouseMove; this.MouseWheel += this_MouseWheel; this.MouseDown += this_MouseDown; bar = new Rectangle(0, 0, this.Width, this.Height); //ValueSteps = this.Height; } GraphicsPath GrPath { get { int amount = 2; GraphicsPath grPath = new GraphicsPath(); grPath.AddArc(0, 0, amount, amount, 180, 90); grPath.AddArc(this.Width - amount, 0, amount, amount, 270, 90); grPath.AddArc(this.Width - amount, this.Height - amount, amount, amount, 0, 90); grPath.AddArc(0, this.Height - amount, amount, amount, 90, 90); //grPath.AddEllipse(this.ClientRectangle); return grPath; } } protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); drawArea = new Rectangle(new Point(0,0), this.Size); // this be used to define how and where draw this controls // contents // so that the handle can be drawn outside of the slider bar } protected override void OnPaintBackground(PaintEventArgs pea) { if (Orientation == Orientation.Vertical) pea.Graphics.FillRectangle(new SolidBrush(this.BackColor), 0, 0, this.Width, this.Height); else pea.Graphics.FillRectangle(new SolidBrush(this.BackColor), 0, 0, this.Width, this.Height); } protected override void OnPaint(PaintEventArgs e) { Graphics graphics = e.Graphics; graphics.FillRectangle(new SolidBrush(_sliderBarColor), bar);//, 0, 0, this.Width, this.Height); if (isHandleVisible) DrawHandle(graphics); DrawLabel(); } private void DrawHandle(Graphics graphics) { Image thumbImg; Rectangle imgRect; if (Orientation == Orientation.Horizontal) { thumbImg = RoboRemoPC.Resources.slider_thumb_h; imgRect = new Rectangle(bar.Right - handleSize/2, bar.Top, handleSize, this.Height); } else { thumbImg = RoboRemoPC.Resources.slider_thumb_v; imgRect = new Rectangle(bar.Left, bar.Top - handleSize/2, this.Width, handleSize); } graphics.DrawImage(thumbImg, imgRect); } Rectangle lastLabelRectangle = Rectangle.Empty; private void DrawLabel() { if (this.Parent == null) return; // wait for init if (lastLabelRectangle != Rectangle.Empty) { this.Parent.Invalidate(lastLabelRectangle); this.Parent.Update(); } Graphics graphics = this.Parent.CreateGraphics(); // Set the best settings possible (quality-wise) graphics.TextRenderingHint = _TextRenderingHint; // System.Drawing.Text.TextRenderingHint.ClearTypeGridFit graphics.InterpolationMode = GraphicsInterpolationMode; // System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear; graphics.PixelOffsetMode = GraphicsPixelOffsetMode; // System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; graphics.SmoothingMode = GraphicsSmoothingMode; // System.Drawing.Drawing2D.SmoothingMode.HighQuality; SizeF textSizeF = graphics.MeasureString(_label, this.Font); int width = (int)Math.Ceiling(textSizeF.Width); int height = (int)Math.Ceiling(textSizeF.Height); Size textSize = new Size(width, height); Point position = new Point(this.Left - (textSize.Width - this.Width)/2, this.Bottom); Rectangle rectangle = new Rectangle(position, textSize); lastLabelRectangle = rectangle; graphics.DrawString(_label, this.Font, new SolidBrush(this.ForeColor), rectangle); } public delegate void SliderMovedEventHandler(object tag, int value); public event SliderMovedEventHandler SliderMoved = null; public delegate void ValueChangedEventHandler(object tag, int value); public event ValueChangedEventHandler ValueChanged = null; public Action<string> DebugMessageDelegate; private void DebugMessage(string message) { if (DebugMessageDelegate != null) DebugMessageDelegate(message); } private Orientation _orientation; private int _valueMax = 100; private int _valueMin = 0; private int _value; private int _valueSteps = 1; public int ValueSteps { get { return _valueSteps; } set { _valueSteps = value; } } public int ValueStepSize { get { if (Orientation == Orientation.Horizontal) { if (this.Width > ValueRange) return this.Width / ValueRange; else return ValueRange / this.Width; } else { if (this.Height > ValueRange) return this.Height/ ValueRange; else return ValueRange / this.Height; } } } public int ValueRange { get { return (_valueMax - _valueMin); } } [Description("The max value"), Category("Data")] public int ValueMax { get { return _valueMax; } set { _valueMax = value; Value = _value; } } [Description("the min value"), Category("Data")] public int ValueMin { get { return _valueMin; } set { _valueMin = value; Value = _value; } } [Description("Current value"), Category("Data")] public int Value { get { return _value; } set { _value = value; if (_value < _valueMin) _value = _valueMin; else if (_value > _valueMax) _value = _valueMax; SetBarFromValue(); if (ValueChanged != null) ValueChanged(this.Tag, _value); } } private Color _sliderBarColor; [Description("color of slider"), Category("Data")] public Color SliderBarColor { get { return _sliderBarColor; } set { _sliderBarColor = value; } } public Orientation Orientation { get { return _orientation; } set { _orientation = value; SetBarFromValue(); } } private void SetBarFromValue() { if (_orientation == Orientation.Vertical) SetBarByPosition(this.Size.Height - ((_value - _valueMin) * this.Size.Height) / ValueRange); else if (_orientation == Orientation.Horizontal) SetBarByPosition(this.Size.Width - ((_value - _valueMin) * this.Size.Width) / ValueRange); } private void SetBarByPosition(int rootPos) { if (_orientation == Orientation.Vertical) { bar.X = 0; if (rootPos < 0) rootPos = 0; else if (rootPos >= this.Height) rootPos = this.Height; bar.Height = this.Height - rootPos; bar.Y = rootPos; bar.Width = this.Width; } else if (_orientation == Orientation.Horizontal) { bar.X = 0; if (rootPos < 0) rootPos = 0; else if (rootPos >= this.Width) rootPos = this.Width; bar.Width = this.Width - rootPos; bar.Y = 0; bar.Height = this.Height; } Refresh(); } private void SliderUserMove(int rootPos) { SetBarByPosition(rootPos); // calculate value from slider GUI position if (Orientation == Orientation.Vertical) _value = _valueMin + (ValueRange * (this.Height - bar.Y)) / this.Height; else _value = _valueMin + (ValueRange * (this.Width - bar.X)) / this.Width; if (setLabelToCurrentValue) this.Text = _value.ToString(); if (ValueChanged != null) ValueChanged(this.Tag, _value); RoboRemoPC.Debug.AddLine(this.GetHashCode() + this.Parent.Name + "\n"); SliderMoved(this.Tag, _value); } private void this_MouseDown(object sender, MouseEventArgs e) { if (SliderMoved == null) return; // if the event is not set then this slider is output only if (e.Button != MouseButtons.Left) return; if (Orientation == Orientation.Vertical) SliderUserMove(e.Y); else SliderUserMove(e.X); } private void this_MouseMove(object sender, MouseEventArgs e) { if (SliderMoved == null) return; // if the event is not set then this slider is output only if (e.Button != MouseButtons.Left) return; if (Orientation == Orientation.Vertical) SliderUserMove(e.Y); else SliderUserMove(e.X); } private void this_MouseWheel(object sender, MouseEventArgs e) { if (SliderMoved == null) return; // if the event is not set then this slider is output only if (e.Delta == 0) return; MouseScroll_ChangeValue(e.Delta); SliderMoved(this.Tag, Value); } private void this_Resize(object sender, EventArgs e) { SetBarFromValue(); } private void MouseScroll_ChangeValue(int delta) { if (delta < 0) delta = -1; else delta = 1; Value = _value + delta * ValueStepSize; } private void this_KeyUp(object sender, KeyEventArgs e) { if (SliderMoved == null) return; // if the event is not set then this slider is output only if (e.KeyCode == Keys.Up) Value = _value + ValueStepSize; else if (e.KeyCode == Keys.Down) Value = _value - ValueStepSize; } private void this_MouseEnter(object sender, EventArgs e) { this.Focus(); } }<file_sep>/* * Created by SharpDevelop. * User: Microsan84 * Date: 2017-05-08 * Time: 00:43 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Drawing; using System.Drawing.Drawing2D; namespace RoboRemoPC { /// <summary> /// Description of CustomDraw. /// </summary> public class CustomDraw { public CustomDraw() { } public static void DrawRectangle(Graphics g, Rectangle rect, float penWidth, Color penColor, DashStyle penDashStyle) { using (Pen pen = new Pen(penColor, penWidth)) { pen.DashStyle = penDashStyle; float shrinkAmount = pen.Width / 2; g.DrawRectangle( pen, rect.X + shrinkAmount, // move half a pen-width to the right rect.Y + shrinkAmount, // move half a pen-width to the down rect.Width - penWidth, // shrink width with one pen-width rect.Height - penWidth); // shrink height with one pen-width } } public static Bitmap GetRoundedCornerRectangleGradianted(Color start, Color middle, Color end) { GraphicsPath gp = new GraphicsPath(); // gp.AddArc(0,0, 20, 20, 180, 90); //gp.AddLine(10, 0, 90, 0); gp.AddArc(89, 0, 20, 20, 270, 90); //gp.AddLine(109, 10, 109, 90); gp.AddArc(89, 89, 20, 20, 0, 90); gp.AddArc(0, 89, 20, 20, 90, 90); //gp.AddLine(90, 110, 10, 110); //gp.AddLine(10, 110, 10, 10); Bitmap bm = new Bitmap(110, 110); LinearGradientBrush brush = new LinearGradientBrush(new Point(0, 0), new Point(100, 0), start, middle); using (Graphics g = Graphics.FromImage(bm)) { g.FillPath(brush, gp); g.DrawPath(new Pen(Color.Black, 1), gp); g.Save(); } /* brush = new LinearGradientBrush(new Point(91, 0), new Point(100, 0), middle, end); using (Graphics g = Graphics.FromImage(bm)) { g.FillPath(brush, gp); //g.DrawPath(new Pen(Color.Black, 1), gp); g.Save(); }*/ bm.MakeTransparent(bm.GetPixel(0,0)); return bm; //bm.Save(@"c:\bitmap.bmp"); } } } <file_sep>/* * Created by SharpDevelop. * User: Microsan84 * Date: 2017-05-06 * Time: 13:11 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Data; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.IO; using System.Reflection; using System.Resources; using System.ComponentModel.Design; using System.ComponentModel; using System.Collections; namespace RoboRemoPC { /// <summary> /// Description of MainForm. /// </summary> public partial class MainForm : Form { private VBDataStore vbdsUi; private VBDataStore vbdsUiItemsRef; public List<UiItem> uiItems; private OpenFileDialog ofd; private SaveFileDialog sfd; private string currentFilePath = ""; //private int selectedUiItemIndex = 0; private UiItem currentSelectedUiItem; private Control[] currentSelection = new Control[0]; private Control[] currentSelectionCopyRef = new Control[0]; //private Bitmap bm; public UiItem uiItemCopyRef = null; public UiItem[] uiItemsCopyRef = new UiItem[0]; //private Point panelMousePoint; private DesignSurface ds; private IDesignerHost idh; private ISelectionService selectionService; private UserControl designRoot; private Point lastCmsLocation; public MainForm() { InitializeComponent(); ofd = new OpenFileDialog(); ofd.InitialDirectory = Application.StartupPath + "\\gui_files"; ofd.Filter = "All files|*.*"; sfd = new SaveFileDialog(); sfd.InitialDirectory = Application.StartupPath + "\\gui_files"; sfd.Filter = "All files|*.*"; ResourceManager resources = new ResourceManager("RoboRemoPC.Resources", Assembly.GetExecutingAssembly()); UiItem.Img_UiTouchStopper_Horizontal = (Bitmap) resources.GetObject("stoptape"); //image without extension UiItem.Img_UiTouchStopper_Vertical = (Bitmap) resources.GetObject("stoptape"); //image without extension UiItem.Img_UiTouchStopper_Vertical.RotateFlip(RotateFlipType.Rotate90FlipNone); uiItems = new List<UiItem>(); Init_DesignSurface(); //customSlider22.Init(); customSlider22.SliderMoved += CustomSlider22_SliderMoved; customSlider22.ValueChanged += CustomSlider22_ValueChanged; } private void CustomSlider22_ValueChanged(object tag, int value) { //Debug.AddLine("CustomSlider_ValueChanged: " + value); } private void CustomSlider22_SliderMoved(object tag, int value) { //Debug.AddLine("CustomSlider_SliderMoved: " + value); } /* TODO: fix keyboard commands private void PanelUiView_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if (e.Control && e.KeyCode == Keys.V) PasteUiItem(); else if (e.KeyCode == Keys.Delete) RemoveCurrentUiItem(); }*/ private void Show_DesignSurface_ContextMenu(int xPos, int yPos) { lastCmsLocation = designRoot.PointToClient(new Point(xPos, yPos)); cmsEditor.Show(designRoot, lastCmsLocation); } private void Init_DesignSurface() { panelUiView.Controls.Clear(); // clear development items ServiceContainer serviceContainer = new ServiceContainer(); serviceContainer.AddService(typeof(IMenuCommandService), new MenuService(ds, Show_DesignSurface_ContextMenu)); ds = new DesignSurface(serviceContainer); ds.BeginLoad(typeof(UserControl)); // Get the View of the DesignSurface, host it in a form, and show it Control c = ds.View as Control; c.Parent = panelUiView; c.Dock = DockStyle.Fill; idh = (IDesignerHost)ds.GetService(typeof(IDesignerHost)); selectionService = (ISelectionService)ds.GetService(typeof(ISelectionService)); if (selectionService != null) { // Add an event handler for the SelectionChanging // and SelectionChanged events. //selectionService.SelectionChanging += new EventHandler(OnSelectionChanging); selectionService.SelectionChanged += new EventHandler(OnSelectionChanged); } designRoot = (UserControl)idh.RootComponent; designRoot.SizeChanged += designRoot_SizeChanged; designRoot.Height = panelUiView.Height - 32; designRoot.Width = panelUiView.Width - 32; // Use ComponentChangeService to announce changing of the // Form's Controls collection */ IComponentChangeService icc = (IComponentChangeService)idh.GetService(typeof(IComponentChangeService)); icc.OnComponentChanging(idh.RootComponent, TypeDescriptor.GetProperties(idh.RootComponent)["Controls"]); } private void DeselectAllRows(DataGridView dgv) { for (int i = 0; i < dgv.RowCount; i++) dgv.Rows[i].Cells[0].Selected = false; } private void OnSelectionChanged(object sender, EventArgs args) { currentSelection = new Control[((ICollection)selectionService.GetSelectedComponents()).Count]; ((ICollection)selectionService.GetSelectedComponents()).CopyTo(currentSelection, 0); DeselectAllRows(dgv); if (currentSelection.Length == 1) { Control ctrl = currentSelection[0]; if (ctrl.GetType() == typeof(UserControl)) { dgvUiItem.DataSource = null; return; } //Debug.AddLine(DateTime.Now.ToLongTimeString() + " OnSelectionChanged type:"+ctrl.GetType()); currentSelectedUiItem = (UiItem)ctrl.Tag; dgvUiItem.DataSource = currentSelectedUiItem.vbds.dt; int uiItemIndex = uiItems.IndexOf(currentSelectedUiItem); int ownerIndex = vbdsUi.keys.IndexOf(uiItemIndex.ToString()); dgv.Rows[ownerIndex].Cells[0].Selected = true; return; } //Debug.AddLine(DateTime.Now.ToLongTimeString() + " OnSelectionChanged"); dgvUiItem.DataSource = null; for (int i = 0; i < currentSelection.Length; i++) { UiItem uiItem = (UiItem)currentSelection[i].Tag; int uiItemIndex = uiItems.IndexOf(uiItem); int ownerIndex = vbdsUi.keys.IndexOf(uiItemIndex.ToString()); dgv.Rows[ownerIndex].Cells[0].Selected = true; } } private void this_Shown(object sender, EventArgs e) { Init_DesignSurface(); try { OpenUiItemsRefFile(ofd.InitialDirectory + "\\master.txt"); } catch { } CreateNewUi(); Color colorStart = Color.FromArgb(255, 255, 0, 0); Color colorMiddle = Color.FromArgb(255, 255, 64, 64); Color colorEnd = Color.FromArgb(255, 255, 16, 16); } private void tsmiCreateNewUi_Click(object sender, EventArgs e) { CreateNewUi(); } public void CreateNewUi() { uiItems.Clear(); vbdsUi = new VBDataStore(vbdsUiItemsRef.ToString()); int indexOf = vbdsUi.keys.IndexOf("1"); // don't remove item zero because it's menu int count = vbdsUi.keys.Count - indexOf; vbdsUi.RemoveItems(indexOf, count); vbdsUi.putString("itemCount", "1"); vbdsUi.putBoolean("touchProcessingExact", true); vbdsUi.GenerateDataTable(); UiItem newUiItem = new UiItem(vbdsUi.getUiItem("0")); uiItems.Add(newUiItem); newUiItem.vbds.putString("text", "menu"); designRoot.Controls.Clear(); AddNewUiItemToPanel(newUiItem); int bgColor = int.Parse(vbdsUi.getString("bgColor", "FFFFFFFF"), System.Globalization.NumberStyles.HexNumber); designRoot.BackColor = Color.FromArgb(bgColor); dgv.DataSource = vbdsUi.dt; } private void tsmiFileOpen_Click(object sender, EventArgs e) { if (ofd.ShowDialog() == DialogResult.Cancel) return; OpenAndShow(ofd.FileName); currentFilePath = ofd.FileName; tsmiSaveFile.Enabled = true; } private void tsmiFileSaveAs_Click(object sender, EventArgs e) { if (sfd.ShowDialog() == DialogResult.Cancel) return; currentFilePath = sfd.FileName; SaveCurrentFile(); tsmiSaveFile.Enabled = true; } private void tsmiSaveFile_Click(object sender, EventArgs e) { SaveCurrentFile(); } private void SaveCurrentFile() { vbdsUi.putInt("itemCount", uiItems.Count); for (int i = 0; i < uiItems.Count; i++) { vbdsUi.putUIitem(i.ToString(), uiItems[i].Type, uiItems[i].vbds.ToString()); } File.WriteAllText(currentFilePath, vbdsUi.ToString()); } private void tsmiRefUiItemsFileOpen_Click(object sender, EventArgs e) { if (ofd.ShowDialog() == DialogResult.Cancel) return; OpenUiItemsRefFile(ofd.FileName); } private void OpenUiItemsRefFile(string filePath) { vbdsUiItemsRef = new VBDataStore(File.ReadAllText(filePath)); int itemCount = vbdsUiItemsRef.getInt("itemCount", 0); if (itemCount == 0) { MessageBox.Show("This Ref. File don't contain any UiItems"); return; } tsmiAdd.DropDownItems.Clear(); for (int i = 1;i < itemCount; i++) { string uiItemType = vbdsUiItemsRef.getType(i.ToString()); if (uiItemType == "") continue; // failsafe ToolStripMenuItem tsmi = new ToolStripMenuItem(uiItemType); tsmi.Click += tsmiAddItem_Click; tsmi.Tag = i.ToString(); tsmiAdd.DropDownItems.Add(tsmi); } } private void PasteUiItem() { /*for (int i = 0; i < uiItemsCopyRef.Length; i++) { AddNewUiItem(uiItemsCopyRef[i].Type, uiItemsCopyRef[i].vbds.ToString(), lastCmsLocation); }*/ if (currentSelectionCopyRef == null) return; if (currentSelectionCopyRef.Length == 0) return; Point refPoint = currentSelectionCopyRef[0].Location; for (int i = 1; i < currentSelectionCopyRef.Length; i++) { if (refPoint.X > currentSelectionCopyRef[i].Location.X || refPoint.Y > currentSelectionCopyRef[i].Location.Y) { refPoint = currentSelectionCopyRef[i].Location; } } for (int i = 0; i < currentSelectionCopyRef.Length; i++) { UiItem uiItem = (UiItem)currentSelectionCopyRef[i].Tag; Point newPoint = new Point((currentSelectionCopyRef[i].Location.X - refPoint.X) + lastCmsLocation.X, (currentSelectionCopyRef[i].Location.Y - refPoint.Y) + lastCmsLocation.Y); AddNewUiItem(uiItem.Type, uiItem.vbds.ToString(), newPoint); } } public void AddNewUiItem(string type, string value, Point location) { UiItem newUiItem = new UiItem(type, value); uiItems.Add(newUiItem); newUiItem.vbds.putString("text", type); vbdsUi.putUIitem((uiItems.Count - 1).ToString(), type, newUiItem.vbds.ToString()); vbdsUi.putInt("itemCount", uiItems.Count); newUiItem.setX((float)location.X / designRoot.Width); newUiItem.setY((float)location.Y / designRoot.Height); if (newUiItem.Type == "UiTextField") { newUiItem.vbds.putString("bgColor", "00FFFFFF"); // transparent background as default newUiItem.vbds.putString("w", "0.22"); newUiItem.vbds.putString("h", "0.04"); } AddNewUiItemToPanel(newUiItem); //TODO: proper select of item //currentSelectedUiItem = newUiItem; } public void AddNewUiItemToPanel(UiItem newUiItem) { Control ctrl = newUiItem.CreateNewUiControl(idh); ctrl.MouseUp += ctrl_MouseUp; ctrl.Click += Ctrl_Click; ctrl.SizeChanged += (sender, e) => UiItem_ControlMovedOrResized(ctrl); ctrl.LocationChanged += (sender, e) => UiItem_ControlMovedOrResized(ctrl); ctrl.BringToFront(); } private void Ctrl_Click(object sender, EventArgs e) { Debug.AddLine("ctrl clkci"); } public void RemoveCurrentSelectedUiItems() { if (currentSelection == null) return; if (currentSelection.Length == 0) return; for (int i = 0; i < currentSelection.Length; i++) { if (currentSelection[i].GetType() == typeof(UserControl)) continue; RemoveUiItem((UiItem)currentSelection[i].Tag); } currentSelection = new Control[0]; } public bool IsMenuButton(UiItem uiItem) { return (uiItem.vbds.getString("pressAction", "") == "menu") || (uiItem.vbds.getString("releaseAction", "") == "menu"); } public void RemoveUiItem(UiItem uiItem) { if (uiItem == null) return; if (uiItem.Type == "UiButton") { if (IsMenuButton(uiItem)) { MessageBox.Show("Can't remove menu button!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } int index = uiItems.IndexOf(uiItem); designRoot.Controls.Remove(uiItem.control); uiItems.RemoveAt(index); vbdsUi.RemoveUiItem(index.ToString()); vbdsUi.putInt("itemCount", uiItems.Count); vbdsUi.GenerateDataTable(); dgv.DataSource = vbdsUi.dt; } private void tsmiAddItem_Click(object sender, EventArgs e) { TypeValuePair tvp = vbdsUiItemsRef.getUiItem((string)((ToolStripMenuItem)sender).Tag); AddNewUiItem(tvp.Type, tvp.Value, lastCmsLocation); } private void OpenAndShow(string filePath) { vbdsUi = new VBDataStore(File.ReadAllText(filePath)); dgv.DataSource = vbdsUi.dt; int itemCount = vbdsUi.getInt("itemCount", 0); if (itemCount == 0) return; uiItems = new List<UiItem>(itemCount); designRoot.Controls.Clear(); tsslblItemCount.Text = itemCount.ToString(); for (int i = 0; i < itemCount; i++) { UiItem newUiItem = new UiItem(vbdsUi.getUiItem(i.ToString())); uiItems.Add(newUiItem); AddNewUiItemToPanel(newUiItem); currentSelectedUiItem = null; } int bgColor = int.Parse(vbdsUi.getString("bgColor", "FFFFFFFF"), System.Globalization.NumberStyles.HexNumber); designRoot.BackColor = Color.FromArgb(bgColor); } private void dgv_CellClick(object sender, DataGridViewCellEventArgs e) { if (((string)vbdsUi.dt.Rows[e.RowIndex][1]).StartsWith("Ui")) { int selectedUiItemIndex = int.Parse((string)vbdsUi.dt.Rows[e.RowIndex][0]); currentSelectedUiItem = uiItems[selectedUiItemIndex]; dgvUiItem.DataSource = currentSelectedUiItem.vbds.dt; } } private void dgv_DataSourceChanged(object sender, EventArgs e) { dgv.Columns[0].SortMode = DataGridViewColumnSortMode.Programmatic; dgv.Columns[1].SortMode = DataGridViewColumnSortMode.Programmatic; dgv.Columns[2].SortMode = DataGridViewColumnSortMode.Programmatic; } private void dgvUiItem_DataSourceChanged(object sender, EventArgs e) { dgvUiItem.Columns[0].SortMode = DataGridViewColumnSortMode.Programmatic; dgvUiItem.Columns[1].SortMode = DataGridViewColumnSortMode.Programmatic; dgvUiItem.Columns[2].SortMode = DataGridViewColumnSortMode.Programmatic; dgvUiItem.Columns[0].ReadOnly = true; dgvUiItem.Columns[1].ReadOnly = true; dgvUiItem.Columns[2].ReadOnly = false; } private void ctrl_MouseUp(object s, MouseEventArgs e) { Debug.AddLine("ctrl mouseup"); Control sender = (Control)s; if (e.Button == MouseButtons.Left) { currentSelectedUiItem = (UiItem)sender.Tag; dgvUiItem.DataSource = currentSelectedUiItem.vbds.dt; int uiItemIndex = uiItems.IndexOf(currentSelectedUiItem); int ownerIndex = vbdsUi.keys.IndexOf(uiItemIndex.ToString()); dgv.Rows[ownerIndex].Cells[0].Selected = true; } else if (e.Button == MouseButtons.Right) { cmsEditor.Show(sender, e.Location); } } private bool UpdatingDesignRoot_Size = false; private void UiItem_ControlMovedOrResized(Control ctrl) { if (UpdatingDesignRoot_Size) return; //Debug.AddLine("UiItem_ControlMovedOrResized"); UiItem uiItem = (UiItem)ctrl.Tag; uiItem.setX( (float)ctrl.Left / (float)designRoot.Width); uiItem.setY( (float)ctrl.Top / (float)designRoot.Height); uiItem.setW( (float)ctrl.Width / (float)designRoot.Width); uiItem.setH( (float)ctrl.Height / (float)designRoot.Height); uiItem.UpdateUiControl(designRoot); } private void designRoot_SizeChanged(object sender, EventArgs e) { UpdatingDesignRoot_Size = true; int itemCount = designRoot.Controls.Count; for (int i= 0; i < itemCount; i++) { Control ctrl = (Control)designRoot.Controls[i]; UiItem uiItem = (UiItem)ctrl.Tag; uiItem.UpdateUiControl(designRoot); } UpdatingDesignRoot_Size = false; } private void dgvUiItem_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) { if (e.ColumnIndex != 2) e.Cancel = true; } private void dgvUiItem_CellValueChanged(object sender, DataGridViewCellEventArgs e) { if (currentSelectedUiItem == null) return; currentSelectedUiItem.vbds.UpdateValueFromDataTableToStore(e.RowIndex); currentSelectedUiItem.UpdateUiControl(designRoot); dgvUiItem.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true; } private void tsmiRemoveUiItems_Click(object sender, EventArgs e) { RemoveCurrentSelectedUiItems(); } private void tsmiCopyUiItem_Click(object sender, EventArgs e) { currentSelectionCopyRef = currentSelection; /*uiItemsCopyRef = new UiItem[currentSelection.Length]; for (int i = 0; i < currentSelection.Length; i++) { uiItemsCopyRef[i] = (UiItem)currentSelection[i].Tag; }*/ //uiItemCopyRef = currentSelectedUiItem; // just store ref to avoid memory usage } private void tsmiPasteUiItem_Click(object sender, EventArgs e) { PasteUiItem(); } private void dgv_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) { if (e.ColumnIndex != 2 || e.RowIndex == 0) e.Cancel = true; string type = (string)dgv.Rows[e.RowIndex].Cells[1].Value; if (type.StartsWith("Ui")) e.Cancel = true; } private void dgv_CellValueChanged(object sender, DataGridViewCellEventArgs e) { vbdsUi.UpdateValueFromDataTableToStore(e.RowIndex); string key = (string)dgv.Rows[e.RowIndex].Cells[0].Value; if (key == "bgColor") { int bgColor = int.Parse(vbdsUi.getString("bgColor", "FFFFFFFF"), System.Globalization.NumberStyles.HexNumber); designRoot.BackColor = Color.FromArgb(bgColor); } } GraphicsPath GrPath { get { GraphicsPath grPath = new GraphicsPath(); grPath.AddArc(0, 0, 40, 40, 180, 90); grPath.AddArc(this.Width - 40, 0, 40, 40, 270, 90); grPath.AddArc(this.Width - 40, this.Height - 40, 40, 40, 0, 90); grPath.AddArc(0, this.Height - 40, 40, 40, 90, 90); //grPath.AddEllipse(this.ClientRectangle); return grPath; } } private void dgvUiItem_CellClick(object sender, DataGridViewCellEventArgs e) { dgvUiItem.BeginEdit(false); } } } <file_sep>/* * Created by SharpDevelop. * User: Microsan84 * Date: 2017-05-06 * Time: 17:10 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; namespace RoboRemoPC { /// <summary> /// Description of UiItem. /// </summary> public abstract class UiItem_JAVAsrc { private float h; protected bool isEditLocked = false; protected bool isInteractive = true; //protected VBWin prevWin; protected Ui ui; private float w; private float x; private float y; public abstract String[] getEditOptions(); public abstract void onEditOptionSelected(String str); public abstract void onPointerDown(float f, float f2); public abstract void onPointerMoved(float f, float f2, float f3, float f4); public abstract void onPointerUp(float f, float f2, float f3, float f4); public abstract void paint(Canvas canvas); public abstract void start(); public abstract void stop(); public void storeParams(VBDataStore store) { store.putFloat("x", getX()); store.putFloat("y", getY()); store.putFloat("w", getW()); store.putFloat("h", getH()); store.putBoolean("isEditLocked", this.isEditLocked); } public void loadParams(VBDataStore store) { setX(store.getFloat("x", 0.0f)); setY(store.getFloat("y", 0.0f)); setW(store.getFloat("w", 0.0f)); setH(store.getFloat("h", 0.0f)); this.isEditLocked = store.getBoolean("isEditLocked", false); } public float getX() { return this.x; } public float getY() { return this.y; } public float getW() { return this.w; } public float getH() { return this.h; } public void setX(float val) { this.x = snapToGrid(val); } public void setY(float val) { this.y = snapToGrid(val); } public void setW(float val) { this.w = snapToGrid(val); } public void setH(float val) { this.h = snapToGrid(val); } private float snapToGrid(float in) { float result; if (in > 0.0f) { result = ((float) ((int) (((double) (in / 0.02f)) + 0.5d))) * 0.02f; } else { result = ((float) ((int) (((double) (in / 0.02f)) - 0.5d))) * 0.02f; } result *= 1.0E7f; if (in > 0.0f) { result = (float) ((int) (((double) result) + 0.5d)); } else { result = (float) ((int) (((double) result) - 0.5d)); } return result / 1.0E7f; } public float distTo(float px, float py) { px -= this.x + (this.w / 2.0f); py -= this.y + (this.h / 2.0f); if ((-this.w) / 2.0f > px || px > this.w / 2.0f || (-this.h) / 2.0f > py || py > this.h / 2.0f) { if ((-this.w) / 2.0f <= px && px <= this.w / 2.0f) { if (py < 0.0f) { return ((-this.h) / 2.0f) - py; } if (py > 0.0f) { return py - (this.h / 2.0f); } } if ((-this.h) / 2.0f <= py && py <= this.h / 2.0f) { if (px < 0.0f) { return ((-this.w) / 2.0f) - px; } if (px > 0.0f) { return px - (this.w / 2.0f); } } return (float) Math.sqrt((double) min(min((((this.w / 2.0f) + px) * ((this.w / 2.0f) + px)) + (((this.h / 2.0f) + py) * ((this.h / 2.0f) + py)), ((px - (this.w / 2.0f)) * (px - (this.w / 2.0f))) + (((this.h / 2.0f) + py) * ((this.h / 2.0f) + py))), min(((px - (this.w / 2.0f)) * (px - (this.w / 2.0f))) + ((py - (this.h / 2.0f)) * (py - (this.h / 2.0f))), (((this.w / 2.0f) + px) * ((this.w / 2.0f) + px)) + ((py - (this.h / 2.0f)) * (py - (this.h / 2.0f)))))); } return -min(min((this.w / 2.0f) - px, px + (this.w / 2.0f)), min((this.h / 2.0f) - py, py + (this.h / 2.0f))); } public bool containsPoint(float x, float y) { if (x >= this.x && y >= this.y && x <= this.x + this.w && y <= this.y + this.h) { return true; } return false; } private float min(float a, float b) { return a < b ? a : b; } public void openEditOptions() { this.prevWin = MainActivity.win; final UiItem item = this; String title = BuildConfig.VERSION_NAME; if (item instanceof UiButton) { title = "button"; } if (item instanceof UiSlider) { title = "slider"; } if (item instanceof UiLed) { title = "led"; } if (item instanceof UiIndicator) { title = "level indicator"; } if (item instanceof UiTextLog) { title = "text log"; } if (item instanceof UiAcc) { title = "accelerometer"; } if (item instanceof UiTextField) { title = "text field"; } if (item instanceof UiPlot) { title = "plot"; } if (item instanceof UiImage) { title = "image"; } if (item instanceof UiTouchPad) { title = "touchpad"; } if (item instanceof UiKbdConnector) { title = "kbd connector"; } if (item instanceof UiHeartbeatSender) { title = "heartbeat sender"; } if (item instanceof UiTouchStopper) { title = "touch stopper"; } if (item instanceof UiVibrator) { title = "vibrator"; } if (item instanceof UiFileReceiver) { title = "file receiver"; } if (item instanceof UiFileSender) { title = "file sender"; } if (item instanceof UiSpeaker) { title = "speaker"; } if (item instanceof UiPrintf) { title = "printf()"; } if (item instanceof UiInputParser) { title = "input parser"; } new VBMenu(title, getItemEditOptions()) { public void onSelect(String st, int i) { if (st.equals("remove")) { UiItem.this.stop(); ((UiEditor) UiItem.this.prevWin).ui.remove(item); UiItem.this.ui.updateProcessingItems(); UiItem.this.prevWin.show(); } else if (st.equals("copy")) { ((UiEditor) UiItem.this.prevWin).itemToCopy = item; UiItem.this.prevWin.show(); } else if (st.equals("lock edit")) { item.isEditLocked = true; UiItem.this.prevWin.show(); } else { UiItem.this.onEditOptionSelected(st); UiItem.this.prevWin.show(); } } }.show(); } public void onChanged() { MainActivity.win.repaint(); } private String[] getItemEditOptions() { int i; String[] st = getEditOptions(); String[] common = new String[]{"copy", "remove", "lock edit"}; String[] res = new String[(common.length + st.length)]; for (i = 0; i < common.length; i++) { res[i] = common[i]; } for (i = common.length; i < res.length; i++) { res[i] = st[i - common.length]; } return res; } public void receiveData(byte[] data, int len, bool moreToCome) { } public UiItem clone() { try { Class<?> c = getClass(); String st = toString(); return (UiItem) c.getDeclaredMethod("fromString", new Class[]{String.class}).invoke(null, new Object[]{st}); } catch (Exception e) { return null; } } public void paintMoveResizeHint(Canvas cnv, int color) { String moveText; String configText; String resizeText; int configX; Ui.paint.setStyle(Style.STROKE); Ui.paint.setStrokeWidth(0.0f); Ui.paint.setColor(color); Ui.setTextSize(20.0f); int x = (int) (getX() * ((float) VBWin.w)); int y = (int) (getY() * ((float) VBWin.h)); int w = (int) (getW() * ((float) VBWin.w)); int h = (int) (getH() * ((float) VBWin.h)); if (x < VBWin.w / 2) { Ui.paint.setTextAlign(Align.LEFT); moveText = "\u2199 Drag to move"; configText = "\u2190 Click to config."; resizeText = "\u2196 Drag to resize"; configX = x + w; } else { Ui.paint.setTextAlign(Align.RIGHT); moveText = "Drag to move \u2198"; configText = "Click to config. \u2192"; resizeText = "Drag to resize \u2197"; configX = x; } cnv.drawText(moveText, (float) x, (float) ((Ui.fontAscent / 2) + y), Ui.paint); cnv.drawText(configText, (float) configX, (float) ((h / 2) + y), Ui.paint); cnv.drawText(resizeText, (float) (x + w), (float) ((y + h) - Ui.fontAscent), Ui.paint); Ui.setDefaultTextSize(); } protected void send(String st) { if (this.ui != null) { this.ui.send(st); } } protected void send(String[] st) { if (this.ui != null) { this.ui.send(st); } } protected void sendWithoutCmdEnding(String st) { if (this.ui != null) { this.ui.sendWithoutCmdEnding(st); } } protected void sendBytes(byte[] ba, int offset, int len) { if (this.ui != null) { this.ui.sendBytes(ba, offset, len); } } protected void updateFromVersion(String oldVersion) { } } }
12b9c5ef47349d7334ed1bf5f75bcea1b41608cb
[ "Markdown", "C#" ]
13
C#
manicken/RoboRemoPCeditor
71147f549c2adf37cf4aa742e3d58368155039ba
8d1fa294fe029a1e92474facb3034b335b0c91e5
refs/heads/main
<file_sep># Criptografía y seguridad en redes: Cifrado simétrico Se utiliza javascript para descifrar un mensaje cifrado con otro lenguaje. El objetivo de este trabajo es verificar la interoperabilidad de distintos lenguajes y de sus librerías criptográficas. Según estadísticas recopiladas por el sitio Stack Overflow, los dos lenguajes que más proyecciones a futuro tienen son Python y Javascript, por lo que para la presente tarea se le solicita utilizar ambos lenguajes. Por el lado del servidor, para la creación de sitios web, se crea un archivo html con Python, el cual contiene: ``` <p>Este sitio contiene un mensaje secreto</p> <div class="algorithm" id="msg_cifrado"></div> ``` donde el contenido de id corresponde a un mensaje cifrado utilizando la librería de Python con el algoritmo de cifrado simetrico BlowFish. Desde el lado del cliente, a través de un plugin para Tampermonkey utilizando Javascript, se descifra el mensaje cifrado previamente, utilizando una configuración previamente acordada (parámetros como llave, semilla, rounds, etc. ) dependiendo los parámetros soportados por el algoritmo y por la implementación del algoritmo. ## Archivos * Archivo Python: Encriptación Blowfish - PCBC y generador HTML. ``` import: Se importan librerías necesarias, entre ellas: Blowfish, base 64, time y os urandom. ciper: Se crea un objeto Cipher con una key. my_str: Texto plano a cifrar. El modo PCBC solo puede cifrar datos que sean (en longitud) múltiplos del tamaño del bloque. Es decir, len(iv)*n donde en este caso, n = 2. my_str_as_bytes: Representación en bytes de texto plano a cifrar. iv: urandom(8) vector inicializador (Random bytes largo 8).Puede ser modificado directamente. data_encrypted: variable que representará el texto cifrado. Cipher.encrypt_pcbc(): Método de la clase Cipher. Inicializamos la función encriptar con los parámetros correspondientes. token_iv: Vector inicializador decodificado desde utf-8 y codificado en base64 para lograr introducirlo en el archivo HTML. token_dataencrypted: Texto encriptado decodificado desde utf-8 y codificado en base64 para lograr introducirlo en el archivo HTML. html_str: String que corresponde al futuro archivo HTML. html: Se reemplaza dentro del html_str el id por la representación en base 64 del vector inicializador. time.sleep(1): Se utilizó para evitar problemas al intentar sobre-escribir. Html1: Se reemplaza dentro del html_str el id por la representación en base 64 del texto encriptado por el algoritmo Blowfish. Html_file: Se crea un archivo con extensión .html con los permisos para escribir en él. Html_file.write(html1): Escribimos en el archivo. ``` <p align="center"> <img src="images/bw_html.png" /> </p> * Archivo JavaScript: Obtener parámetros desde HTML y desencriptar. ``` @match / @require: Apunta a un archivo JavaScript que se carga y ejecuta antes de que el script comience a ejecutarse. (Blowfish , Enc-base64, crypto-js , core-min). var iv: Variable que representa el vector inicializador (b64) obtenido a partir del HTML. console.log(): Mostramos por consola la variable deseada. var bf: Variable que representa el texto encriptado (b64) obtenido a partir del HTML. enc.Base64.parse(): Decodificar cadena desde Base64. ``` <p align="center"> <img src="images/bw_html_js.png" /> </p> ## Blowfish Blowfish es un cifrado de bloque simétrico que se puede utilizar como reemplazo directo de DES o IDEA. Se necesita una clave de longitud variable, desde 32 bits hasta 448 bits (4 a 56 Bytes), lo que la hace ideal tanto para uso doméstico como exportable. Blowfish fue diseñado en 1993 por <NAME> como una alternativa rápida y gratuita a los algoritmos de cifrado existentes. Desde entonces se ha analizado considerablemente y poco a poco está ganando aceptación como un algoritmo de cifrado sólido. Blowfish no está patentado y no tiene licencia, y está disponible gratis para todos los usos. ### Modos de operación de una unidad de cifrado por bloques En este caso, se trabajará con el Modo PCBC (_Propagating cipher-block chaining_). ![alt text](https://www.researchgate.net/profile/Rhouma-Rhouma/publication/215783767/figure/fig3/AS:394138559238147@1470981363207/Propagating-cipher-block-chaining-PCBC-mode-encryption.png) PCBC es usado por Kerberos y Waste. ### IV: Vector de inicialización Un IV es un bloque de bits que es utilizado por varios modos de operación para hacer aleatorio el proceso de encriptación y por lo tanto generar distintos textos cifrados incluso cuando el mismo texto claro es encriptado varias veces, sin la necesidad de regenerar la clave, ya que es un proceso lento. El vector de inicialización tiene requerimientos de seguridad diferentes a los de la clave, por lo que el IV no necesita mantenerse secreto. <file_sep>import blowfish import base64 import time from base64 import b64encode from base64 import b64decode from os import urandom cipher = blowfish.Cipher(b"9kPz9O_H`4nYRx/1") my_str = "holacómoestás?" my_str_as_bytes = str.encode(my_str) #print(type(my_str_as_bytes))# ensure it is byte representation iv = urandom(8) # initialization vector data_encrypted = b"".join(cipher.encrypt_pcbc(my_str_as_bytes, iv)) print(type(iv)) print("dataencrypted (array bytes): ",data_encrypted) token_iv = b64encode(iv).decode('utf-8') token_dataencrypted = b64encode(data_encrypted).decode('utf-8') print("dataencrypted (b64): ",token_dataencrypted) html_str = """ <p> Este sitio contiene un mensaje secreto </p> <div class="iv" id='iv_bytes'></div> <div class="Blowfish" id='msge_encriptado'></div> """ html = html_str.replace("iv_bytes", token_iv) time.sleep(1) html1 = html.replace("msge_encriptado", token_dataencrypted) Html_file= open("Blowfish-PCBC.html","w") Html_file.write(html1) Html_file.close()
7037dd8496b9d0cc0c9632ec6aac3890073dcc02
[ "Markdown", "Python" ]
2
Markdown
joyarce/tarea3cripto
f56ee8186cdd8db47db50224535696910c38a727
ec9d5ea6fe58e07ee97f13f1b03ded9cd827f691
refs/heads/master
<repo_name>mechanicznapomarancza/LZW<file_sep>/main.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define D_MAX 100000 #define W_MAX 1000 typedef struct { char s[W_MAX]; } dictionary; int next_available = 0; //public dictionary dictionary d[D_MAX]={"\0"}; //functions int cnt_file(FILE *); void prnt_arr(char*,int); void dict_prefill(); void ctos(char *, char); void dict_add(char *); int dict_exist(char *); void code(char *, int, FILE *); int main(int argc, char const *argv[]) { /*necessary variables*/ char *c; int i = 0; FILE *ft; int c_count = 0; /*working with text file*/ if((ft=fopen(argv[1], "r"))!=NULL) { c_count = cnt_file(ft); //assigning new memory for array of characters c = (char*)malloc(c_count*sizeof(char)); //copying text from file to array rewind(ft); while(fscanf(ft,"%c", &c[i++])!=EOF); //printing a7rray (for checking if everything is OK) //prnt_arr(c,c_count); fclose(ft); //mamy już teskt z pliku w tablicy dict_prefill(); if((ft=fopen(argv[2], "a+"))!=NULL) { code(c,c_count, ft); fclose(ft); // fclose(f2); } } else { printf("File not opened, make sure it exists!\n"); } printf("\n\nWielkosc slownika: %d na %d pozycji. Ilosc znakow w oryginale: %d",next_available, D_MAX, c_count); free(c); return 0; } int cnt_file(FILE *ft) { /* * WEJSCIE: wskaznik na plik * WYJSCIE: liczba znakow wewnatrz tego pliku */ char d; static int cnt =0; while(fscanf(ft, "%c", &d)!=EOF) cnt++; return cnt; } void prnt_arr(char *c, int size_c) { /* * WEJSCIE: wskaznik na lancuch znakow * wielkosc lancucha znakow * PROCEDURA: wyswietlanie lancucha znakow */ for(int i=0; i < size_c; i++) printf("%c", c[i]); } void dict_prefill() { /* * PROCEDURA: uzupelnienie slownika znakami z tablicy ASCII */ char str[2]; for(next_available; next_available<128; next_available++) { ctos(str, next_available); strcat(d[next_available].s,str); } } void ctos(char *s, char letter) { /* * WEJSCIE: wskaznik na dwuelementowy lancuch znakow (ozn. s) * pojedynczy znak do zamiany w lancuch (ozn. letter) * PROCEDURA: zamienienie znaku w lancuch znakow */ s[0] = (char)letter; s[1] = '\0'; } void dict_add(char *str) { /* WEJSCIE: lancuch znakow (ozn. s) * PROCEDURA: dodanie podanego na wejsciu lancucha znakow * na ostatnia wolna pozycje w slowniku */ strcat(d[next_available].s, str); } int dict_exist(char *str) { int i; for(i=0; i<next_available; i++) { if(strcmp(d[i].s,str)==0) return i; } return -1; } void code(char *c, int size_c, FILE *ft) { //fprintf(f, "words;dict_size;time\n"); int i, pos; char a[W_MAX]="\0"; char b[2]; for(i=0; i<size_c; i++) { ctos(b,c[i]); pos = dict_exist(a); strcat(a,b); if(dict_exist(a)==(-1)) { fprintf(ft,"%c", pos); strcat(d[next_available++].s,a); strcpy(a,b); } //fprintf(f,"%i;%i;%f\n",i, next_available, (float)(clock())/(float)(CLOCKS_PER_SEC)); /* if(next_available>=D_MAX) { fprintf(f,"\n\nprzeciazenie slownika \n"); break; } } fclose(f);*/ } } <file_sep>/README.md # LZW Projekt informatyczny na PRM v.0.1 Wstępna wersja projektu: - program potrafi odczytać plik tekstowy i zakodować go metodą lzw - program odczytuje ścieżki do plików wejściowego i wyjściowego jako parametry programu To-do list: 1) dorzucić parametr programu wybierający kompresję/dekompresję 2) zrobić zabezpieczenia przed podaniem złych plików 3) ZROBIĆ ALGORYTM DEKOMPRESJI #important 4) sprawdzić czas wykonywania programu (dopisać funkcję spisującą: ilość liter, wielkość słownika, czas wykonywania) (dopasować funkcję i wyznaczyć teoretyczny, przybliżony czas wykonywania programu)
c4075ffe09a8903dd0dd3a6004d0c097845b4f23
[ "Markdown", "C" ]
2
C
mechanicznapomarancza/LZW
77373dcf37b699763e30ef58ad95ca74d42cb60e
af8b8160bedef64c005fdabfe985497ac56fadf9
refs/heads/master
<repo_name>alexbarron/oo-student-scraper-v-000<file_sep>/scrape_selects.rb students = css("div.student-card") name = students.first.css("h4.student-name").text location = students.first.css("p.student-location").text profile_url = students.first.css("a").first["href"] #potential loop students.each do |students| name = student.css("h4.student-name").text location = student.css("p.student-location").text profile_url = student.css("a").first["href"] end # for profile page scraping profile_page = css("") # Need to pullin array of all social links, then detect ones where the href includes the social network name. # What to do about the blog? ## Maybe for blog, choose the href that does not include any of the social media names #Example of blogger profile: http://127.0.0.1:4000/students/danny-dawson.html social = css("div.social-icon-container a") twitter = social[0]["href"] linkedin = social[1]["href"] github = social[2]["href"] git = social.detect {|x| x["href"].include? "github"} blog = profile_quote = css("div.profile-quote").text bio = css.("div.descripton-holder p").text<file_sep>/lib/scraper.rb require 'open-uri' require 'pry' require 'nokogiri' class Scraper def self.scrape_index_page(index_url) index_page = Nokogiri::HTML(open(index_url)) student_info = index_page.css("div.student-card") students = [] student_info.each do |student| name = student.css("h4.student-name").text location = student.css("p.student-location").text profile_url = index_url + student.css("a").first["href"] student_hash = {name: name, location: location, profile_url: profile_url} students << student_hash end return students end def self.scrape_profile_page(profile_url) profile_page = Nokogiri::HTML(open(profile_url)) profile_hash = {} social = profile_page.css("div.social-icon-container a") social.each do |link| if link["href"].include? "twitter" profile_hash[:twitter] = link["href"] elsif link["href"].include? "linkedin" profile_hash[:linkedin] = link["href"] elsif link["href"].include? "github" profile_hash[:github] = link["href"] else profile_hash[:blog] = link["href"] end end profile_hash[:profile_quote] = profile_page.css("div.profile-quote").text profile_hash[:bio] = profile_page.css("div.description-holder p").text return profile_hash end end
2a01597be5dab48de22182d5f054c276a537f161
[ "Ruby" ]
2
Ruby
alexbarron/oo-student-scraper-v-000
4e2592f3e0387d82f7f4150edec54fb8b9b63634
78306669d8a354225ec64d7271a10184f9445f2a
refs/heads/master
<file_sep># Covid-19-Analysis Just another simple coronavirus mapper app - prepared for Advanced Databases course on AGH. <img src="https://scontent-waw1-1.xx.fbcdn.net/v/t1.15752-9/119447609_329753258236494_2014040091221266111_n.png?_nc_cat=102&_nc_sid=b96e70&_nc_ohc=pc0CbT1hAg0AX_OaQ-m&_nc_ht=scontent-waw1-1.xx&oh=0dedc1fce6ef41d78be07908e6332f13&oe=5F861452" align:center> ## Overview Django website showing an interactive map of confirmed cases (based on data pulled from WHO repo). Interaction allows for: - selecting a country and displaying more details Clicking a country triggers an AJAX call to the REST API of our website. This pulls additional data for the selected country and shows its geometry on the map. ## Database Schema <img src="https://scontent-waw1-1.xx.fbcdn.net/v/t1.15752-9/119089960_789328245155282_2305347574397524466_n.png?_nc_cat=111&_nc_sid=b96e70&_nc_ohc=yX4SdTG05iYAX8qQooN&_nc_ht=scontent-waw1-1.xx&oh=ebfaf96f1717415aa87a049903750ff1&oe=5F8317E2" align:center width="800" height="600"> ## Project Requirements - Anaconda - Python >3.7 - Django 3 - DRF (Django Rest Framework) + DRF-Gis - LeafletJS (django-leaflet) - PostgreSQL - PostGIS - GDAL ### 💪 More to come as we develop the project! 💪 <file_sep>import pandas as pd from webmap.models import Confirmed from webmap.models import Deaths from webmap.models import Recovered from webmap.models import WorldBorder confirmed = pd.read_csv('../World_total_data/Wolrd_Confirmed.csv') deaths = pd.read_csv('../World_total_data/Wolrd_Deaths.csv') recovered = pd.read_csv('../World_total_data/Wolrd_Recovered.csv') def run(): print('__Confirmed__') for x in confirmed.iterrows(): C = Confirmed(date=confirmed['date'][x[0]], total=confirmed['confirmed_total'][x[0]]) print(confirmed['country'][x[0]]) try: C.country = WorldBorder.objects.get(name=confirmed['country'][x[0]]) except WorldBorder.DoesNotExist: C.country = None C.save() print('__Deaths__') for x in deaths.iterrows(): D = Deaths(date=deaths['date'][x[0]], total=deaths['deaths_total'][x[0]]) print(deaths['country'][x[0]]) try: D.country = WorldBorder.objects.get(name=deaths['country'][x[0]]) except WorldBorder.DoesNotExist: D.country = None D.save() print('__Confirmed__') for x in recovered.iterrows(): R = Recovered(date=recovered['date'][x[0]], total=recovered['recovered_total'][x[0]]) print(recovered['country'][x[0]]) try: R.country = WorldBorder.objects.get(name=recovered['country'][x[0]]) except WorldBorder.DoesNotExist: R.country = None R.save()<file_sep>from django.contrib import admin from django.contrib.gis.admin import OSMGeoAdmin from .models import WorldBorder @admin.register(WorldBorder) class WorldBorderAdmin(OSMGeoAdmin): default_lon = 0 # underscores for readability default_lat = 0 default_zoom = 1 <file_sep>from rest_framework import serializers from django.db.models import Max from django.contrib.gis.geos import Point from rest_framework_gis.serializers import GeoFeatureModelSerializer, GeometrySerializerMethodField from .models import Confirmed, WorldBorder class CovidConfirmedSerializer(serializers.ModelSerializer): class Meta: model = Confirmed fields = ('total', ) class CountrySerializer(GeoFeatureModelSerializer): current_total = serializers.SerializerMethodField("get_current_total") location = GeometrySerializerMethodField() # allows to compute value during serialization def get_current_total(self, country): # SerializerMethodField automatically infers callback from variable name try: items = Confirmed.objects.filter(country=country.pk).latest('date') except Confirmed.DoesNotExist: items = Confirmed(country=country, date=None, total=None) serializer = CovidConfirmedSerializer(instance=items) return serializer.data def get_location(self, obj): return Point(obj.lon, obj.lat) class Meta: model = WorldBorder geo_field = 'location' fields = ('name', 'pop2005', 'current_total', ) class SelectedGeometrySerializer(GeoFeatureModelSerializer): class Meta: model = WorldBorder geo_field = 'mpoly' fields = ('name',) <file_sep>import pandas as pd from webmap.models import GDP from webmap.models import Bloodtype from webmap.models import Healthcare from webmap.models import Smoking from webmap.models import WorldBorder gdp = pd.read_csv('../supplemental_data/transformed/gdp.csv') bloodtypes = pd.read_csv('../supplemental_data/transformed/bloodtypes.csv') healthcare = pd.read_csv('../supplemental_data/transformed/healthcare_rank.csv', engine='python') smoking_rate = pd.read_csv('../supplemental_data/transformed/smoking_rate.csv') def run(): print('__GPD__') for x in gdp.iterrows(): G = GDP(rank=gdp['rank'][x[0]], gdpPerCapita=gdp['gdpPerCapita'][x[0]]) print(gdp['country'][x[0]]) try: G.country = WorldBorder.objects.get(name=gdp['country'][x[0]]) except WorldBorder.DoesNotExist: G.country = None G.save() print('___Bloodtype___') for x in bloodtypes.iterrows(): B = Bloodtype(Ominus=bloodtypes['Ominus'][x[0]], Oplus=bloodtypes['Oplus'][x[0]], Aminus=bloodtypes['Aminus'][x[0]], Aplus=bloodtypes['Aplus'][x[0]], Bminus=bloodtypes['Bminus'][x[0]], Bplus=bloodtypes['Bplus'][x[0]], ABminus=bloodtypes['ABminus'][x[0]], ABplus=bloodtypes['ABplus'][x[0]]) print(bloodtypes['country'][x[0]]) try: B.country = WorldBorder.objects.get(name=bloodtypes['country'][x[0]]) except WorldBorder.DoesNotExist: B.country = None B.save() print('___Healthcare___') for x in healthcare.iterrows(): H = Healthcare(rank=healthcare['rank'][x[0]], score=healthcare['score'][x[0]]) print(healthcare['country'][x[0]]) try: H.country = WorldBorder.objects.get(name=healthcare['country'][x[0]]) except WorldBorder.DoesNotExist: H.country = None H.save() print('___Smoking___') for x in smoking_rate.iterrows(): S = Smoking(male=smoking_rate['male'][x[0]], female=smoking_rate['female'][x[0]], total=smoking_rate['total'][x[0]]) print(smoking_rate['country'][x[0]]) try: S.country = WorldBorder.objects.get(name=smoking_rate['country'][x[0]]) except WorldBorder.DoesNotExist: S.country = None S.save() <file_sep># This file may be used to create an environment using: # $ conda create --name <env> --file <this file> # platform: win-64 @EXPLICIT https://repo.anaconda.com/pkgs/main/win-64/blas-1.0-mkl.conda https://repo.anaconda.com/pkgs/main/win-64/ca-certificates-2020.7.22-0.conda https://repo.anaconda.com/pkgs/main/win-64/icc_rt-2019.0.0-h0cc432a_1.conda https://repo.anaconda.com/pkgs/main/win-64/intel-openmp-2020.2-254.conda https://repo.anaconda.com/pkgs/msys2/win-64/msys2-conda-epoch-20160418-1.tar.bz2 https://repo.anaconda.com/pkgs/main/win-64/vs2015_runtime-14.16.27012-hf0eaf9b_3.conda https://repo.anaconda.com/pkgs/msys2/win-64/m2w64-expat-2.1.1-2.tar.bz2 https://repo.anaconda.com/pkgs/msys2/win-64/m2w64-gmp-6.1.0-2.tar.bz2 https://repo.anaconda.com/pkgs/msys2/win-64/m2w64-libiconv-1.14-6.tar.bz2 https://repo.anaconda.com/pkgs/msys2/win-64/m2w64-libwinpthread-git-5.0.0.4634.697f757-2.tar.bz2 https://repo.anaconda.com/pkgs/main/win-64/mkl-2020.2-256.conda https://repo.anaconda.com/pkgs/main/win-64/vc-14.1-h0510ff6_4.conda https://repo.anaconda.com/pkgs/main/win-64/bzip2-1.0.8-he774522_0.conda https://repo.anaconda.com/pkgs/main/win-64/cfitsio-3.470-he774522_5.conda https://repo.anaconda.com/pkgs/main/win-64/expat-2.2.9-h33f27b4_2.conda https://repo.anaconda.com/pkgs/main/win-64/geos-3.8.0-h33f27b4_0.conda https://repo.anaconda.com/pkgs/main/win-64/icu-58.2-ha925a31_3.conda https://repo.anaconda.com/pkgs/main/win-64/jpeg-9b-hb83a4c4_2.conda https://repo.anaconda.com/pkgs/main/win-64/libiconv-1.15-h1df5818_7.conda https://repo.anaconda.com/pkgs/main/win-64/lz4-c-1.8.1.2-h2fa13f4_0.conda https://repo.anaconda.com/pkgs/msys2/win-64/m2w64-gcc-libs-core-5.3.0-7.tar.bz2 https://repo.anaconda.com/pkgs/main/win-64/openssl-1.1.1g-he774522_1.conda https://repo.anaconda.com/pkgs/main/win-64/pcre-8.44-ha925a31_0.conda https://repo.anaconda.com/pkgs/main/win-64/tbb-2018.0.5-he980bc4_0.conda https://repo.anaconda.com/pkgs/main/win-64/tk-8.6.10-he774522_0.conda https://repo.anaconda.com/pkgs/main/win-64/xerces-c-3.2.2-ha925a31_0.conda https://repo.anaconda.com/pkgs/main/win-64/xz-5.2.5-h62dcd97_0.conda https://repo.anaconda.com/pkgs/main/win-64/zlib-1.2.11-h62dcd97_4.conda https://repo.anaconda.com/pkgs/main/win-64/freexl-1.0.5-hfa6e2cd_0.conda https://repo.anaconda.com/pkgs/main/win-64/hdf4-4.2.13-h712560f_2.conda https://repo.anaconda.com/pkgs/main/win-64/hdf5-1.10.4-h7ebc959_0.conda https://repo.anaconda.com/pkgs/main/win-64/krb5-1.16.4-hc04afaa_0.conda https://repo.anaconda.com/pkgs/main/win-64/libboost-1.67.0-hd9e427e_4.conda https://repo.anaconda.com/pkgs/main/win-64/libpng-1.6.37-h2a8f88b_0.conda https://repo.anaconda.com/pkgs/main/win-64/libssh2-1.9.0-h7a1dbc1_1.conda https://repo.anaconda.com/pkgs/main/win-64/libxml2-2.9.10-h464c3ec_1.conda https://repo.anaconda.com/pkgs/msys2/win-64/m2w64-gcc-libgfortran-5.3.0-6.tar.bz2 https://repo.anaconda.com/pkgs/main/win-64/sqlite-3.33.0-h2a8f88b_0.conda https://repo.anaconda.com/pkgs/main/win-64/zstd-1.3.7-h508b16e_0.conda https://repo.anaconda.com/pkgs/main/win-64/kealib-1.4.7-h07cbb95_6.conda https://repo.anaconda.com/pkgs/main/win-64/libcurl-7.67.0-h2a8f88b_0.conda https://repo.anaconda.com/pkgs/main/win-64/libkml-1.3.0-he5f2a48_4.conda https://repo.anaconda.com/pkgs/main/win-64/libpq-11.2-h3235a2c_0.conda https://repo.anaconda.com/pkgs/main/win-64/libtiff-4.1.0-h56a325e_0.conda https://repo.anaconda.com/pkgs/msys2/win-64/m2w64-gcc-libs-5.3.0-7.tar.bz2 https://repo.anaconda.com/pkgs/main/win-64/proj-6.2.1-h9f7ef89_0.conda https://repo.anaconda.com/pkgs/main/win-64/python-3.8.5-h5fd99cc_1.conda https://repo.anaconda.com/pkgs/main/noarch/asgiref-3.2.10-py_0.conda https://repo.anaconda.com/pkgs/main/win-64/certifi-2020.6.20-py38_0.conda https://repo.anaconda.com/pkgs/main/win-64/curl-7.67.0-h2a8f88b_0.conda https://repo.anaconda.com/pkgs/main/win-64/geotiff-1.5.1-h5770a2b_1.conda https://repo.anaconda.com/pkgs/main/win-64/libspatialite-4.3.0a-h7ffb84d_0.conda https://repo.anaconda.com/pkgs/msys2/win-64/m2w64-gettext-0.19.7-2.tar.bz2 https://repo.anaconda.com/pkgs/main/win-64/openjpeg-2.3.0-h5ec785f_1.conda https://repo.anaconda.com/pkgs/main/win-64/postgresql-11.2-h3235a2c_0.conda https://repo.anaconda.com/pkgs/main/win-64/psycopg2-2.8.4-py38h7a1dbc1_0.conda https://repo.anaconda.com/pkgs/main/noarch/pytz-2020.1-py_0.conda https://repo.anaconda.com/pkgs/main/noarch/six-1.15.0-py_0.conda https://repo.anaconda.com/pkgs/main/noarch/sqlparse-0.3.1-py_0.conda https://repo.anaconda.com/pkgs/main/noarch/wheel-0.35.1-py_0.conda https://repo.anaconda.com/pkgs/main/win-64/wincertstore-0.2-py38_0.conda https://repo.anaconda.com/pkgs/main/noarch/django-3.0.3-py_0.conda https://repo.anaconda.com/pkgs/main/win-64/libnetcdf-4.6.1-h411e497_2.conda https://repo.anaconda.com/pkgs/msys2/win-64/m2w64-xz-5.2.2-2.tar.bz2 https://repo.anaconda.com/pkgs/main/win-64/mkl-service-2.3.0-py38hb782905_0.conda https://repo.anaconda.com/pkgs/main/win-64/setuptools-49.6.0-py38_0.conda https://repo.anaconda.com/pkgs/main/win-64/tiledb-1.6.3-h7b000aa_0.conda https://repo.anaconda.com/pkgs/main/win-64/libgdal-3.0.2-h1155b67_0.conda https://repo.anaconda.com/pkgs/main/win-64/numpy-base-1.19.1-py38ha3acd2a_0.conda https://repo.anaconda.com/pkgs/main/win-64/pip-20.2.2-py38_0.conda https://repo.anaconda.com/pkgs/main/win-64/gdal-3.0.2-py38hdf43c64_0.conda https://repo.anaconda.com/pkgs/main/win-64/mkl_fft-1.1.0-py38h45dec08_0.conda https://repo.anaconda.com/pkgs/main/win-64/mkl_random-1.1.1-py38h47e9c7a_0.conda https://repo.anaconda.com/pkgs/main/win-64/numpy-1.19.1-py38h5510c5b_0.conda <file_sep>from django.contrib.gis.db import models from django.core.validators import MaxValueValidator, MinValueValidator class WorldBorder(models.Model): # Regular Django fields corresponding to the attributes in the world borders shapefile. name = models.CharField(max_length=50, primary_key=True) area = models.IntegerField() pop2005 = models.IntegerField('Population 2005', default="") fips = models.CharField('FIPS Code', max_length=2, null=True) iso2 = models.CharField('2 Digit ISO', max_length=2, default="") iso3 = models.CharField('3 Digit ISO', max_length=3, default="") un = models.IntegerField('United Nations Code', default="") region = models.IntegerField('Region Code', default="") subregion = models.IntegerField('Sub-Region Code', default="") lon = models.FloatField(default="") lat = models.FloatField(default="") # GeoDjango-specific: a geometry field (MultiPolygonField) mpoly = models.MultiPolygonField(default="") # Returns the string representation of the model. def __str__(self): return self.name class Confirmed(models.Model): date = models.CharField(max_length=15) total = models.IntegerField() country = models.ForeignKey(WorldBorder, default="", on_delete=models.CASCADE, blank=True, null=True, related_name='covid_confirmed') class Deaths(models.Model): date = models.CharField(max_length=15) total = models.IntegerField() country = models.ForeignKey(WorldBorder, default="", on_delete=models.CASCADE, blank=True, null=True) class Recovered(models.Model): date = models.CharField(max_length=15) total = models.IntegerField() country = models.ForeignKey(WorldBorder, default="", on_delete=models.CASCADE, blank=True, null=True) class Bloodtype(models.Model): Ominus = models.CharField(max_length=10) Oplus = models.CharField(max_length=10) Aminus = models.CharField(max_length=10) Aplus = models.CharField(max_length=10) Bminus = models.CharField(max_length=10) Bplus = models.CharField(max_length=10) ABminus = models.CharField(max_length=10) ABplus = models.CharField(max_length=10) country = models.ForeignKey(WorldBorder, default="", on_delete=models.CASCADE, blank=True, null=True) class Healthcare(models.Model): rank = models.IntegerField() score = models.FloatField( validators=[MinValueValidator(0), MaxValueValidator(100)] ) country = models.ForeignKey(WorldBorder, default="", on_delete=models.CASCADE, blank=True, null=True) class Smoking(models.Model): male = models.FloatField( validators=[MinValueValidator(0), MaxValueValidator(100)], ) female = models.FloatField( validators=[MinValueValidator(0), MaxValueValidator(100)], ) total = models.FloatField( validators=[MinValueValidator(0), MaxValueValidator(100)], ) country = models.ForeignKey(WorldBorder, default="", on_delete=models.CASCADE, blank=True, null=True) class GDP(models.Model): rank = models.IntegerField() gdpPerCapita = models.FloatField() country = models.ForeignKey(WorldBorder, default="", on_delete=models.CASCADE, blank=True, null=True) <file_sep>from rest_framework.viewsets import ReadOnlyModelViewSet from rest_framework_gis.filters import InBBoxFilter from rest_framework_gis.pagination import GeoJsonPagination from django.views.generic import TemplateView from django.http import HttpResponse, JsonResponse from django.db.models import Max, Sum from webmap import models from .serializers import CountrySerializer, SelectedGeometrySerializer from webmap import models from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status # Create your views here. class CountryViewSet(ReadOnlyModelViewSet): queryset = models.WorldBorder.objects.all() serializer_class = CountrySerializer bbox_filter_field = 'point' filter_backends = (InBBoxFilter, ) class SelectedGeometryViewSet(ReadOnlyModelViewSet): serializer_class = SelectedGeometrySerializer bbox_filter_field = 'mpoly' filter_backends = (InBBoxFilter, ) def get_queryset(self, **kwargs): queryset = models.WorldBorder.objects.filter(name=self.kwargs['country_name']).only('mpoly') return queryset class MainPageView(TemplateView): confirmed_total = models.Confirmed.objects.values('country_id__name').annotate(Max('total')).aggregate(Sum('total__max'))['total__max__sum'] template_name = "webmap/map.html" def get_context_data(self, **context): context['confirmed_total'] = self.confirmed_total return context @api_view(['GET']) def dataLoad(request, pk): # main class try: country = models.WorldBorder.objects.get(name=pk) except models.WorldBorder.DoesNotExist: content = {pk:'No such country'} return Response(content, status=status.HTTP_404_NOT_FOUND) # supplemental data try: gdp = models.GDP.objects.get(country_id=country.name) except models.GDP.DoesNotExist: gdp = models.GDP(rank=None, gdpPerCapita=None) try: smoking = models.Smoking.objects.get(country_id=country.name) except models.Smoking.DoesNotExist: smoking = models.Smoking(male=None, female=None, total=None) try: healthcare = models.Healthcare.objects.get(country_id=country.name) except models.Healthcare.DoesNotExist: healthcare = models.Healthcare(rank=None, score=None) try: bloodtype = models.Bloodtype.objects.get(country_id=country.name) except models.Bloodtype.DoesNotExist: bloodtype = models.Bloodtype(Ominus=None, Oplus=None, Aminus=None, Bminus=None, Bplus=None, ABminus =None, ABplus=None) # covid data try: confirmed = models.Confirmed.objects.filter(country_id=country.name).latest('date') except models.Confirmed.DoesNotExist: confirmed = models.Confirmed(date=None, total=None) try: recovered = models.Recovered.objects.filter(country_id=country.name).latest('date') except models.Recovered.DoesNotExist: recovered = models.Recovered(date=None, total=None) try: deaths = models.Deaths.objects.filter(country_id=country.name).latest('date') except models.Deaths.DoesNotExist: deaths = models.Deaths(date=None, total=None) all_data = { 'Country': { 'name': country.name, 'area': country.area, 'pop2005': country.pop2005, 'fips': country.fips, 'iso2': country.iso2, 'iso3': country.iso3, 'un': country.un, 'region': country.region, 'subregion': country.subregion, 'lon': country.lon, 'lat': country.lat, }, 'Date': confirmed.date, 'Confirmed_total': confirmed.total, 'Recovered_total': recovered.total, 'Deaths_total': deaths.total, 'Bloodtype': { 'Ominus': bloodtype.Ominus, 'Oplus': bloodtype.Oplus, 'Aminus': bloodtype.Aminus, 'Aplus': bloodtype.Aplus, 'Bminus': bloodtype.Bminus, 'Bplus': bloodtype.Bplus, 'ABminus': bloodtype.ABminus, 'ABplus': bloodtype.ABplus }, 'Healthcare': { 'rank': healthcare.rank, 'score': healthcare.score }, 'Smoking': { 'male': smoking.male, 'female': smoking.female, 'total': smoking.total }, 'GDP': { 'rank': gdp.rank, 'gdpPerCapita': gdp.gdpPerCapita } } return JsonResponse(all_data)
99150039f4ce12c6bd93630088a87d2cca6e52b4
[ "Markdown", "Python", "Text" ]
8
Markdown
TomasiewiczW/Covid-19-Analysis
9f548cd357c1d5cfbe8b031063755de6eb13a5fa
7d271ed20c01da502b9328152a33a02fb727ecc8
refs/heads/master
<repo_name>Nugine/tester<file_sep>/src/output.rs use std::fmt::Display; use serde::Serialize; #[derive(Debug, Serialize)] pub struct Time { pub real: u64, pub user: u64, pub sys: u64, } #[derive(Debug, Serialize)] pub struct Output { pub code: Option<i64>, pub signal: Option<String>, pub time: Time, // in ms pub memory: u64, // in kb } impl Display for Output { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { if let Some(code) = &self.code { writeln!(f, "code: {}", code)?; } if let Some(sig) = &self.signal { writeln!(f, "signal: {}", sig)?; } writeln!(f, "real time: {} ms", self.time.real)?; writeln!(f, "user time: {} ms", self.time.user)?; writeln!(f, "sys time: {} ms", self.time.sys)?; if self.memory > 4096 { write!(f, "memory: {:.3} MB", (self.memory as f64) / 1024.0) } else { write!(f, "memory: {} KB", self.memory) } } } <file_sep>/test/tim.c #include <stdio.h> #include <stdlib.h> int main() { int lim = rand() % 100 + 5 * 1e8; for (int i = 0; i < lim; ++i) { if (i % 100000000 == 0) { printf("%d\n", i); } } return 0; }<file_sep>/src/main.rs mod error; mod opt; mod output; mod tester; #[cfg(test)] mod test; use crate::opt::Opt; use crate::tester::{Tester, TraitTester}; use structopt::StructOpt; #[inline(always)] fn err_exit<E: std::fmt::Display>(e: E) -> ! { eprintln!("tester: {}", e); std::process::exit(1) } fn main() { let opt = Opt::from_args(); let json = opt.json; use std::io::Write; let mut output_file: Box<dyn Write> = match opt.output { None => Box::new(std::io::stderr()), Some(ref path) => match std::fs::File::create(path) { Err(e) => err_exit(e), Ok(f) => Box::new(f), }, }; let tester = Tester::new(opt.target, opt.args); match tester.run() { Err(err) => { if let Err(e) = writeln!(output_file, "tester: {}", err.msg()) { err_exit(e) } } Ok(out) => { let out_string = if json { serde_json::to_string(&out).unwrap() } else { format!("{}", out) }; if let Err(e) = writeln!(output_file, "{}", out_string) { err_exit(e) } } } } <file_sep>/test/mem.cpp #include <cstdio> #include <cstring> int main() { int lim = 2 * 100000; long long *a = new long long[lim]; memset(a, 0, lim); return 0; }<file_sep>/src/error.rs use std::fmt::Display; #[derive(Debug)] pub struct Error { message: String, } impl Error { pub fn new(msg: &str) -> Self { Self { message: msg.into(), } } pub fn msg(&self) -> &str { &self.message } } impl<T: Display> From<T> for Error { fn from(error: T) -> Self { Self { message: format!("{}", error), } } } <file_sep>/src/tester.rs #[cfg(unix)] mod linux; #[cfg(windows)] mod windows; use crate::error::Error; use crate::output::Output; use std::ffi::OsString; pub trait TraitTester { fn run(&self) -> Result<Output, Error>; } pub struct Tester { target: OsString, args: Vec<OsString>, } impl Tester { pub fn new(target: OsString, args: Vec<OsString>) -> Self { Self { target, args } } } <file_sep>/README.md # tester ## Install cargo install --git https://github.com/Nugine/tester.git ## Example $ tester ./test/hello Hello, world! code: 0 real time: 3 ms user time: 0 ms sys time: 2 ms memory: 1460 KB $ echo hey | tester cat hey code: 0 real time: 5 ms user time: 0 ms sys time: 4 ms memory: 2124 KB $ tester -j ping -- www.baidu.com -c 5 > /dev/null {"code":0,"signal":null,"time":{"real":4051,"user":4,"sys":4},"memory":2748} ## Usage tester 0.3.1 Nugine <<EMAIL>> USAGE: tester [FLAGS] [OPTIONS] <target> [-- <args>...] FLAGS: -h, --help Prints help information -j, --json Json output -V, --version Prints version information OPTIONS: -o, --output <output> output file path (default stderr) ARGS: <target> command to run <args>... arguments to be passed ## Output declaration ```typescript declare type TesterOutput = ({ code: number signal: null } | { code: null, signal: string }) & { time: { real: number, user: number, sys: number }, memory: number } ``` ## Changelog + Add option `--output` on `0.3.1` + Break changes on `0.3.0` delete `--arg` pass arguments by `[-- <args>...]` ## Todo more test cases!<file_sep>/src/opt.rs use std::ffi::OsString; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(name = "tester")] pub struct Opt { #[structopt(parse(from_os_str), help = "command to run")] pub target: OsString, #[structopt(short = "j", long = "json", help = "Json output")] pub json: bool, #[structopt( short = "o", long = "output", parse(from_os_str), help = "output file path (default stderr)" )] pub output: Option<OsString>, #[structopt(last = true, parse(from_os_str), help = "arguments to be passed")] pub args: Vec<OsString>, } <file_sep>/Cargo.toml [package] name = "tester" version = "0.3.1" authors = ["Nugine <<EMAIL>>"] edition = "2018" [dependencies] libc = "^0.2" structopt = "^0.2" serde_json = "1.0.39" serde = { version = "1.0.90", features = ["derive"] } [target.'cfg(unix)'.dependencies] nix = "^0.13" [target.'cfg(windows)'.dependencies] winapi = { version = "^0.3", features = ["std", "psapi"] } <file_sep>/src/tester/windows.rs use super::{Tester, TraitTester}; use crate::error::Error; use crate::output::{Output, Time}; use std::os::windows::io::AsRawHandle; use std::os::windows::io::RawHandle; use std::process::Command; use winapi::shared::minwindef::FILETIME; use winapi::shared::ntdef::ULARGE_INTEGER; use winapi::um::processthreadsapi::GetProcessTimes; use winapi::um::psapi::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; unsafe fn to_u64(ft: FILETIME) -> u64 { let mut ui = std::mem::zeroed::<ULARGE_INTEGER>(); ui.s_mut().LowPart = ft.dwLowDateTime; ui.s_mut().HighPart = ft.dwHighDateTime; *ui.QuadPart() } unsafe fn get_time(h_process: RawHandle) -> Result<Time, Error> { let mut creation_time = std::mem::zeroed::<FILETIME>(); let mut exit_time = std::mem::zeroed::<FILETIME>(); let mut kernel_time = std::mem::zeroed::<FILETIME>(); let mut user_time = std::mem::zeroed::<FILETIME>(); if GetProcessTimes( h_process, &mut creation_time, &mut exit_time, &mut kernel_time, &mut user_time, ) == 0 { return Err(Error::new("fail to get time of process")); } // 1ms = 10000 * 100ns Ok(Time { real: to_u64(exit_time).saturating_sub(to_u64(creation_time)) / 10000, user: to_u64(user_time) / 10000, sys: to_u64(kernel_time) / 10000, }) } unsafe fn get_memory(h_process: RawHandle) -> Result<u64, Error> { let mut pmc = std::mem::zeroed::<PROCESS_MEMORY_COUNTERS>(); let cb = std::mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32; if GetProcessMemoryInfo(h_process, &mut pmc, cb) == 0 { return Err(Error::new("fail to get memory info of process")); } Ok((pmc.PeakWorkingSetSize as u64) / 1024) } impl TraitTester for Tester { fn run(&self) -> Result<Output, Error> { let mut child = Command::new(&self.target) .args(&self.args) .spawn() .map_err(Error::from)?; let status = child.wait().map_err(Error::from)?; let code: Option<i64> = status.code().map(i64::from); let handle = child.as_raw_handle(); let time = unsafe { get_time(handle)? }; let memory = unsafe { get_memory(handle)? }; Ok(Output { code, signal: None, time, memory, }) } } <file_sep>/src/tester/linux.rs use super::{Tester, TraitTester}; use crate::error::Error; use crate::output::{Output, Time}; use std::os::unix::process::ExitStatusExt; use std::process::{Command, ExitStatus}; use std::time::SystemTime; use nix::sys::signal::Signal; use nix::unistd::Pid; use libc::{c_int, rusage, wait4, WSTOPPED}; fn u32_to_i32(u: u32) -> Option<i32> { if u > i32::max_value() as u32 { None } else { Some(u as i32) } } impl TraitTester for Tester { fn run(&self) -> Result<Output, Error> { let t0 = SystemTime::now(); let child = Command::new(&self.target) .args(&self.args) .spawn() .map_err(Error::from)?; let pid = Some(child.id()) .and_then(u32_to_i32) .ok_or_else(|| Error::new("Pid overflow")) .map(Pid::from_raw)?; let (time, memory, status) = unsafe { let mut status = std::mem::zeroed::<c_int>(); let mut ru = std::mem::zeroed::<rusage>(); if wait4( pid.as_raw(), &mut status as *mut c_int, WSTOPPED, &mut ru as *mut rusage, ) == -1 { return Err(Error::new("fail to wait child process")); } let real = t0 .elapsed() .map(|d| d.as_millis() as u64) .map_err(Error::from)?; let time = Time { real, user: (ru.ru_utime.tv_sec * 1000 + ru.ru_utime.tv_usec / 1000).max(0) as u64, sys: (ru.ru_stime.tv_sec * 1000 + ru.ru_stime.tv_usec / 1000).max(0) as u64, }; let memory: u64 = ru.ru_maxrss.max(0) as u64; let status = ExitStatus::from_raw(status); (time, memory, status) }; let code: Option<i64> = status.code().map(i64::from); let signal: Option<String> = status .signal() .and_then(|s| Signal::from_c_int(s).ok()) .map(|sig| format!("{}", sig)); Ok(Output { code, signal, time, memory, }) } } <file_sep>/src/test.rs use crate::tester::{Tester, TraitTester}; use std::ffi::OsString; #[test] fn test_ok() { let r = Tester::new(OsString::from("./test/hello"), Vec::new()).run(); assert!(r.is_ok()); let out = r.unwrap(); dbg!(&out); assert_eq!(out.code, Some(0)); assert_eq!(out.signal, None); assert!(out.time.user < 10); assert!(out.memory < 2000); } #[test] fn test_err() { let r = Tester::new(OsString::from("./test/"), Vec::new()).run(); assert!(r.is_err()); let e = r.unwrap_err(); assert_eq!(e.msg(), "Permission denied (os error 13)"); } #[test] fn test_mem() { let r = Tester::new(OsString::from("./test/mem"), Vec::new()).run(); assert!(r.is_ok()); let out = r.unwrap(); dbg!(&out); assert_eq!(out.code, Some(0)); assert_eq!(out.signal, None); assert!(out.time.real < 20); assert!(out.memory > 2500 && out.memory < 3000); } #[test] fn test_ret1() { let r = Tester::new(OsString::from("./test/ret1"), Vec::new()).run(); assert!(r.is_ok()); let out = r.unwrap(); dbg!(&out); assert_eq!(out.code, Some(1)); assert_eq!(out.signal, None); assert!(out.time.user < 10); assert!(out.memory < 1800); } #[cfg(unix)] #[test] fn test_seg() { let r = Tester::new(OsString::from("./test/seg"), Vec::new()).run(); assert!(r.is_ok()); let out = r.unwrap(); dbg!(&out); assert_eq!(out.code, None); assert_eq!(out.signal, Some("SIGSEGV".into())); assert!(out.time.user < 10); assert!(out.memory < 1800); } #[test] fn test_tim() { let r = Tester::new(OsString::from("./test/tim"), Vec::new()).run(); assert!(r.is_ok()); let out = r.unwrap(); dbg!(&out); assert_eq!(out.code, Some(0)); assert_eq!(out.signal, None); assert!(out.time.user > 950 && out.time.user < 1150); assert!(out.memory > 1000 && out.memory < 2000); } #[test] fn test_ping() { let r = Tester::new( OsString::from("ping"), vec!["-c".into(), "5".into(), "www.baidu.com".into()], ) .run(); assert!(r.is_ok()); let out = r.unwrap(); dbg!(&out); assert_eq!(out.code, Some(0)); assert_eq!(out.signal, None); assert!(out.time.real > 3500 && out.time.real < 5500); assert!(out.memory > 2500 && out.memory < 3500); }
70d741fc7c447d67fd7e261afebb26c9b95f5a14
[ "Markdown", "TOML", "Rust", "C", "C++" ]
12
Rust
Nugine/tester
82bed456bdf562bca7cb7e1178ba68ab3aaee9db
b6b3b2c98e9ea92bae581cac49c24abfe3cda50a
refs/heads/main
<file_sep>package com.luv2code.springdemo.service; import java.util.List; import com.luv2code.springdemo.entity.SuperHeroe; public interface SuperHeroeService { public List<SuperHeroe> getAllSuperHeroes(); public List<SuperHeroe> getSuperHeroesByName(String search); public void updateSuperHeroe(SuperHeroe superHeroe); public void deleteSuperHeroe(int id); public SuperHeroe getSuperHeroeById(int id); }<file_sep>package com.luv2code.springdemo.controller; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.luv2code.springdemo.entity.SuperHeroe; import com.luv2code.springdemo.service.SuperHeroeService; import exception.ResourceNotFoundException; @RestController @RequestMapping("/superheroes") public class SuperHeroeController { @Autowired private SuperHeroeService superHeroeService; // get list of all SuperHeroes @GetMapping("/list") List<SuperHeroe> showListAllSuperHeroes() throws ResourceNotFoundException { List<SuperHeroe> superHeroes = new ArrayList<>(); superHeroes = superHeroeService.getAllSuperHeroes(); if(superHeroes.isEmpty()) { throw new ResourceNotFoundException("List SuperHeroe is null : SuperHeroes not found in database"); } return superHeroes; } // get list of all SuperHeroes by name @GetMapping("/listByName/{search}") List<SuperHeroe> showListAllSuperHeroesByName(@PathVariable String search) throws ResourceNotFoundException { List<SuperHeroe> superHeroes = new ArrayList<>(); superHeroes = superHeroeService.getSuperHeroesByName(search); if(superHeroes.isEmpty()) { throw new ResourceNotFoundException("List of SuperHeroes is null : by name not found in database"); } return superHeroes; } // add mapping to UPDATE SuperHeroe @GetMapping("/updateSuperHeroe/{id}/{name}") public ResponseEntity < SuperHeroe > updateSuperHeroe(@PathVariable int id, @PathVariable String name) { SuperHeroe superHeroe = new SuperHeroe(id, name); superHeroeService.updateSuperHeroe(superHeroe); System.out.println("SuperHeroe updated"); return ResponseEntity.ok(superHeroe); } // add mapping to DELETE SuperHeroe @GetMapping("/delete/{id}") public void deleteSuperHeroe(@PathVariable int id) { superHeroeService.deleteSuperHeroe(id); System.out.println("SuperHeroe deleted"); } // add mapping to GET SuperHeroe BY ID @GetMapping("/getSuperHeroe/{id}") public ResponseEntity < SuperHeroe > getSuperHeroeById(@PathVariable int id) throws ResourceNotFoundException { SuperHeroe s = superHeroeService.getSuperHeroeById(id); if(s == null) { throw new ResourceNotFoundException("Object SuperHeroe is null : SuperHeroe not found in database"); } return ResponseEntity.ok().body(s); } } <file_sep>"# w2m-super-heroes Project" "# Documentation of API" "# endpoints availables" "# ******************************************************************************************************" "# when the system starts the H2 database is populated from HomeController.java endpoint : http://localhost:8080/w2m-super-heroes/demo/startH2" "# get all superheros --> http://localhost:8080/w2m-super-heroes/superheroes/list" "# get superheros by search string --> http://localhost:8080/w2m-super-heroes/superheroes/listByName/man" "# update superhero --> http://localhost:8080/w2m-super-heroes/superheroes/updateSuperHeroe/4/Thor" "# delete superhero --> http://localhost:8080/w2m-super-heroes/superheroes/delete/3" "# get superhero by id --> http://localhost:8080/w2m-super-heroes/superheroes/getSuperHeroe/2" <file_sep>package com.luv2code.springdemo.dao; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.luv2code.springdemo.entity.SuperHeroe; @Repository public class SuperHeroeDAOImpl implements SuperHeroeDAO { @Autowired private SessionFactory sessionFactory; @Override public List<SuperHeroe> getAllSuperHeroes() { Session currentSession = sessionFactory.getCurrentSession(); String queryString = "from SuperHeroe"; Query<SuperHeroe> theQuery = currentSession.createQuery(queryString, SuperHeroe.class); List<SuperHeroe> superHeroes = theQuery.getResultList(); return superHeroes; } @Override public List<SuperHeroe> getSuperHeroesByName(String search) { Session currentSession = sessionFactory.getCurrentSession(); String queryString = "from SuperHeroe where lower(name) like :theSearch order by name desc"; Query<SuperHeroe> theQuery = currentSession.createQuery(queryString, SuperHeroe.class); theQuery.setParameter("theSearch", "%" + search.toLowerCase() + "%"); List<SuperHeroe> employees = theQuery.getResultList(); return employees; } @Override public void updateSuperHeroe(SuperHeroe superHeroe) { Session currentSession = sessionFactory.getCurrentSession(); currentSession.saveOrUpdate(superHeroe); } @Override public void deleteSuperHeroe(int id) { Session currentSession = sessionFactory.getCurrentSession(); Query theQuery = currentSession.createQuery("delete from SuperHeroe where id=:superHeroeId"); theQuery.setParameter("superHeroeId", id); theQuery.executeUpdate(); } @Override public SuperHeroe getSuperHeroeById(int id) { Session currentSession = sessionFactory.getCurrentSession(); SuperHeroe s = currentSession.get(SuperHeroe.class, id); return s; } }
ee140335843952eb1830e533a7b10f06b52b0c4c
[ "Markdown", "Java" ]
4
Java
jescor123/w2m-super-heroes
e99592886bedcea948a4170045cea8216d01a42f
256ce7df92f896b962e010e91504cec5d57d3c86
refs/heads/master
<repo_name>contensive/aoAdminNavigator<file_sep>/Collections/Admin Navigator/AdminNavigator.js // //---------- // Open and close click methods for admin nav ajax menu //---------- // function AdminNavOpenClick(OffNode,OnNode,ContentNode,NodeID,onEmptyShow,onEmptyHide) { document.getElementById(OffNode).style.display='none'; document.getElementById(OnNode).style.display='block'; var e=document.getElementById(ContentNode); if(e.ok) {//already populated cj.ajax.addon('AdminNavigatorOpenNode','nodeid='+NodeID) navBindNodes(); }else{ e.ok='ok'; var arg = {contentNode:ContentNode}; arg.onEmptyHide = onEmptyHide; arg.onEmptyShow = onEmptyShow; cj.ajax.addonCallback("AdminNavigatorGetNode",'nodeid='+NodeID,AdminNavOpenClickCallback,arg); //cj.ajax.addon('AdminNavigatorGetNode','nodeid='+NodeID,'',ContentNode,onEmptyHide,onEmptyShow) } e.style.display='block'; } function AdminNavOpenClickCallback(serverResponse, arg ) { if (serverResponse == '') { if (document.getElementById(arg.onEmptyHide)) { document.getElementById(arg.onEmptyHide).style.display = 'none' } if (document.getElementById(arg.onEmptyShow)) { document.getElementById(arg.onEmptyShow).style.display = 'block' } } else { var el1 = document.getElementById(arg.contentNode); if (el1) { el1.innerHTML = serverResponse navBindNodes(); }; } } function AdminNavCloseClick(OffNode,OnNode,ContentNode,NodeID,EmptyNode) { document.getElementById(OffNode).style.display='none'; document.getElementById(OnNode).style.display='block'; document.getElementById(ContentNode).style.display='none'; cj.ajax.addon('AdminNavigatorCloseNode','nodeid='+NodeID); } /* * bind nodes */ function navBindNodes() { jQuery(".navDrag").each(function(){ jQuery(this).draggable({ stop: function(event, ui){ navDrop(this.id,ui.position.left,ui.position.top); } ,helper: "clone" ,revert: "invalid" ,zIndex: 0 ,hoverClass: "droppableHover" ,opacity: 0.50 ,cursor: "move" }); }); } /* * OnReady */ jQuery( document ).ready(function(){ /* * bind to icon nodes */ navBindNodes(); }); /* * open/close */ var AdminNavPop=false; /* * open nav when created closed */ function OpenAdminNav() { SetDisplay('AdminNavHeadOpened','block'); SetDisplay('AdminNavHeadClosed','none'); SetDisplay('AdminNavContentOpened','block'); SetDisplay('AdminNavContentMinWidth','block'); SetDisplay('AdminNavContentClosed','none'); cj.ajax.setVisitProperty('','AdminNavOpen','1'); navBindNodes(); if(!AdminNavPop){ cj.ajax.addonCallback("AdminNavigatorGetNode",'',OpenAdminNavCallback); AdminNavPop=true; }else{ cj.ajax.addon('AdminNavigatorOpenNode'); } } function OpenAdminNavCallback(serverResponse){ if (serverResponse != '') { var el1 = document.getElementById("AdminNavContentOpened"); if (el1) { el1.innerHTML = serverResponse SetDisplay('AdminNavContentOpened','block'); navBindNodes(); }; } } /* * close nav when created closed */ function reCloseAdminNav() { SetDisplay('AdminNavHeadOpened','none'); SetDisplay('AdminNavHeadClosed','block'); SetDisplay('AdminNavContentOpened','none'); SetDisplay('AdminNavContentMinWidth','none'); SetDisplay('AdminNavContentClosed','block'); cj.ajax.setVisitProperty('','AdminNavOpen','0') } /* * open nav when created open */ function closeAdminNav() { SetDisplay('AdminNavHeadOpened','none'); SetDisplay('AdminNavContentOpened','none'); SetDisplay('AdminNavHeadClosed','block'); SetDisplay('AdminNavContentClosed','block'); // var allowSaveState = true; // var $allowSaveStateInput=$('input[name=allowAdminNavSaveState'); // console.log('$allowSaveStateInput.length [' + $allowSaveStateInput.length + ']'); // if($allowSaveStateInput.length && $allowSaveStateInput.val()=='false') { // allowSaveState=false; // } // console.log('allowSaveState [' + allowSaveState + ']'); //if (allowSaveState) { cj.ajax.setVisitProperty('','AdminNavOpen','0'); //} } /* * close nav when created open */ function reOpenAdminNav() { SetDisplay('AdminNavHeadOpened','block'); SetDisplay('AdminNavContentOpened','block'); SetDisplay('AdminNavHeadClosed','none'); SetDisplay('AdminNavContentClosed','none'); navBindNodes(); cj.ajax.setVisitProperty('','AdminNavOpen','1') }
a749b8ae5b359e2412c7ce4e07f80eaa303f9308
[ "JavaScript" ]
1
JavaScript
contensive/aoAdminNavigator
f4586e950955493b51212261671131ca34c0e1d9
2173722a171b5d3084b3398b62a6d5d962aa4b97
refs/heads/trunk
<file_sep>/* eslint-env jest */ import { fromByteArray } from 'base64-js'; import fs from 'fs'; import yaml from 'js-yaml'; import JSBI from 'jsbi'; import { encode, decode } from '../src'; import { Codec, NeatTypes } from '../src/neat'; import { decodePointer } from '../src/neat/extensions'; import { createBaseType } from '../src/neat/typeCreators'; import { PlainObject } from '../types'; import { BaseType, Element } from '../types/neat'; const INT_64_CODE = 207; const UINT_64_CODE = 211; const msgpackCustomCodec = { encode: (inputs: unknown) => encode(inputs, { extensionCodec: Codec }), decode: (data: Uint8Array) => decode(data, { extensionCodec: Codec }), }; const msgpackCustomCodecJSBI = { encode: (inputs: unknown) => encode(inputs, { extensionCodec: Codec }), decode: (data: Uint8Array) => decode(data, { extensionCodec: Codec, useJSBI: true }), }; const msgpackJSBI = { encode: (inputs: unknown) => encode(inputs), decode: (data: Uint8Array) => decode(data, { useJSBI: true }), }; const PRIMITIVE_DEFAULTS: { [key: string]: { value: unknown; binaryValue: number[] }; } = { boolean: { value: new NeatTypes.Bool(false), binaryValue: [194], }, integer: { value: new NeatTypes.Int(0), binaryValue: [0], }, float32: { value: new NeatTypes.Float32(0), binaryValue: [202, 0, 0, 0, 0], }, float64: { value: new NeatTypes.Float64(0), binaryValue: [203, 0, 0, 0, 0, 0, 0, 0, 0], }, string: { value: new NeatTypes.Str(''), binaryValue: [196, 0], }, array: { value: [], binaryValue: [144], }, object: { value: {}, binaryValue: [128], }, }; interface YamlTest { name: string; out: number[]; bool: boolean; i8: number; i16: number; i32: number; i64: string; f32: number; f64: string; str: string; map: Record<string, unknown>; array: unknown[]; pointer: Element[]; complex: [Record<string, unknown>, unknown][]; bytes: number[]; wildcard: string; } function createComplexMap(complexArr: unknown[]) { const map = new Map(); for (let i = 0; i < complexArr.length; i += 2) { const keyType = createBaseType(complexArr[i]) as Map<unknown, BaseType>; keyType.forEach((v: BaseType, k: unknown) => { if (v instanceof NeatTypes.Int) { keyType.set(k, new NeatTypes.Float64(v.value)); } }); let valueType = createBaseType(complexArr[i + 1]); if (valueType instanceof NeatTypes.Int) { valueType = new NeatTypes.Float64(valueType.value); } map.set(keyType, valueType); } return map; } function createComplexKey(key: Record<string, unknown>): string { const mapArr: [unknown, unknown][] = []; Object.entries(key).forEach((entry) => { mapArr.push([ entry[0], typeof entry[1] !== 'string' ? new NeatTypes.Float64(entry[1]) : entry[1], ]); }); return fromByteArray(msgpackCustomCodec.encode(new Map(mapArr))); } function createExpectedComplexObject(complexArr: unknown[]) { const obj: PlainObject<unknown> = {}; for (let i = 0; i < complexArr.length; i += 2) { const key = complexArr[i] as Record<string, unknown>; obj[createComplexKey(key)] = { _key: key, _value: complexArr[i + 1], }; } return obj; } describe('NEAT codec', () => { const tests = yaml.load(fs.readFileSync(process.cwd() + '/test/codec_tests.yaml', 'utf8')); const arrayTests: YamlTest[] = []; const boolTests: YamlTest[] = []; const complexTests: YamlTest[] = []; const float32Tests: YamlTest[] = []; const float64Tests: YamlTest[] = []; const int16Tests: YamlTest[] = []; const int32Tests: YamlTest[] = []; const int64Tests: YamlTest[] = []; const int8Tests: YamlTest[] = []; const mapTests: YamlTest[] = []; const pointerTests: YamlTest[] = []; const stringTests: YamlTest[] = []; const nilTests: YamlTest[] = []; const bytesTests: YamlTest[] = []; const wildcardTests: YamlTest[] = []; if (typeof tests === 'object') { (tests as { tests: YamlTest[] }).tests.forEach((test: YamlTest) => { if (test.bool !== undefined) { boolTests.push(test); } else if (test.i8 !== undefined) { int8Tests.push(test); } else if (test.i16 !== undefined) { int16Tests.push(test); } else if (test.i32 !== undefined) { int32Tests.push(test); } else if (test.i64 !== undefined) { int64Tests.push(test); } else if (test.f32 !== undefined) { float32Tests.push(test); } else if (test.f64 !== undefined) { float64Tests.push(test); } else if (test.str !== undefined) { stringTests.push(test); } else if (test.map !== undefined) { mapTests.push(test); } else if (test.array !== undefined) { arrayTests.push(test); } else if (test.pointer !== undefined) { pointerTests.push(test); } else if (test.complex !== undefined) { complexTests.push(test); } else if (test.bytes !== undefined) { bytesTests.push(test); } else if (test.wildcard !== undefined) { wildcardTests.push(test); } else { nilTests.push(test); } }); } test('should properly encode/decode nil', () => { nilTests.forEach((test) => { expect(msgpackCustomCodec.encode(null)).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(null); expect(msgpackCustomCodec.encode(undefined)).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(null); }); }); test('should properly encode/decode bytes', () => { bytesTests.forEach((test) => { expect(msgpackCustomCodec.encode(new Uint8Array(test.bytes))).toEqual( new Uint8Array(test.out), ); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(''); }); }); test('should properly encode/decode bool', () => { boolTests.forEach((test) => { expect(msgpackCustomCodec.encode(test.bool)).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(test.bool); }); }); test('should properly encode/decode int8', () => { int8Tests.forEach((test) => { const int = new NeatTypes.Int(test.i8); // expect(msgpackCustomCodec.encode(test.i8)).toEqual(new Uint8Array(test.out)); // expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(test.i8); expect(msgpackCustomCodec.encode(int)).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(int.value); }); }); test('should properly encode/decode int16', () => { int16Tests.forEach((test) => { const int = new NeatTypes.Int(test.i16); expect(msgpackCustomCodec.encode(test.i16)).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(test.i16); expect(msgpackCustomCodec.encode(int)).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(int.value); }); }); test('should properly encode/decode int32', () => { int32Tests.forEach((test) => { const int = new NeatTypes.Int(test.i32); expect(msgpackCustomCodec.encode(test.i32)).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(test.i32); expect(msgpackCustomCodec.encode(int)).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(int.value); }); }); test('should properly encode/decode int64', () => { int64Tests.forEach((test) => { const int = new NeatTypes.Int(test.i64); expect(msgpackCustomCodec.encode(BigInt(test.i64))).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodec.encode(int)).toEqual(new Uint8Array(test.out)); if (test.out[0] !== INT_64_CODE && test.out[0] !== UINT_64_CODE) { expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(parseInt(test.i64, 10)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(int.value); } else { expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(BigInt(test.i64)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual( BigInt(int.value as unknown as string), ); const int64 = new NeatTypes.Int(BigInt(test.i64)); expect(msgpackCustomCodec.encode(int64)).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(int64.value); } }); }); test('should properly encode/decode int64 as JSBI', () => { int64Tests.forEach((test) => { const int = new NeatTypes.Int(test.i64, true); expect(msgpackCustomCodecJSBI.encode(JSBI.BigInt(test.i64))).toEqual( new Uint8Array(test.out), ); expect(msgpackCustomCodecJSBI.encode(int)).toEqual(new Uint8Array(test.out)); if (test.out[0] !== INT_64_CODE && test.out[0] !== UINT_64_CODE) { expect(msgpackCustomCodecJSBI.decode(new Uint8Array(test.out))).toEqual( parseInt(test.i64, 10), ); expect(msgpackCustomCodecJSBI.decode(new Uint8Array(test.out))).toEqual(int.value); // Without custom codec expect(msgpackJSBI.decode(new Uint8Array(test.out))).toEqual(parseInt(test.i64, 10)); } else { expect(msgpackCustomCodecJSBI.decode(new Uint8Array(test.out))).toEqual( JSBI.BigInt(test.i64), ); expect(msgpackCustomCodecJSBI.decode(new Uint8Array(test.out))).toEqual( JSBI.BigInt(int.value.toString()), ); const int64 = new NeatTypes.Int(JSBI.BigInt(test.i64)); expect(msgpackCustomCodecJSBI.encode(int64)).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodecJSBI.decode(new Uint8Array(test.out))).toEqual(int64.value); // Without custom codec expect(msgpackJSBI.decode(new Uint8Array(test.out))).toEqual(JSBI.BigInt(test.i64)); } }); }); test('should properly encode/decode string', () => { stringTests.forEach((test) => { expect(msgpackCustomCodec.encode(test.str)).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(test.str); }); }); test('should properly encode/decode array', () => { arrayTests.forEach((test) => { expect(msgpackCustomCodec.encode(test.array)).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(test.array); }); }); test('should properly encode/decode simple objects as maps', () => { mapTests.forEach((test) => { expect(msgpackCustomCodec.encode(test.map)).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(test.map); }); }); test('should properly encode/decode maps', () => { mapTests.forEach((test) => { const map = new Map(Object.entries(test.map)); expect(msgpackCustomCodec.encode(map)).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(test.map); }); }); test('should add proper header and length for map 32', () => { const map = new Map(); const obj: { [key: string]: string } = {}; const key = 'key'; const value = 'value'; for (let i = 0; i < 65537; i += 1) { map.set(key + i, value); obj[key + i] = value; } const encodedValue = msgpackCustomCodec.encode(map); expect(encodedValue[0]).toEqual(0xdf); expect(encodedValue.slice(1, 5)).toEqual(new Uint8Array([0, 1, 0, 1])); expect(msgpackCustomCodec.decode(encodedValue)).toEqual(obj); }); test('should properly encode/decode ext 32', () => { const resultPrefix = [201, 0, 1, 0, 3, 0, 145, 197, 255, 255]; const valueArray = new Array(65536); const decodedValue = new NeatTypes.Pointer(valueArray.join('a')); const binaryValue = new Array(65535); binaryValue.fill(97, 0, 65535); const encodedValue = new Uint8Array(resultPrefix.concat(binaryValue)); expect(msgpackCustomCodec.encode(decodedValue)).toEqual(encodedValue); expect(msgpackCustomCodec.decode(encodedValue)).toEqual(decodedValue); }); test('should properly encode/decode array 32', () => { const resultPrefix = [221, 0, 1, 0, 0]; const decodedValue = new Array(65536); decodedValue.fill(4, 0, 65536); const binaryValue = new Array(65536); binaryValue.fill(4, 0, 65536); const encodedValue = new Uint8Array(resultPrefix.concat(binaryValue)); expect(msgpackCustomCodec.encode(decodedValue)).toEqual(encodedValue); expect(msgpackCustomCodec.decode(encodedValue)).toEqual(decodedValue); }); test('should properly encode/decode str 32', () => { const resultPrefix = [198, 0, 1, 0, 0]; const valueArray = new Array(65537); const decodedValue = valueArray.join('a'); const binaryValue = new Array(65536); binaryValue.fill(97, 0, 65536); const encodedValue = new Uint8Array(resultPrefix.concat(binaryValue)); expect(msgpackCustomCodec.encode(decodedValue)).toEqual(encodedValue); expect(msgpackCustomCodec.decode(encodedValue)).toEqual(decodedValue); }); test('should properly encode/decode bin 16', () => { const resultPrefix = [197, 16, 0]; const valueArray = new Array(4097); const decodedValue = valueArray.join('a'); const binaryValue = new Array(4096); binaryValue.fill(97, 0, 4096); const encodedValue = new Uint8Array(resultPrefix.concat(binaryValue)); expect(msgpackCustomCodec.encode(new Uint8Array(binaryValue))).toEqual(encodedValue); expect(msgpackCustomCodec.decode(encodedValue)).toEqual(decodedValue); }); test('should properly encode/decode bin 32', () => { const resultPrefix = [198, 0, 1, 0, 0]; const valueArray = new Array(65537); const decodedValue = valueArray.join('a'); const binaryValue = new Array(65536); binaryValue.fill(97, 0, 65536); const encodedValue = new Uint8Array(resultPrefix.concat(binaryValue)); expect(msgpackCustomCodec.encode(new Uint8Array(binaryValue))).toEqual(encodedValue); expect(msgpackCustomCodec.decode(encodedValue)).toEqual(decodedValue); }); test('should properly encode/decode pointers', () => { pointerTests.forEach((test) => { // Empty pointer if (!test.pointer.length) { expect(msgpackCustomCodec.encode(new NeatTypes.Pointer())).toEqual( new Uint8Array(test.out), ); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual( new NeatTypes.Pointer(test.pointer), ); } expect(msgpackCustomCodec.encode(new NeatTypes.Pointer(test.pointer))).toEqual( new Uint8Array(test.out), ); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual( new NeatTypes.Pointer(test.pointer), ); }); }); test('should properly encode/decode wildcards', () => { wildcardTests.forEach((test) => { expect(msgpackCustomCodec.encode(new NeatTypes.Wildcard())).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(new NeatTypes.Wildcard()); }); }); test('should properly encode/decode maps with complex keys', () => { complexTests.forEach((test) => { expect(msgpackCustomCodec.encode(createComplexMap(test.complex))).toEqual( new Uint8Array(test.out), ); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual( createExpectedComplexObject(test.complex), ); }); }); test('should properly encode/decode a map value with non string keys', () => { const aMap = new Map([[{ c: 'd' }, 'e']]); const bMap = new Map([[{ d: 'd' }, 'e']]); const testInput = new Map<string, unknown>([ ['a', aMap], ['b', bMap], ]); const expectedDecodedValue = { a: { 'gcQBY8QBZA==': { _key: { c: 'd' }, _value: 'e' } }, b: { 'gcQBZMQBZA==': { _key: { d: 'd' }, _value: 'e' } }, }; const testOutput = [ 130, 196, 1, 97, 129, 129, 196, 1, 99, 196, 1, 100, 196, 1, 101, 196, 1, 98, 129, 129, 196, 1, 100, 196, 1, 100, 196, 1, 101, ]; expect(msgpackCustomCodec.encode(testInput)).toEqual(new Uint8Array(testOutput)); expect(msgpackCustomCodec.decode(new Uint8Array(testOutput))).toEqual(expectedDecodedValue); }); test('should properly encode/decode map with complex key and undefined object value', () => { const testInput = [{ a: 'b', c: 'd' }, Object.create(null)]; const testDecodedInput = [{ a: 'b', c: 'd' }, null]; const testOutput = [129, 130, 196, 1, 97, 196, 1, 98, 196, 1, 99, 196, 1, 100, 192]; expect(msgpackCustomCodec.encode(createComplexMap(testInput))).toEqual( new Uint8Array(testOutput), ); expect(msgpackCustomCodec.decode(new Uint8Array(testOutput))).toEqual( createExpectedComplexObject(testDecodedInput), ); }); test('should properly encode/decode float32', () => { float32Tests.forEach((test) => { const float = new NeatTypes.Float32(test.f32); expect(msgpackCustomCodec.encode(float)).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(Math.fround(test.f32)); }); }); test('should properly encode/decode float64', () => { float64Tests.forEach((test) => { const float = new NeatTypes.Float64(test.f64); expect(msgpackCustomCodec.encode(float)).toEqual(new Uint8Array(test.out)); expect(msgpackCustomCodec.decode(new Uint8Array(test.out))).toEqual(parseFloat(test.f64)); }); }); test('should properly encode/decode functions', () => { const randomClass = class RandomNonExistantType {}; const randomFunction = () => null; const nullByte = [0xc0]; expect(msgpackCustomCodec.encode(randomClass)).toEqual(new Uint8Array(nullByte)); expect(msgpackCustomCodec.encode(randomFunction)).toEqual(new Uint8Array(nullByte)); }); test('should fallback to an empty pointer, if pointer is not decoded as an array', () => { expect(decodePointer(Codec)(new Uint8Array([212, 0, 0]))).toEqual(new NeatTypes.Pointer()); }); describe('Encode primitive default values', () => { const type = Object.keys(PRIMITIVE_DEFAULTS); type.forEach((primitiveType) => { test(`should properly encode ${primitiveType}`, () => { const primitive = PRIMITIVE_DEFAULTS[primitiveType]; expect(msgpackCustomCodec.encode(primitive.value)).toEqual( new Uint8Array(primitive.binaryValue), ); }); }); }); }); <file_sep>// A setup script to load a mock websocket for tests import { WebSocket } from 'mock-socket'; import util from 'util'; // TextDecoder implementation that matches the lib dom API class TextDE { private decoder = new util.TextDecoder(); public readonly encoding = 'utf-8'; public readonly fatal = false; public readonly ignoreBOM = true; public decode(input?: Uint8Array): string { return this.decoder.decode(input); } } global.WebSocket = WebSocket; global.TextDecoder = TextDE; global.TextEncoder = util.TextEncoder; const swallowError = (): void => undefined; /* eslint-disable no-console */ console.error = swallowError; console.warn = swallowError; /* eslint-enable no-console */ <file_sep>// Copyright (c) 2018, Arista Networks, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. /* eslint-disable max-classes-per-file */ import JSBI from 'jsbi'; import { Element, PathElements } from '../../types/neat'; import { isJsbi } from '../utils/data'; export class Float32 { public static type: 'float32' = 'float32'; public type: 'float32'; public value: number; /** * A class to represent an explicit float32 */ public constructor(value: unknown) { this.type = Float32.type; this.value = value ? parseFloat(String(value)) : 0.0; // undefined defaults to 0.0 } public toString(): string { const strValue = this.value.toString(); const hasDecimal = strValue.includes('.'); return hasDecimal ? strValue : this.value.toFixed(1); } } export class Float64 { public static type: 'float64' = 'float64'; public type: 'float64'; public value: number; /** * A class to represent an explicit float64 */ public constructor(value: unknown) { this.type = Float64.type; this.value = value ? parseFloat(String(value)) : 0.0; // undefined defaults to 0.0 } public toString(): string { const strValue = this.value.toString(); const hasDecimal = strValue.includes('.'); return hasDecimal ? strValue : this.value.toFixed(1); } } export class Int { public static type: 'int' = 'int'; public type: 'int'; public value: number | bigint | JSBI; /** * A class to represent an explicit int */ public constructor(value: unknown, forceJSBI = false) { this.type = Int.type; if (typeof value === 'string') { let BI; // This is a type alias for JSBI/BigInt if (typeof BigInt === 'undefined' || forceJSBI) { BI = JSBI.BigInt; } else { BI = BigInt; } this.value = parseInt(value, 10) > 0xffffffff || parseInt(value, 10) < -0x80000000 ? BI(value) // eslint-disable-line new-cap : parseInt(value, 10); } else if (typeof value === 'bigint' || isJsbi(value)) { this.value = value as bigint | JSBI; } else { this.value = parseInt(String(value), 10); } } public toString(): string { return this.value.toString(); } } export class Bool { public static type: 'bool' = 'bool'; public type: 'bool'; public value: boolean; /** * A class to represent an explicit boolean */ public constructor(value: unknown) { this.type = Bool.type; this.value = !!value; } public toString(): string { return this.value ? 'true' : 'false'; } } export class Nil { public static type: 'nil' = 'nil'; public type: 'nil'; public value: null; /** * A class to represent an explicit Nil */ public constructor() { this.type = Nil.type; this.value = null; } public toString(): string { return 'null'; } } export class Str { public static type: 'str' = 'str'; public type: 'str'; public value: string; /** * A class to represent an explicit String */ public constructor(value: unknown) { this.type = Str.type; switch (typeof value) { case 'string': this.value = value; break; case 'bigint': this.value = value.toString(); break; case 'undefined': this.value = ''; break; default: this.value = JSON.stringify(value); } if (isJsbi(value)) { this.value = (value as JSBI).toString(); } } public toString(): string { return this.value; } } export class Pointer { public static type: 'ptr' = 'ptr'; public value: PathElements; public type: 'ptr'; public delimiter: string; /** * A class to represent a Pointer type. * A Pointer is a pointer from one set of path elements to another. */ public constructor(value: PathElements | string | unknown = []) { this.delimiter = '/'; this.type = Pointer.type; let strValue: string; if (!Array.isArray(value)) { if (typeof value !== 'string') { strValue = JSON.stringify(value); } else { strValue = value; } const ptrArray: string[] = strValue.split(this.delimiter); while (ptrArray[0] === '') { ptrArray.shift(); } this.value = ptrArray.map((pathEl): Element => { try { return JSON.parse(pathEl); } catch (e) { // ignore errors, these are just regular strings } return pathEl; }); } else { this.value = value; } } public toString(): string { return this.value .map((pathEl): string => { if (typeof pathEl === 'string') { return pathEl; } return JSON.stringify(pathEl); }) .join(this.delimiter); } } export class Wildcard { public static type: '*' = '*'; public value: null; public type: '*'; /** * A class to represent a Wildcard type. * A Wildcard is a type that matches 1 or more path elements */ public constructor() { this.type = Wildcard.type; this.value = null; } public toString(): string { return '*'; } } <file_sep># CloudVision CloudVision is a network management framework supporting workload orchestration, workflow automation and telemetry. ## CloudVision Database The CloudVision Database is a large-scale distributed database for generic, semi-structured state sharing and archival. The database is a core component of CloudVision but may also be used as a platform to write versatile client applications. > Note: The CloudVision Database is undergoing rapid development and the APIs are subject > to change. <file_sep>import type { GrpcControlMessage, StreamingResourceResponse } from '@types'; import { grpc } from '@arista/grpc-web'; import { INITIAL_SYNC_COMPLETE_MESSAGE } from './constants'; export function isInitialSyncCompleteMessage(message: GrpcControlMessage): boolean { return ( 'error' in message && message.error.code === INITIAL_SYNC_COMPLETE_MESSAGE.error.code && message.error.message === INITIAL_SYNC_COMPLETE_MESSAGE.error.message ); } export function isStreamResponse( response: grpc.ProtobufMessage, ): response is StreamingResourceResponse { return 'type' in response; } <file_sep>/* eslint-disable @typescript-eslint/ban-ts-comment */ // @ts-nocheck /* eslint-disable */ import Long from 'long'; import _m0 from '@arista/protobufjs/minimal'; import { Syntax, Option, syntaxFromJSON, syntaxToJSON } from '../../google/protobuf/type'; import { SourceContext } from '../../google/protobuf/source_context'; export const protobufPackage = 'google.protobuf'; /** * Api is a light-weight descriptor for an API Interface. * * Interfaces are also described as "protocol buffer services" in some contexts, * such as by the "service" keyword in a .proto file, but they are different * from API Services, which represent a concrete implementation of an interface * as opposed to simply a description of methods and bindings. They are also * sometimes simply referred to as "APIs" in other contexts, such as the name of * this message itself. See https://cloud.google.com/apis/design/glossary for * detailed terminology. */ export interface Api { /** * The fully qualified name of this interface, including package name * followed by the interface's simple name. */ name: string; /** The methods of this interface, in unspecified order. */ methods: Method[]; /** Any metadata attached to the interface. */ options: Option[]; /** * A version string for this interface. If specified, must have the form * `major-version.minor-version`, as in `1.10`. If the minor version is * omitted, it defaults to zero. If the entire version field is empty, the * major version is derived from the package name, as outlined below. If the * field is not empty, the version in the package name will be verified to be * consistent with what is provided here. * * The versioning schema uses [semantic * versioning](http://semver.org) where the major version number * indicates a breaking change and the minor version an additive, * non-breaking change. Both version numbers are signals to users * what to expect from different versions, and should be carefully * chosen based on the product plan. * * The major version is also reflected in the package name of the * interface, which must end in `v<major-version>`, as in * `google.feature.v1`. For major versions 0 and 1, the suffix can * be omitted. Zero major versions must only be used for * experimental, non-GA interfaces. */ version: string; /** * Source context for the protocol buffer service represented by this * message. */ sourceContext: SourceContext | undefined; /** Included interfaces. See [Mixin][]. */ mixins: Mixin[]; /** The source syntax of the service. */ syntax: Syntax; } /** Method represents a method of an API interface. */ export interface Method { /** The simple name of this method. */ name: string; /** A URL of the input message type. */ requestTypeUrl: string; /** If true, the request is streamed. */ requestStreaming: boolean; /** The URL of the output message type. */ responseTypeUrl: string; /** If true, the response is streamed. */ responseStreaming: boolean; /** Any metadata attached to the method. */ options: Option[]; /** The source syntax of this method. */ syntax: Syntax; } /** * Declares an API Interface to be included in this interface. The including * interface must redeclare all the methods from the included interface, but * documentation and options are inherited as follows: * * - If after comment and whitespace stripping, the documentation * string of the redeclared method is empty, it will be inherited * from the original method. * * - Each annotation belonging to the service config (http, * visibility) which is not set in the redeclared method will be * inherited. * * - If an http annotation is inherited, the path pattern will be * modified as follows. Any version prefix will be replaced by the * version of the including interface plus the [root][] path if * specified. * * Example of a simple mixin: * * package google.acl.v1; * service AccessControl { * // Get the underlying ACL object. * rpc GetAcl(GetAclRequest) returns (Acl) { * option (google.api.http).get = "/v1/{resource=**}:getAcl"; * } * } * * package google.storage.v2; * service Storage { * rpc GetAcl(GetAclRequest) returns (Acl); * * // Get a data record. * rpc GetData(GetDataRequest) returns (Data) { * option (google.api.http).get = "/v2/{resource=**}"; * } * } * * Example of a mixin configuration: * * apis: * - name: google.storage.v2.Storage * mixins: * - name: google.acl.v1.AccessControl * * The mixin construct implies that all methods in `AccessControl` are * also declared with same name and request/response types in * `Storage`. A documentation generator or annotation processor will * see the effective `Storage.GetAcl` method after inheriting * documentation and annotations as follows: * * service Storage { * // Get the underlying ACL object. * rpc GetAcl(GetAclRequest) returns (Acl) { * option (google.api.http).get = "/v2/{resource=**}:getAcl"; * } * ... * } * * Note how the version in the path pattern changed from `v1` to `v2`. * * If the `root` field in the mixin is specified, it should be a * relative path under which inherited HTTP paths are placed. Example: * * apis: * - name: google.storage.v2.Storage * mixins: * - name: google.acl.v1.AccessControl * root: acls * * This implies the following inherited HTTP annotation: * * service Storage { * // Get the underlying ACL object. * rpc GetAcl(GetAclRequest) returns (Acl) { * option (google.api.http).get = "/v2/acls/{resource=**}:getAcl"; * } * ... * } */ export interface Mixin { /** The fully qualified name of the interface which is included. */ name: string; /** * If non-empty specifies a path under which inherited HTTP paths * are rooted. */ root: string; } const baseApi: object = { name: '', version: '', syntax: 0 }; export const Api = { encode(message: Api, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { if (message.name !== '') { writer.uint32(10).string(message.name); } for (const v of message.methods) { Method.encode(v!, writer.uint32(18).fork()).ldelim(); } for (const v of message.options) { Option.encode(v!, writer.uint32(26).fork()).ldelim(); } if (message.version !== '') { writer.uint32(34).string(message.version); } if (message.sourceContext !== undefined) { SourceContext.encode(message.sourceContext, writer.uint32(42).fork()).ldelim(); } for (const v of message.mixins) { Mixin.encode(v!, writer.uint32(50).fork()).ldelim(); } if (message.syntax !== 0) { writer.uint32(56).int32(message.syntax); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Api { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseApi } as Api; message.methods = []; message.options = []; message.mixins = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.name = reader.string(); break; case 2: message.methods.push(Method.decode(reader, reader.uint32())); break; case 3: message.options.push(Option.decode(reader, reader.uint32())); break; case 4: message.version = reader.string(); break; case 5: message.sourceContext = SourceContext.decode(reader, reader.uint32()); break; case 6: message.mixins.push(Mixin.decode(reader, reader.uint32())); break; case 7: message.syntax = reader.int32() as any; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Api { const message = { ...baseApi } as Api; message.methods = []; message.options = []; message.mixins = []; if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } else { message.name = ''; } if (object.methods !== undefined && object.methods !== null) { for (const e of object.methods) { message.methods.push(Method.fromJSON(e)); } } if (object.options !== undefined && object.options !== null) { for (const e of object.options) { message.options.push(Option.fromJSON(e)); } } if (object.version !== undefined && object.version !== null) { message.version = String(object.version); } else { message.version = ''; } if (object.sourceContext !== undefined && object.sourceContext !== null) { message.sourceContext = SourceContext.fromJSON(object.sourceContext); } else { message.sourceContext = undefined; } if (object.mixins !== undefined && object.mixins !== null) { for (const e of object.mixins) { message.mixins.push(Mixin.fromJSON(e)); } } if (object.syntax !== undefined && object.syntax !== null) { message.syntax = syntaxFromJSON(object.syntax); } else { message.syntax = 0; } return message; }, toJSON(message: Api): unknown { const obj: any = {}; message.name !== undefined && (obj.name = message.name); if (message.methods) { obj.methods = message.methods.map((e) => (e ? Method.toJSON(e) : undefined)); } else { obj.methods = []; } if (message.options) { obj.options = message.options.map((e) => (e ? Option.toJSON(e) : undefined)); } else { obj.options = []; } message.version !== undefined && (obj.version = message.version); message.sourceContext !== undefined && (obj.sourceContext = message.sourceContext ? SourceContext.toJSON(message.sourceContext) : undefined); if (message.mixins) { obj.mixins = message.mixins.map((e) => (e ? Mixin.toJSON(e) : undefined)); } else { obj.mixins = []; } message.syntax !== undefined && (obj.syntax = syntaxToJSON(message.syntax)); return obj; }, fromPartial(object: DeepPartial<Api>): Api { const message = { ...baseApi } as Api; message.methods = []; message.options = []; message.mixins = []; if (object.name !== undefined && object.name !== null) { message.name = object.name; } else { message.name = ''; } if (object.methods !== undefined && object.methods !== null) { for (const e of object.methods) { message.methods.push(Method.fromPartial(e)); } } if (object.options !== undefined && object.options !== null) { for (const e of object.options) { message.options.push(Option.fromPartial(e)); } } if (object.version !== undefined && object.version !== null) { message.version = object.version; } else { message.version = ''; } if (object.sourceContext !== undefined && object.sourceContext !== null) { message.sourceContext = SourceContext.fromPartial(object.sourceContext); } else { message.sourceContext = undefined; } if (object.mixins !== undefined && object.mixins !== null) { for (const e of object.mixins) { message.mixins.push(Mixin.fromPartial(e)); } } if (object.syntax !== undefined && object.syntax !== null) { message.syntax = object.syntax; } else { message.syntax = 0; } return message; }, }; const baseMethod: object = { name: '', requestTypeUrl: '', requestStreaming: false, responseTypeUrl: '', responseStreaming: false, syntax: 0, }; export const Method = { encode(message: Method, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { if (message.name !== '') { writer.uint32(10).string(message.name); } if (message.requestTypeUrl !== '') { writer.uint32(18).string(message.requestTypeUrl); } if (message.requestStreaming === true) { writer.uint32(24).bool(message.requestStreaming); } if (message.responseTypeUrl !== '') { writer.uint32(34).string(message.responseTypeUrl); } if (message.responseStreaming === true) { writer.uint32(40).bool(message.responseStreaming); } for (const v of message.options) { Option.encode(v!, writer.uint32(50).fork()).ldelim(); } if (message.syntax !== 0) { writer.uint32(56).int32(message.syntax); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Method { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMethod } as Method; message.options = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.name = reader.string(); break; case 2: message.requestTypeUrl = reader.string(); break; case 3: message.requestStreaming = reader.bool(); break; case 4: message.responseTypeUrl = reader.string(); break; case 5: message.responseStreaming = reader.bool(); break; case 6: message.options.push(Option.decode(reader, reader.uint32())); break; case 7: message.syntax = reader.int32() as any; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Method { const message = { ...baseMethod } as Method; message.options = []; if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } else { message.name = ''; } if (object.requestTypeUrl !== undefined && object.requestTypeUrl !== null) { message.requestTypeUrl = String(object.requestTypeUrl); } else { message.requestTypeUrl = ''; } if (object.requestStreaming !== undefined && object.requestStreaming !== null) { message.requestStreaming = Boolean(object.requestStreaming); } else { message.requestStreaming = false; } if (object.responseTypeUrl !== undefined && object.responseTypeUrl !== null) { message.responseTypeUrl = String(object.responseTypeUrl); } else { message.responseTypeUrl = ''; } if (object.responseStreaming !== undefined && object.responseStreaming !== null) { message.responseStreaming = Boolean(object.responseStreaming); } else { message.responseStreaming = false; } if (object.options !== undefined && object.options !== null) { for (const e of object.options) { message.options.push(Option.fromJSON(e)); } } if (object.syntax !== undefined && object.syntax !== null) { message.syntax = syntaxFromJSON(object.syntax); } else { message.syntax = 0; } return message; }, toJSON(message: Method): unknown { const obj: any = {}; message.name !== undefined && (obj.name = message.name); message.requestTypeUrl !== undefined && (obj.requestTypeUrl = message.requestTypeUrl); message.requestStreaming !== undefined && (obj.requestStreaming = message.requestStreaming); message.responseTypeUrl !== undefined && (obj.responseTypeUrl = message.responseTypeUrl); message.responseStreaming !== undefined && (obj.responseStreaming = message.responseStreaming); if (message.options) { obj.options = message.options.map((e) => (e ? Option.toJSON(e) : undefined)); } else { obj.options = []; } message.syntax !== undefined && (obj.syntax = syntaxToJSON(message.syntax)); return obj; }, fromPartial(object: DeepPartial<Method>): Method { const message = { ...baseMethod } as Method; message.options = []; if (object.name !== undefined && object.name !== null) { message.name = object.name; } else { message.name = ''; } if (object.requestTypeUrl !== undefined && object.requestTypeUrl !== null) { message.requestTypeUrl = object.requestTypeUrl; } else { message.requestTypeUrl = ''; } if (object.requestStreaming !== undefined && object.requestStreaming !== null) { message.requestStreaming = object.requestStreaming; } else { message.requestStreaming = false; } if (object.responseTypeUrl !== undefined && object.responseTypeUrl !== null) { message.responseTypeUrl = object.responseTypeUrl; } else { message.responseTypeUrl = ''; } if (object.responseStreaming !== undefined && object.responseStreaming !== null) { message.responseStreaming = object.responseStreaming; } else { message.responseStreaming = false; } if (object.options !== undefined && object.options !== null) { for (const e of object.options) { message.options.push(Option.fromPartial(e)); } } if (object.syntax !== undefined && object.syntax !== null) { message.syntax = object.syntax; } else { message.syntax = 0; } return message; }, }; const baseMixin: object = { name: '', root: '' }; export const Mixin = { encode(message: Mixin, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { if (message.name !== '') { writer.uint32(10).string(message.name); } if (message.root !== '') { writer.uint32(18).string(message.root); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Mixin { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMixin } as Mixin; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.name = reader.string(); break; case 2: message.root = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Mixin { const message = { ...baseMixin } as Mixin; if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } else { message.name = ''; } if (object.root !== undefined && object.root !== null) { message.root = String(object.root); } else { message.root = ''; } return message; }, toJSON(message: Mixin): unknown { const obj: any = {}; message.name !== undefined && (obj.name = message.name); message.root !== undefined && (obj.root = message.root); return obj; }, fromPartial(object: DeepPartial<Mixin>): Mixin { const message = { ...baseMixin } as Mixin; if (object.name !== undefined && object.name !== null) { message.name = object.name; } else { message.name = ''; } if (object.root !== undefined && object.root !== null) { message.root = object.root; } else { message.root = ''; } return message; }, }; type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined; export type DeepPartial<T> = T extends Builtin ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> } : Partial<T>; if (_m0.util.Long !== Long) { _m0.util.Long = Long as any; _m0.configure(); } <file_sep>/* eslint-env jest */ import { ensureUint8Array, createDataView } from '../../src/utils/typedArrays'; describe.each([ [ensureUint8Array, [1, 2], Uint8Array], [ensureUint8Array, new Uint8Array(2), Uint8Array], [ensureUint8Array, new ArrayBuffer(2), Uint8Array], [ensureUint8Array, new Int8Array(), Uint8Array], [createDataView, new ArrayBuffer(2), DataView], [createDataView, new Int8Array(), DataView], ])('typedArrays', (fn, input, type) => { test(`should return the type ${type.name} for ${fn.name}`, () => { // @ts-expect-error Easier than typing everything expect(fn.call(undefined, input)).toBeInstanceOf(type); }); }); <file_sep>/* eslint-env jest */ import { CachedKeyDecoder } from '../src/CachedKeyDecoder'; import { utf8EncodeJs, utf8Count } from '../src/utils/utf8'; function tryDecode(decoder: CachedKeyDecoder, str: string): string { const byteLength = utf8Count(str); const bytes = new Uint8Array(byteLength); utf8EncodeJs(str, bytes, 0); if (!decoder.canBeCached(byteLength)) { throw new Error('Unexpected precondition'); } return decoder.decode(bytes, 0, byteLength); } describe('CachedKeyDecoder', () => { describe('basic behavior', () => { test('decodes a string', () => { const decoder = new CachedKeyDecoder(); expect(tryDecode(decoder, 'foo')).toEqual('foo'); expect(tryDecode(decoder, 'foo')).toEqual('foo'); expect(tryDecode(decoder, 'foo')).toEqual('foo'); }); test('decodes strings', () => { const decoder = new CachedKeyDecoder(); expect(tryDecode(decoder, 'foo')).toEqual('foo'); expect(tryDecode(decoder, 'bar')).toEqual('bar'); expect(tryDecode(decoder, 'foo')).toEqual('foo'); }); test('decodes strings with purging records', () => { const decoder = new CachedKeyDecoder(16, 4); for (let i = 0; i < 100; i++) { expect(tryDecode(decoder, 'foo1')).toEqual('foo1'); expect(tryDecode(decoder, 'foo2')).toEqual('foo2'); expect(tryDecode(decoder, 'foo3')).toEqual('foo3'); expect(tryDecode(decoder, 'foo4')).toEqual('foo4'); expect(tryDecode(decoder, 'foo5')).toEqual('foo5'); } }); }); describe('edge cases', () => { // len=0 is not supported because it is just an empty string test('decodes str with len=1', () => { const decoder = new CachedKeyDecoder(); expect(tryDecode(decoder, 'f')).toEqual('f'); expect(tryDecode(decoder, 'a')).toEqual('a'); expect(tryDecode(decoder, 'f')).toEqual('f'); expect(tryDecode(decoder, 'a')).toEqual('a'); }); test('decodes str with len=maxKeyLength', () => { const decoder = new CachedKeyDecoder(1); expect(tryDecode(decoder, 'f')).toEqual('f'); expect(tryDecode(decoder, 'a')).toEqual('a'); expect(tryDecode(decoder, 'f')).toEqual('f'); expect(tryDecode(decoder, 'a')).toEqual('a'); }); }); }); <file_sep>{ "extends": "../../tsconfig.json", "compilerOptions": { "target": "ES6" }, "typedocOptions": { "cleanOutputDir": true, "entryPoints": ["src/index.ts"], "exclude": "test/**", "excludeExternals": true, "excludePrivate": true, "hideGenerator": true, "out": "docs", "readme": "./README.md" } } <file_sep>/* eslint-env jest */ import { encode, decode, ExtensionCodec } from '../src'; describe('ExtensionCodec', () => { describe('custom extensions', () => { const extensionCodec = new ExtensionCodec(); // Set<T> extensionCodec.register({ type: 0, identifier: (data) => data instanceof Set, encode: (object: Set<unknown>): Uint8Array => { return encode([...object]); }, decode: (data: Uint8Array) => { const array = decode(data) as unknown[]; return new Set(array); }, }); // DateTime extensionCodec.register({ type: 1, identifier: (data) => data instanceof Date, encode: (object: Date): Uint8Array => { return encode(object.getTime()); }, decode: (data: Uint8Array) => { const d = decode(data); return new Date(Number(d)); }, }); test('encodes and decodes custom data types (synchronously)', () => { const set = new Set([1, 2, 3]); const date = new Date(); const encoded = encode([set, date], { extensionCodec }); expect(decode(encoded, { extensionCodec })).toEqual([set, date]); }); }); }); <file_sep># Change Log All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. ## [0.0.19](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.0.19) (2020-04-06) **Note:** Version bump only for package benchmark-msgpack ## [0.0.18](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.0.18) (2020-03-30) **Note:** Version bump only for package benchmark-msgpack ## [0.0.17](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.0.17) (2020-03-23) **Note:** Version bump only for package benchmark-msgpack ## [0.0.16](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.0.16) (2020-03-20) **Note:** Version bump only for package benchmark-msgpack ## [0.0.15](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.0.15) (2020-03-20) **Note:** Version bump only for package benchmark-msgpack ## [0.0.14](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.0.14) (2020-03-19) **Note:** Version bump only for package benchmark-msgpack ## [0.0.13](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.0.13) (2020-03-16) **Note:** Version bump only for package benchmark-msgpack ## [0.0.12](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.0.12) (2020-03-09) **Note:** Version bump only for package benchmark-msgpack ## [0.0.11](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.0.11) (2020-03-04) **Note:** Version bump only for package benchmark-msgpack ## [0.0.10](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.0.10) (2020-02-26) **Note:** Version bump only for package benchmark-msgpack ## [0.0.9](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.0.9) (2020-02-25) **Note:** Version bump only for package benchmark-msgpack ## [0.0.8](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.0.8) (2020-02-24) **Note:** Version bump only for package benchmark-msgpack ## [0.0.7](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.0.7) (2020-02-17) **Note:** Version bump only for package benchmark-msgpack ## [0.0.6](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.0.6) (2020-02-10) **Note:** Version bump only for package benchmark-msgpack ## [0.0.5](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.0.5) (2020-02-03) **Note:** Version bump only for package benchmark-msgpack ## [0.0.4](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.0.4) (2020-01-27) **Note:** Version bump only for package benchmark-msgpack ## [0.0.3](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.0.3) (2020-01-22) **Note:** Version bump only for package benchmark-msgpack ## 0.0.2 (2020-01-22) ### Bug Fixes * **a-msgpack,cloudvision-connector:** improve perf ([3b6992d](http://gerrit.corp.arista.io:29418/web-components/commits/3b6992d783463f8f4f000c3334ceb0693e793083)) <file_sep>import { Encoder } from './Encoder'; import { ExtensionCodecType } from './ExtensionCodec'; export interface EncodeOptions { /** * The extension codec to use. * Default is none */ extensionCodec?: ExtensionCodecType; /** * The maximum object depth * Default 100 */ maxDepth?: number; /** * The size of the buffer when beginning encoding. * This is the minimum amount of memory allocated. * Default 2048 */ initialBufferSize?: number; } const defaultEncodeOptions = {}; /** * It encodes `value` in the MessagePack format and * returns a byte buffer. * * The returned buffer is a slice of a larger `ArrayBuffer`, so you have to use its `#byteOffset` * and `#byteLength` in order to convert it to another typed arrays including NodeJS `Buffer`. */ export function encode(value: unknown, options: EncodeOptions = defaultEncodeOptions): Uint8Array { const encoder = new Encoder(options.extensionCodec, options.maxDepth, options.initialBufferSize); encoder.encode(value, 1); return encoder.getUint8Array(); } <file_sep>/* eslint-env jest */ import { encode, decode } from '../src'; describe('edge cases', () => { describe('try to encode cyclic refs', () => { test('throws errors on arrays', () => { const cyclicRefs: unknown[] = []; cyclicRefs.push(cyclicRefs); expect(() => { encode(cyclicRefs); }).toThrow(/too deep/i); }); test('throws errors on objects', () => { const cyclicRefs: Record<string, unknown> = {}; cyclicRefs.foo = cyclicRefs; expect(() => { encode(cyclicRefs); }).toThrow(/too deep/i); }); }); describe('try to encode non-encodable objects', () => { test('throws errors', () => { expect(() => { encode(Symbol('Astros are cheaters')); }).toThrow(/unrecognized object/i); }); }); describe('try to decode invlid MessagePack binary', () => { test('throws errors', () => { const TYPE_NEVER_USED = 0xc1; expect(() => { decode([TYPE_NEVER_USED]); }).toThrow(/unrecognized type byte/i); }); }); describe('try to decode insufficient data', () => { test('throws errors (synchronous)', () => { expect(() => { decode([196, 3, 115, 116]); }).toThrow(/Insufficient data/i); }); test('throws errors for extentions (synchronous)', () => { expect(() => { decode([213, 0, 145]); }).toThrow(/Insufficient data/i); }); }); describe('try to decode data with extra bytes', () => { test('throws errors (synchronous)', () => { expect(() => { decode([ 0x90, // fixarray size=0 ...encode(null), ]); }).toThrow(RangeError); }); }); describe('MAX_SAFE_INTEGER as float64', () => { const input = 9007199254740992; const out = new Uint8Array([203, 67, 64, 0, 0, 0, 0, 0, 0]); test('encode', () => { expect(encode(input)).toEqual(out); }); test('decode', () => { expect(decode(out)).toEqual(input); }); }); test('decode without cachedKeyDecoder', () => { const input = { a: 'b', c: 'd' }; const out = new Uint8Array([130, 196, 1, 97, 196, 1, 98, 196, 1, 99, 196, 1, 100]); expect( decode(out, { cachedKeyDecoder: null, }), ).toEqual(input); }); }); <file_sep>import { PathElements, Timestamp } from 'a-msgpack'; import { RequestContext } from './connection'; import { DatasetObject } from './params'; export interface CloudVisionMetaData<V> { [key: string]: V; } export interface CloudVisionDatasets { metadata: CloudVisionMetaData<unknown>; datasets: DatasetObject[]; } export interface CloudVisionStatus { code?: number; message?: string; } export interface CloudVisionDatapoint<K, V> { key: K; value: V; } export interface CloudVisionNotification<PE, T, U, D> { timestamp: T; nanos?: T; delete_all?: boolean; // eslint-disable-line @typescript-eslint/naming-convention deletes?: D; path_elements?: PE; // eslint-disable-line @typescript-eslint/naming-convention updates?: U; } export interface CloudVisionUpdates<K, V> { [key: string]: CloudVisionDatapoint<K, V>; } /** @deprecated: Use `CloudVisionUpdates`. */ export type CloudVisionUpdate<K, V> = CloudVisionUpdates<K, V>; export interface CloudVisionDeletes<K> { [key: string]: { key: K }; } /** @deprecated: Use `CloudVisionDeletes`. */ export type CloudVisionDelete<K> = CloudVisionDeletes<K>; export type ConvertedNotification<K = unknown, V = unknown> = CloudVisionNotification< PathElements, number, CloudVisionUpdates<K, V>, CloudVisionDeletes<K> >; export type NewConvertedNotification<K = unknown, V = unknown> = CloudVisionNotification< PathElements, Timestamp, CloudVisionDatapoint<K, V>[], K[] >; export type RawNotification = CloudVisionNotification< string[], Timestamp, CloudVisionDatapoint<string, string>[], string[] >; export interface CloudVisionNotifs { dataset: DatasetObject; metadata: CloudVisionMetaData<unknown>; notifications: ConvertedNotification[]; } export interface CloudVisionRawNotifs { dataset: DatasetObject; metadata?: CloudVisionMetaData<unknown>; notifications: RawNotification[]; } export interface CloudVisionBatchedNotifications { dataset: DatasetObject; metadata: CloudVisionMetaData<unknown>; notifications: { [path: string]: ConvertedNotification[]; }; } export interface CloudVisionServiceResult { [key: string]: unknown; } /** * This can either be the update returned as query result, or update to write * to the CloudVision API server. */ export type CloudVisionResult = CloudVisionNotifs | CloudVisionDatasets; export type CloudVisionBatchedResult = CloudVisionBatchedNotifications | CloudVisionDatasets; export interface CloudVisionMessage { result: CloudVisionBatchedResult | CloudVisionResult | CloudVisionServiceResult; status: CloudVisionStatus; token: string; error?: string; } /** * A function that gets called when a notification associated with the [[Query]] is * received. * * @param error `null` if there is no error. If there is an error this will be the message * @param result if there is a result in the notification this will be defined * @param status if there is a status in the notification this will be defined * @param token the token associated with the notification. If not defined, then there is * no notification associated with the call. */ export interface NotifCallback { ( err: string | null, result?: CloudVisionBatchedResult | CloudVisionResult | CloudVisionServiceResult, status?: CloudVisionStatus, token?: string, requestContext?: RequestContext, ): void; } <file_sep>import { PathElements } from 'a-msgpack'; import { DEVICE_DATASET_TYPE } from '../src/constants'; import { ConvertedNotification, PublishNotification, Query, RawNotification } from '../types'; export const path1: PathElements = ['some', 'other', { path: 'here' }]; export const path2: PathElements = ['some', 'path']; export const path3: PathElements = ['some', 'path', { path: 'here' }]; export const encodedPath1 = ['xARzb21l', 'xAVvdGhlcg==', 'gcQEcGF0aMQEaGVyZQ==']; export const encodedPath2 = ['xARzb21l', 'xARwYXRo']; export const encodedPath3 = ['xARzb21l', 'xARwYXRo', 'gcQEcGF0aMQEaGVyZQ==']; export const key1 = 'firstKey'; export const encodedKey1 = '<KEY>'; export const rootNotif: RawNotification = { timestamp: { seconds: 1539822611, nanos: 883496 }, updates: [ { key: '<KEY>', value: '<KEY>', }, { key: '<KEY>', value: 'xAlBdGhsZXRpY3M=', }, ], }; export const firstNotif: RawNotification = { path_elements: encodedPath1, timestamp: { seconds: 1539822611, nanos: 883496678 }, updates: [ { key: '<KEY>', value: 'xAdEb2RnZXJz', }, { key: '<KEY>', value: 'xAlBdGhsZXRpY3M=', }, ], }; export const secondNotif: RawNotification = { path_elements: encodedPath2, timestamp: { seconds: 1539822631, nanos: 883496 }, updates: [ { key: '<KEY>', value: 'xANOQkE=', }, ], }; export const thirdNotif: RawNotification = { path_elements: encodedPath1, timestamp: { seconds: 1539822611 }, updates: [ { key: '<KEY>', value: 'ksQCTkzEAkFM', }, ], deletes: ['xA1CYXkgQXJlYSBUZWFt'], }; export const fourthNotif: RawNotification = { path_elements: encodedPath1, timestamp: { seconds: 1539822631, nanos: 9934968754 }, deletes: ['xA1CYXNlYmFsbCBUZWFt'], }; export const fifthNotif: RawNotification = { path_elements: encodedPath3, timestamp: { seconds: 1539822631, nanos: 993496 }, updates: [ { key: '<KEY>', value: 'xANOQkE=', }, ], }; export const sixthNotif: RawNotification = { path_elements: encodedPath1, timestamp: { seconds: 1539832611, nanos: 883496678 }, delete_all: true, }; export const expectedRootNotif: ConvertedNotification = { path_elements: [], timestamp: 1539822611000, nanos: 883496, updates: { xA1CYXNlYmFsbCBUZWFt: { key: 'Baseball Team', value: 'Dodgers', }, xA1CYXkgQXJlYSBUZWFt: { key: 'Bay Area Team', value: 'Athletics', }, }, }; export const expectedFirstNotif: ConvertedNotification = { nanos: 883496678, path_elements: path1, timestamp: 1539822611883, updates: { xA1CYXNlYmFsbCBUZWFt: { key: 'Baseball Team', value: 'Dodgers', }, xA1CYXkgQXJlYSBUZWFt: { key: 'Bay Area Team', value: 'Athletics', }, }, }; export const expectedSecondNotif: ConvertedNotification = { path_elements: path2, timestamp: 1539822631000, nanos: 883496, updates: { xApCYXNrZXRiYWxs: { key: 'Basketball', value: 'NBA', }, }, }; export const expectedThirdNotif: ConvertedNotification = { path_elements: path1, timestamp: 1539822611000, nanos: 0, updates: { gcQFc3BvcnTECGJhc2ViYWxs: { key: { sport: 'baseball' }, value: ['NL', 'AL'], }, }, deletes: { xA1CYXkgQXJlYSBUZWFt: { key: 'Bay Area Team', }, }, }; export const expectedFourthNotif: ConvertedNotification = { nanos: 9934968754, path_elements: path1, timestamp: 1539822631993, deletes: { xA1CYXNlYmFsbCBUZWFt: { key: 'Baseball Team', }, }, }; export const expectedFifthNotif: ConvertedNotification = { path_elements: path3, timestamp: 1539822631000, nanos: 993496, updates: { xApCYXNrZXRiYWxs: { key: 'Basketball', value: 'NBA', }, }, }; export const expectedSixthNotif: ConvertedNotification = { path_elements: path1, timestamp: 1539832611883, nanos: 883496678, deletes: {}, }; export const firstNotifPublishRaw: PublishNotification = { path_elements: path1, timestamp: { seconds: 1539822611, nanos: 883496678 }, updates: [ { key: 'Baseball Team', value: 'Dodgers', }, { key: 'Bay Area Team', value: 'Athletics', }, ], }; export const secondNotifPublishRaw: PublishNotification = { path_elements: path2, timestamp: { seconds: 1539822631, nanos: 883496 }, updates: [ { key: 'Basketball', value: 'NBA', }, ], }; export const thirdNotifPublishRaw: PublishNotification = { path_elements: path1, timestamp: { seconds: 1539822611 }, updates: [ { key: { sport: 'baseball' }, value: ['NL', 'AL'], }, ], deletes: ['Bay Area Team'], }; export const fourthNotifPublishRaw: PublishNotification = { path_elements: path1, timestamp: { seconds: 1539822631, nanos: 9934968754 }, deletes: ['Baseball Team'], }; export const sixthNotifPublishRaw: PublishNotification = { path_elements: path1, timestamp: { seconds: 1539832611, nanos: 883496678 }, deletes: [], }; export const rootNotifPublishRaw: PublishNotification = { path_elements: [], timestamp: { seconds: 1539822611, nanos: 883496 }, updates: [ { key: 'Baseball Team', value: 'Dodgers', }, { key: 'Bay Area Team', value: 'Athletics', }, ], }; export const query: Query = [ { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1', }, paths: [ { path_elements: path2, }, ], }, { dataset: { type: DEVICE_DATASET_TYPE, name: 'device2', }, paths: [ { path_elements: path1, }, { path_elements: path2, }, ], }, ]; export const queryWithKeys: Query = [ { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1', }, paths: [ { path_elements: path2, keys: [key1], }, ], }, { dataset: { type: DEVICE_DATASET_TYPE, name: 'device2', }, paths: [ { path_elements: path1, }, { path_elements: path2, }, ], }, ]; export const encodedQuery: Query = [ { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1', }, paths: [ { path_elements: encodedPath2, }, ], }, { dataset: { type: DEVICE_DATASET_TYPE, name: 'device2', }, paths: [ { path_elements: encodedPath1, }, { path_elements: encodedPath2, }, ], }, ]; export const encodedQueryWithKeys: Query = [ { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1', }, paths: [ { path_elements: encodedPath2, keys: [encodedKey1], }, ], }, { dataset: { type: DEVICE_DATASET_TYPE, name: 'device2', }, paths: [ { path_elements: encodedPath1, }, { path_elements: encodedPath2, }, ], }, ]; export const queryOneDeviceMultiplePaths: Query = [ { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1', }, paths: [ { path_elements: path1, }, { path_elements: path2, }, ], }, ]; export const encodedQueryOneDeviceMultiplePaths: Query = [ { dataset: { type: DEVICE_DATASET_TYPE, name: 'device2', }, paths: [ { path_elements: encodedPath1, }, { path_elements: encodedPath2, }, ], }, ]; export const queryOneDeviceOnePath: Query = [ { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1', }, paths: [ { path_elements: path1, }, ], }, ]; <file_sep>/* eslint-env jest */ /* eslint-disable @typescript-eslint/naming-convention */ import { encode } from '../../src'; import { Bool, Float32, Float64, Int, Nil, Pointer, Str } from '../../src/neat/NeatTypes'; import { isNeatType, NeatTypeSerializer, sortMapByKey } from '../../src/neat/utils'; function testSerializeAndDeserialize( value: Bool | Float32 | Float64 | Nil | Int | Str | Pointer, ): void { const serializedValue = NeatTypeSerializer.serialize(value); const deserializedValue = NeatTypeSerializer.deserialize(serializedValue); expect(serializedValue.value).toEqual(value.value); /* eslint-disable-next-line */ expect(serializedValue.__neatTypeClass).toEqual(value.type); expect(deserializedValue.value).toEqual(value.value); expect(deserializedValue.type).toEqual(value.type); } describe('isNeatType', () => { test('should validate proper Neat objects', () => { const exampleStr = new Str('arista'); const exampleNil = new Nil(); const exampleBool = new Bool(true); const exampleInt = new Int(7); const exampleFloat32 = new Float32(91.3); const exampleFloat64 = new Float64(90000.25); const examplePtr = new Pointer(['path', 'to', 'fivepm']); expect(isNeatType(exampleStr)).toBeTruthy(); expect(isNeatType(exampleNil)).toBeTruthy(); expect(isNeatType(exampleBool)).toBeTruthy(); expect(isNeatType(exampleInt)).toBeTruthy(); expect(isNeatType(exampleFloat32)).toBeTruthy(); expect(isNeatType(exampleFloat64)).toBeTruthy(); expect(isNeatType(examplePtr)).toBeTruthy(); }); test('should reject regular javascript elements', () => { expect(isNeatType('arista')).toBeFalsy(); expect(isNeatType(null)).toBeFalsy(); expect(isNeatType(true)).toBeFalsy(); expect(isNeatType(7)).toBeFalsy(); expect(isNeatType(91.3)).toBeFalsy(); expect(isNeatType(90000.25)).toBeFalsy(); expect(isNeatType(['path', 'to', 'fivepm'])).toBeFalsy(); expect(isNeatType({ type: 'device', value: 'red_herring' })).toBeFalsy(); expect(isNeatType({ type: 'str', value: 'nefarious', valueTwo: 'fake neattype' })).toBeFalsy(); const fakePtr = { type: 'ptr', value: ['ptr', 'w/o', 'delimiter', 'is', 'just', 'array'] }; expect(isNeatType(fakePtr)).toBeFalsy(); }); }); describe('sortMapByKey', () => { test('should return -1, if value a is smaller', () => { expect(sortMapByKey([encode('a'), 'a'], [encode('b'), 'b'])).toEqual(-1); expect(sortMapByKey([encode('a'), 'a'], [encode('aa'), 'aa'])).toEqual(-1); expect(sortMapByKey([encode(1), 1], [encode(2), 2])).toEqual(-1); expect( sortMapByKey( [new Uint8Array([1, 2, 3]), [1, 2, 3]], [new Uint8Array([1, 2, 3, 4]), [1, 2, 3, 4]], ), ).toEqual(-1); }); test('should return 1, if value a is larger', () => { expect(sortMapByKey([encode('b'), 'b'], [encode('a'), 'a'])).toEqual(1); expect(sortMapByKey([encode('bb'), 'bb'], [encode('b'), 'b'])).toEqual(1); expect(sortMapByKey([encode(2), 2], [encode(1), 1])).toEqual(1); expect( sortMapByKey( [new Uint8Array([1, 2, 3, 4]), [1, 2, 3, 4]], [new Uint8Array([1, 2, 3]), [1, 2, 3]], ), ).toEqual(1); }); test('should return 0, if values are equal', () => { expect(sortMapByKey([encode('a'), 'a'], [encode('a'), 'a'])).toEqual(0); expect(sortMapByKey([encode(1), 1], [encode(1), 1])).toEqual(0); expect( sortMapByKey([new Uint8Array([1, 2, 3]), [1, 2, 3]], [new Uint8Array([1, 2, 3]), [1, 2, 3]]), ).toEqual(0); const samePointer: [Uint8Array, unknown] = [new Uint8Array([1, 2, 3]), [1, 2, 3]]; expect(sortMapByKey(samePointer, samePointer)).toEqual(0); }); }); describe('NeatTypeSerializer', () => { test('Bool', () => { testSerializeAndDeserialize(new Bool(true)); testSerializeAndDeserialize(new Bool(false)); }); test('Float32', () => { testSerializeAndDeserialize(new Float32(123.456)); }); test('Float64', () => { testSerializeAndDeserialize(new Float64(8274.51123)); }); test('Int', () => { testSerializeAndDeserialize(new Int(67)); }); test('Str', () => { testSerializeAndDeserialize(new Str('the answer is now')); }); test('Pointer', () => { testSerializeAndDeserialize(new Pointer(['path', 'to', 'glory'])); }); test('Nil', () => { testSerializeAndDeserialize(new Nil()); }); }); <file_sep>/* eslint-disable @typescript-eslint/prefer-for-of */ // Allow usage of for loops, since here performance is paramount // Copyright (c) 2018, Arista Networks, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import { encode, decode, Codec, PathElements } from 'a-msgpack'; import { fromByteArray, toByteArray } from 'base64-js'; import { BatchPublishRequest, CloudVisionBatchedNotifications, CloudVisionDatapoint, CloudVisionDeletes, CloudVisionMessage, CloudVisionNotifs, CloudVisionParams, CloudVisionPublishRequest, CloudVisionQueryMessage, CloudVisionRawNotifs, CloudVisionUpdates, ConvertedNotification, NewConvertedNotification, PathObject, PublishRequest, Query, QueryObject, QueryParams, RawNotification, ServiceRequest, } from '../types'; const msgpack = { encode: (inputs: unknown): Uint8Array => encode(inputs, { extensionCodec: Codec }), decode: (data: Uint8Array): unknown => decode(data, { extensionCodec: Codec, useJSBI: true }), }; /** * Individually NEAT encodes path elements * @param pathElements an array of unencoded path elements * @returns an array of encoded path elements */ export function encodePathElements(pathElements: PathElements): string[] { const encodedPathElements = []; for (let i = 0; i < pathElements.length; i += 1) { encodedPathElements.push(fromByteArray(msgpack.encode(pathElements[i]))); } return encodedPathElements; } /** * NEAT encodes the path elements and keys in a [[Query]]. * * @returns the [[Query]] with encoded path elements and keys. */ export function encodePathElementsAndKeysInQuery(query: Query): Query { const encodedQuery = []; for (let i = 0; i < query.length; i += 1) { const encodedQueryItem: QueryObject = { dataset: query[i].dataset, paths: [], }; const queryItem = query[i]; for (let j = 0; j < queryItem.paths.length; j += 1) { const path = queryItem.paths[j]; const encodedPath: PathObject = { path_elements: [], }; const encodedKeys = []; if (path.keys && Array.isArray(path.keys)) { for (let k = 0; k < path.keys.length; k += 1) { encodedKeys.push(fromByteArray(msgpack.encode(path.keys[k]))); } encodedPath.keys = encodedKeys; } encodedPath.path_elements = encodePathElements(path.path_elements); encodedQueryItem.paths.push(encodedPath); } encodedQuery.push(encodedQueryItem); } return encodedQuery; } /** * Decodes NEAT encoded path elements. * * @param pathElements an array of encoded path elements * @returns an array of path elements */ export function decodePathElements(pathElements: string[]): PathElements { const decodedPathElements = []; for (let i = 0; i < pathElements.length; i += 1) { decodedPathElements.push(msgpack.decode(toByteArray(pathElements[i]))); } return decodedPathElements as PathElements; } /** * Decodes a single NEAT encoded update notification. * * @param notif an array of object with the keys `key` and `value`. The values are NEAT encoded * @returns an object keyed by the binary representation of the `key` value. Each value * is an object with the keys `key` and `value`, each of which are decoded. */ function decodeNotifs( notif: CloudVisionDatapoint<string, string>[], ): CloudVisionUpdates<unknown, unknown> { const decodedNotifs: CloudVisionUpdates<unknown, unknown> = {}; for (let i = 0; i < notif.length; i += 1) { const key = notif[i].key; const value = notif[i].value; const decodedKey = msgpack.decode(toByteArray(key)); const decodedValue = msgpack.decode(toByteArray(value)); decodedNotifs[key] = { key: decodedKey, value: decodedValue, }; } return decodedNotifs; } /** * Encodes a single update notification in NEAT. * * @param notif an array of objects with the keys `key` and `value`. The values are unencoded. * @returns an array of objects with the keys `key` and `value`. The value of these keys * is the NEAT encoded value of the raw data. */ function encodeNotifs( notif: CloudVisionDatapoint<unknown, unknown>[], ): CloudVisionDatapoint<string, string>[] { const encodedNotifs: CloudVisionDatapoint<string, string>[] = []; for (let i = 0; i < notif.length; i += 1) { const key = notif[i].key; const value = notif[i].value; encodedNotifs.push({ key: fromByteArray(msgpack.encode(key)), value: fromByteArray(msgpack.encode(value)), }); } return encodedNotifs; } /** * Encodes a single delete notification in NEAT. * * @param deletes an array of keys * @returns an array of NEAT encoded `key` values. */ function encodeDeletes(deletes: unknown[]): string[] { const decodedDeletes = []; for (let i = 0; i < deletes.length; i += 1) { const key = deletes[i]; decodedDeletes.push(fromByteArray(msgpack.encode(key))); } return decodedDeletes; } /** * Decodes a single NEAT encoded delete notification. * * @param deletes an array of NEAT encoded `key` values. * @returns an array of decoded keys */ function decodeDeletes(deletes: string[]): CloudVisionDeletes<unknown> { const decodedDeletes: CloudVisionDeletes<unknown> = {}; for (let i = 0; i < deletes.length; i += 1) { const key = deletes[i]; decodedDeletes[key] = { key: msgpack.decode(toByteArray(key)), }; } return decodedDeletes; } /** * The API server returns timestamps in the * [Protobuf Timestamp](https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/Timestamp) * format. * * This converts timestamps in all notifications to milliseconds for use with * JS Date(). */ function convertNotif(notif: RawNotification): ConvertedNotification { const convertedNotif: ConvertedNotification = { path_elements: [], timestamp: 0, }; convertedNotif.path_elements = decodePathElements(notif.path_elements || []); // Pad nano seconds let nanos = ''; if (notif.timestamp.nanos) { nanos += notif.timestamp.nanos; } nanos = nanos.padStart(9, '0'); const timestampAsString = '' + notif.timestamp.seconds + nanos; convertedNotif.nanos = parseInt(nanos, 10); convertedNotif.timestamp = parseInt(timestampAsString.slice(0, 13), 10); if (notif.updates) { convertedNotif.updates = decodeNotifs(notif.updates); } if (notif.deletes) { convertedNotif.deletes = decodeDeletes(notif.deletes); } if (notif.delete_all) { convertedNotif.deletes = {}; } return convertedNotif; } /** * Decodes notifications and batches them by their full path elements * * @param batch the batched notifications to which these raw notifications will be added. * @param notif the raw notifications as they come from the API server. */ function decodeAndBatchNotif(batch: CloudVisionBatchedNotifications, notif: RawNotification): void { const convertedNotif: ConvertedNotification = convertNotif(notif); if (batch.notifications[JSON.stringify(convertedNotif.path_elements)]) { batch.notifications[JSON.stringify(convertedNotif.path_elements)].push(convertedNotif); } else { batch.notifications[JSON.stringify(convertedNotif.path_elements)] = [convertedNotif]; } } /** * Sort function to sort elements in an array by their GRPC timestamp. * * @param first The first element * @param second the second element to compare against */ export function sortTimestamp(first: RawNotification, second: RawNotification): number { // Compare seconds if (first.timestamp.seconds < second.timestamp.seconds) { return -1; } if (first.timestamp.seconds > second.timestamp.seconds) { return 1; } // Compare nanos if (first.timestamp.nanos && second.timestamp.nanos) { if (first.timestamp.nanos < second.timestamp.nanos) { return -1; } if (first.timestamp.nanos > second.timestamp.nanos) { return 1; } } if (!first.timestamp.nanos) { return -1; } if (!second.timestamp.nanos) { return 1; } return 0; } /** * Decodes the full result returned from the API server. * * @param result the raw notifications returned from the API server. * @param batchResults if `true`, notifications will be batched by their path elements. * otherwise the notifications will just be decoded and returned in the same format as * the server sends them. * @returns the decoded result returned from the server */ export function decodeNotifications( result: CloudVisionRawNotifs, batchResults: boolean, ): CloudVisionBatchedNotifications | CloudVisionNotifs { result.notifications.sort(sortTimestamp); if (batchResults) { const batch: CloudVisionBatchedNotifications = { dataset: result.dataset, metadata: result.metadata || {}, notifications: {}, }; for (let i = 0; i < result.notifications.length; i += 1) { const n = result.notifications[i]; decodeAndBatchNotif(batch, n); } return batch; } const notif: CloudVisionNotifs = { dataset: result.dataset, metadata: result.metadata || {}, notifications: [], }; for (let i = 0; i < result.notifications.length; i += 1) { const n = result.notifications[i]; const convertedNotif: ConvertedNotification = convertNotif(n); notif.notifications.push(convertedNotif); } return notif; } /** * Encodes a single notification in NEAT. * * @param notif a single unencoded notification. * @returns the NEAT encoded notifications that can be sent to the server */ function encodeNotification(notif: NewConvertedNotification): RawNotification { const encodedNotif: RawNotification = { timestamp: notif.timestamp, }; if (notif.path_elements?.length) { encodedNotif.path_elements = encodePathElements(notif.path_elements); } if (notif.updates) { encodedNotif.updates = encodeNotifs(notif.updates); } if (notif.deletes) { if (!Object.keys(notif.deletes).length) { encodedNotif.delete_all = true; } else { encodedNotif.deletes = encodeDeletes(notif.deletes); } } return encodedNotif; } /** * Encodes a full request that can be sent to the server. * * @param request an unencoded request. * @returns a NEAT encoded request that can be sent to the server. */ export function encodeNotifications( request: PublishRequest | BatchPublishRequest, ): CloudVisionRawNotifs { const encodedData: RawNotification[] = []; const encodedNotif: CloudVisionRawNotifs = { dataset: request.dataset, notifications: encodedData, }; if (!Array.isArray(request.notifications)) { // This is not in the raw format, so we need to convert it const notifKeys = Object.keys(request.notifications); for (let i = 0; i < notifKeys.length; i += 1) { const pathKey = notifKeys[i]; for (let j = 0; j < request.notifications[pathKey].length; j += 1) { encodedData.push(encodeNotification(request.notifications[pathKey][j])); } } } else { for (let i = 0; i < request.notifications.length; i += 1) { encodedData.push(encodeNotification(request.notifications[i])); } } return encodedNotif; } /** * An implementation of a parser that enables communication with the server. * Implements stringify, so that requests can be sent to the server in the proper format. * Implements parse which decodes responses sent by the server. */ export default class Parser { public static parse(data: string, batch: boolean): CloudVisionMessage { const message = JSON.parse(data); const result = message.result; if (result && !result.datasets && result.notifications) { // Timeseries notification that needs to be decoded with NEAT const decodedResult = decodeNotifications(result, batch); return { error: message.error, result: decodedResult, status: message.status, token: message.token, }; } return { error: message.error, result: message.result, status: message.status, token: message.token, }; } public static stringify(message: CloudVisionQueryMessage): string { const params = { ...message.params }; if (Parser.isQuery(params)) { params.query = encodePathElementsAndKeysInQuery(params.query); } if (Parser.isPublish(params)) { params.batch = encodeNotifications(params.batch); } return JSON.stringify({ token: message.token, command: message.command, params, }); } private static isQuery( params: CloudVisionParams | CloudVisionPublishRequest | ServiceRequest, ): params is QueryParams { const queryParams = params as QueryParams; return queryParams.query !== undefined && Array.isArray(queryParams.query); } private static isPublish( params: CloudVisionParams | CloudVisionPublishRequest | ServiceRequest, ): params is CloudVisionPublishRequest { const publishParams = params as CloudVisionPublishRequest; return publishParams.sync !== undefined && publishParams.batch !== undefined; } } <file_sep>module.exports = { cacheDirectory: '.jest-cache', coverageThreshold: { global: { branches: 98.94, functions: 100, lines: 99.22, statements: 99.25, }, }, coverageReporters: ['html', 'lcov'], collectCoverageFrom: [ '**/*.ts', '!src/index.ts', '!src/utils/utf8.ts', '!src/utils/prettyByte.ts', '!**/node_modules/**', '!**/lib/**', '!**/es/**', '!**/dist/**', '!**/coverage/**', '!**/*.spec.ts', '!**/*.config.js', ], transform: { '^.+\\.ts$': 'ts-jest', }, roots: ['<rootDir>/test', '<rootDir>/src'], setupFiles: ['<rootDir>/test/encoder-setup.js'], }; <file_sep>import { ignoreElements, mergeMap, NEVER, throwError, timer } from 'rxjs'; import { TestScheduler } from 'rxjs/testing'; import { bufferOnce } from '../src/operators'; let testScheduler: TestScheduler; beforeEach(() => { testScheduler = new TestScheduler((actual, expected) => expect(actual).toEqual(expected)); }); describe('bufferOnce', () => { test('should emit buffer on source complete', () => { testScheduler.run(({ cold, expectObservable }) => { const source = cold('1-2-3-|'); const observable = source.pipe(bufferOnce(NEVER)); expectObservable(observable).toBe('------(a|)', { a: ['1', '2', '3'] }); }); }); test('should emit buffer on notifier next', () => { testScheduler.run(({ cold, expectObservable }) => { const source = cold('1-2-3-4-5'); const notifier = timer(5); const observable = source.pipe(bufferOnce(notifier)); expectObservable(observable).toBe('-----(a|)', { a: ['1', '2', '3'] }); }); }); test('should not emit buffer on notifier complete', () => { testScheduler.run(({ cold, expectObservable }) => { const source = cold('1-2-3-4-5'); const notifier = timer(5).pipe(ignoreElements()); const observable = source.pipe(bufferOnce(notifier)); expectObservable(observable).toBe(''); }); }); test('should error on source error', () => { testScheduler.run(({ cold, expectObservable }) => { const error = 'oh no!'; const source = cold('1-2#', undefined, error); const observable = source.pipe(bufferOnce(NEVER)); expectObservable(observable).toBe('---#', undefined, error); }); }); test('should error on notifier error', () => { testScheduler.run(({ cold, expectObservable }) => { const error = 'oh no!'; const source = cold('1-2-3-4-5'); const notifier = timer(5).pipe(mergeMap(() => throwError(() => error))); const observable = source.pipe(bufferOnce(notifier)); expectObservable(observable).toBe('-----#', undefined, error); }); }); }); <file_sep>import { CachedKeyDecoder } from './CachedKeyDecoder'; import { Decoder } from './Decoder'; import { ExtensionCodecType } from './ExtensionCodec'; export interface DecodeOptions { /** * The extension codec to use. * Default is none */ extensionCodec?: ExtensionCodecType; /** * Maximum string length. * Default to 4_294_967_295 (UINT32_MAX). */ maxStrLength?: number; /** * Maximum binary length. * Default to 4_294_967_295 (UINT32_MAX). */ maxBinLength?: number; /** * Maximum array length. * Default to 4_294_967_295 (UINT32_MAX). */ maxArrayLength?: number; /** * Maximum map length. * Default to 4_294_967_295 (UINT32_MAX). */ maxMapLength?: number; /** * Maximum extension length. * Default to 4_294_967_295 (UINT32_MAX). */ maxExtLength?: number; /** * Force using JSBI, even if BigInt is available. * Default false. */ useJSBI?: boolean; /** * Use a different caching implementation for decoding keys. * Passing null disables caching keys on decode. * Default CachedKeyDecoder implementation. */ cachedKeyDecoder?: CachedKeyDecoder | null; } export const defaultDecodeOptions: DecodeOptions = {}; /** * It decodes a MessagePack-encoded buffer. * * This is a synchronous decoding function. See other variants for asynchronous decoding: * `decodeAsync()`, `decodeStream()`, and `decodeArrayStream()` */ export function decode( buffer: ArrayLike<number> | ArrayBuffer, options: DecodeOptions = defaultDecodeOptions, ): unknown { const decoder = new Decoder( options.extensionCodec, options.useJSBI, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength, options.cachedKeyDecoder, ); decoder.setBuffer(buffer); // decodeSync() requires only one buffer return decoder.decodeSingleSync(); } <file_sep>// Copyright (c) 2018, Arista Networks, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import { ExtensionCodec } from '../ExtensionCodec'; import { Bool, Float32, Float64, Int, Nil, Pointer, Str, Wildcard } from './NeatTypes'; import { decodePointer, decodeWildcard, encodePointer, encodeWildcard } from './extensions'; export const POINTER_TYPE = 0; export const WILDCARD_TYPE = 1; export const NeatTypes = { Bool, Float32, Float64, Int, Nil, Pointer, Str, Wildcard, }; export const Codec = new ExtensionCodec(); Codec.register({ type: POINTER_TYPE, identifier: (data: unknown) => data instanceof Pointer, encode: encodePointer(Codec), decode: decodePointer(Codec), }); Codec.register({ type: WILDCARD_TYPE, identifier: (data: unknown) => data instanceof Wildcard, encode: encodeWildcard(), decode: decodeWildcard(), }); <file_sep>// eslint-disable-next-line @typescript-eslint/no-unused-vars declare namespace NodeJS { export interface Global { document: Document; window: Window; WebSocket: WebSocket; TextDecoder: typeof TextDecoder; TextEncoder: typeof TextEncoder; } } <file_sep>/* eslint-disable no-console, @typescript-eslint/no-var-requires */ import _ from 'lodash'; import { encode, decode } from '../src'; const data = require('./benchmark-from-msgpack-lite-data.json'); const dataX = _.cloneDeep(new Array(100).fill(data)); const encoded = encode(dataX); console.log('encoded size:', encoded.byteLength); console.time('decode #1'); for (let i = 0; i < 1000; i++) { decode(encoded); } console.timeEnd('decode #1'); console.time('decode #2'); for (let i = 0; i < 1000; i++) { decode(encoded); } console.timeEnd('decode #2'); <file_sep>/* eslint-disable @typescript-eslint/naming-convention */ import { BasicNeatType, PathElements } from '../../types/neat'; import { Bool, Float32, Float64, Int, Nil, Pointer, Str } from './NeatTypes'; interface SerializedNeatType { __neatTypeClass: string; value: unknown; } interface PointerNeatType { type: Pointer['type']; value: PathElements; delimiter: string; } export function isFloat32(value: BasicNeatType): value is Float32 { return value.type === 'float32'; } export function isFloat64(value: BasicNeatType): value is Float64 { return value.type === 'float64'; } export function isInt(value: BasicNeatType): value is Int { return value.type === 'int'; } export function isStr(value: BasicNeatType): value is Str { return value.type === 'str'; } export function isBool(value: BasicNeatType): value is Bool { return value.type === 'bool'; } export function isBasicNeatType(value: unknown): value is BasicNeatType { if (typeof value === 'object' && value !== null) { if (Object.keys(value).length === 2 && 'type' in value && 'value' in value) { const neatValue = value as BasicNeatType; return [Bool.type, Float32.type, Float64.type, Int.type, Nil.type, Str.type].includes( neatValue.type, ); } } return false; } export function isNeatType(value: unknown): boolean { if (typeof value === 'object' && value !== null) { if (isBasicNeatType(value)) { return true; } if ( Object.keys(value).length === 3 && 'type' in value && 'value' in value && 'delimiter' in value ) { const neatValue = value as PointerNeatType; return neatValue.type === Pointer.type; } } return false; } function sortByBinaryValue(a: Uint8Array, b: Uint8Array): number { const len = Math.min(a.length, b.length); if (a === b) { return 0; } for (let i = 0; i < len; i += 1) { if (a[i] !== b[i]) { return a[i] - b[i]; } } return a.length - b.length; } export function sortMapByKey(a: [Uint8Array, unknown], b: [Uint8Array, unknown]): number { const aVal = a[0]; const bVal = b[0]; return sortByBinaryValue(aVal, bVal); } export class NeatTypeSerializer { private static NEAT_TYPE_MAP: { [type: string]: | typeof Float32 | typeof Float64 | typeof Int | typeof Pointer | typeof Str | typeof Nil | typeof Bool; } = { float32: Float32, float64: Float64, int: Int, ptr: Pointer, str: Str, nil: Nil, bool: Bool, }; public static serialize(neatTypeInstance: BasicNeatType | PointerNeatType): SerializedNeatType { return { __neatTypeClass: neatTypeInstance.type, value: neatTypeInstance.value, }; } public static deserialize( serializedNeatType: SerializedNeatType, ): BasicNeatType | PointerNeatType { // eslint-disable-next-line no-underscore-dangle return new NeatTypeSerializer.NEAT_TYPE_MAP[serializedNeatType.__neatTypeClass]( serializedNeatType.value, ); } } <file_sep>/* eslint-disable @typescript-eslint/ban-ts-comment */ // @ts-nocheck /* eslint-disable */ import Long from 'long'; import _m0 from '@arista/protobufjs/minimal'; export const protobufPackage = 'arista.subscriptions'; export enum Operation { UNSPECIFIED = 0, /** * INITIAL - INITIAL indicates the associated notification is that of the * current state and a fully-specified Resource is provided. */ INITIAL = 10, /** * INITIAL_SYNC_COMPLETE - INITIAL_SYNC_COMPLETE indicates all existing-state has been * streamed to the client. This status will be sent in an * otherwise-empty message and no subsequent INITIAL messages * should be expected. */ INITIAL_SYNC_COMPLETE = 11, /** * UPDATED - UPDATED indicates the associated notification carries * modification to the last-streamed state. This indicates * the contained Resource may be a partial diff, though, it * may contain a fully-specified Resource. */ UPDATED = 20, /** * DELETED - DETLETED indicates the associated notification carries * a deletion. The Resource's key will always be set in this case, * but no other fields should be expected. */ DELETED = 30, UNRECOGNIZED = -1, } export function operationFromJSON(object: any): Operation { switch (object) { case 0: case 'UNSPECIFIED': return Operation.UNSPECIFIED; case 10: case 'INITIAL': return Operation.INITIAL; case 11: case 'INITIAL_SYNC_COMPLETE': return Operation.INITIAL_SYNC_COMPLETE; case 20: case 'UPDATED': return Operation.UPDATED; case 30: case 'DELETED': return Operation.DELETED; case -1: case 'UNRECOGNIZED': default: return Operation.UNRECOGNIZED; } } export function operationToJSON(object: Operation): string { switch (object) { case Operation.UNSPECIFIED: return 'UNSPECIFIED'; case Operation.INITIAL: return 'INITIAL'; case Operation.INITIAL_SYNC_COMPLETE: return 'INITIAL_SYNC_COMPLETE'; case Operation.UPDATED: return 'UPDATED'; case Operation.DELETED: return 'DELETED'; default: return 'UNKNOWN'; } } if (_m0.util.Long !== Long) { _m0.util.Long = Long as any; _m0.configure(); } <file_sep>import type { GrpcControlErrorMessage } from '@types'; import { grpc } from '@arista/grpc-web'; export const INITIAL_SYNC_COMPLETE = 'INITIAL_SYNC_COMPLETE'; export const INITIAL_SYNC_COMPLETE_MESSAGE: GrpcControlErrorMessage = { error: { code: grpc.Code.OK, message: INITIAL_SYNC_COMPLETE, }, }; <file_sep>import { encode, decode } from '../src'; // import { Decoder } from '../src/Decoder'; import { ExtensionCodec } from '../src/ExtensionCodec'; import { DecodeOptions } from '../src/decode'; import { POINTER_TYPE } from '../src/neat'; import { Pointer } from '../src/neat/NeatTypes'; import { decodePointer, encodePointer } from '../src/neat/extensions'; const Codec = new ExtensionCodec(); Codec.register({ type: POINTER_TYPE, identifier: (data: unknown) => data instanceof Pointer, encode: encodePointer(Codec), decode: decodePointer(Codec), }); describe.each([ ['maxStrLength', 'foo'], ['maxBinLength', new Pointer(['Dodgers'])], ['maxArrayLength', [1, 2, 3]], ['maxMapLength', { foo: 1, bar: 1, baz: 3 }], ['maxExtLength', new Pointer(['Dodgers'])], ])('decode with maxLength specified', (optionName, value) => { const input = encode(value, { extensionCodec: Codec }); const options: DecodeOptions = { [optionName]: 1, extensionCodec: Codec }; test(`throws errors for ${optionName} (synchronous)`, () => { expect(() => { decode(input, options); }).toThrow(/max length exceeded/i); }); }); <file_sep>/* eslint-disable no-console */ import { CloudVisionStatus, LogLevel } from '../types'; import { ERROR, WARN } from './constants'; /** * Logs nicely formatted console log errors or warnings. */ export function log( level: LogLevel, message: string | null, status?: CloudVisionStatus, token?: string, ): void { const contextualizedMessage = message ? `${level}: ${message}` : `${level}: No message provided`; const statusMessage = status ? `Status Code: ${status.code}, Status Message: ${status.message}` : undefined; const tokenMessage = token ? `Request Token: ${token}` : undefined; console.groupCollapsed('[[ CloudVision Connector ]]'); switch (level) { case ERROR: if (tokenMessage) { console.error(tokenMessage); } console.error(contextualizedMessage); if (statusMessage) { console.error(statusMessage); } break; case WARN: if (tokenMessage) { console.warn(tokenMessage); } console.warn(contextualizedMessage); if (statusMessage) { console.warn(statusMessage); } break; default: if (tokenMessage) { console.log(tokenMessage); } console.log(contextualizedMessage); if (statusMessage) { console.log(statusMessage); } break; } console.groupEnd(); } <file_sep>export { BaseType, Element, NeatType, NeatTypeClass, PathElements, Timestamp } from 'a-msgpack'; export * from './connection'; export * from './logger'; export * from './notifications'; export * from './params'; export * from './query'; <file_sep> #!/usr/bin/env bash if [ -z "$1" ] then echo "No Go source location supplied. Please enter the location where your go files live." exit 1 fi if [ -z "$2" ] then echo "No proto source location supplied. Please enter the location where the protobuf libraries are installed." exit 1 fi GO_SRC_LOC="$1" PROTO_LOC="$2" # Directory to write generated code to (.js and .d.ts files) OUT_DIR="./generated" mkdir -p "${OUT_DIR}" # Path to this plugin, Note this must be an absolute path on Windows PROTOC_GEN_TS_PATH="./node_modules/.bin/protoc-gen-ts_proto" SUBSCRIPTIONS_PROTO_FILES=$(ls $GO_SRC_LOC/arista/resources/arista/subscriptions/*.proto) TS_GEN_OPTIONS=" --plugin=${PROTOC_GEN_TS_PATH} --ts_proto_out=${OUT_DIR}/ --ts_proto_opt=env=browser --ts_proto_opt=esModuleInterop=true --ts_proto_opt=outputClientImpl=grpc-web " GOOGLE_PROTO_FILES=$(ls $PROTO_LOC/include/google/**/*.proto) protoc \ $TS_GEN_OPTIONS \ -I=$PROTO_LOC/include \ $GOOGLE_PROTO_FILES protoc \ $TS_GEN_OPTIONS \ -I=$GO_SRC_LOC/arista/resources \ $SUBSCRIPTIONS_PROTO_FILES echo "Use @arista/protobufjs" find ${OUT_DIR} -type f -name "*.ts" -print0 | xargs -0 sed -i '' -e "s#protobufjs/minimal#@arista/protobufjs/minimal#g" echo "Don't type-check generated files" find ${OUT_DIR} -type f -name "*.ts" -print0 | xargs -0 sed -i '' -e "1s#^#/* eslint-disable @typescript-eslint/ban-ts-comment */\n// @ts-nocheck\n#" <file_sep>// Copyright (c) 2018, Arista Networks, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import { RequestContext, SearchType } from '../types'; export const ERROR = 'ERROR'; export const INFO = 'INFO'; export const WARN = 'WARN'; export const EOF = 'EOF'; /** * Status code for EOF (End Of File). */ export const EOF_CODE = 1001; /** * Status code for Active (when a subscription has been created and is active). */ export const ACTIVE_CODE = 3001; /** * Error status sent when a request has finished streaming data. */ export const RESPONSE_COMPLETED = 'RESPONSE_COMPLETED'; export const GET_REQUEST_COMPLETED = 'GetRequest'; export const CLOSE = 'close'; export const DEVICES_DATASET_ID = 'DEVICES_DATASET_ID'; export const GET = 'get'; export const GET_DATASETS = 'getDatasets'; export const GET_AND_SUBSCRIBE = 'getAndSubscribe'; export const GET_REGIONS_AND_CLUSTERS = 'getRegionsAndClusters'; export const PUBLISH = 'publish'; export const SUBSCRIBE = 'subscribe'; export const SEARCH = 'alpha/search'; export const SEARCH_SUBSCRIBE = 'alpha/searchSubscribe'; export const SERVICE_REQUEST = 'serviceRequest'; export const APP_DATASET_TYPE = 'app'; export const CONFIG_DATASET_TYPE = 'config'; export const DEVICE_DATASET_TYPE = 'device'; export const ALL_DATASET_TYPES: string[] = [ APP_DATASET_TYPE, CONFIG_DATASET_TYPE, DEVICE_DATASET_TYPE, ]; export const SEARCH_TYPE_ANY = 'ANY'; export const SEARCH_TYPE_IP = 'IP'; export const SEARCH_TYPE_MAC = 'MAC'; export const ALL_SEARCH_TYPES = new Set<SearchType>([ SEARCH_TYPE_ANY, SEARCH_TYPE_IP, SEARCH_TYPE_MAC, ]); export const CONNECTED = 'connected'; export const DISCONNECTED = 'disconnected'; export const ID = 'cloudvision-connector'; export const DEFAULT_CONTEXT: RequestContext = { command: 'NO_COMMAND', token: 'NO_<PASSWORD>', encodedParams: 'NO_PARAMS', }; <file_sep>export * from './grpc'; export * from './operators'; export * from './resource'; <file_sep># a-msgpack MessagePack, but for Arista. This is based on the official msgpack library for JS (@msgpack/msgpack), but implements our specific NEAT protocol. ## Installation ```bash npm install a-msgpack ``` or ```bash npm install a-msgpack ``` ## Usage ```js import { encode, decode, Codec } from 'a-msgpack'; const uint8array = msgpack.encode({ Dodgers: '#1', Astros: 'Cheaters' }, { extensionCodec: Codec }); const object = msgpack.decode(uint8array); ``` ## Browser Support In the browser, `a-msgpack` requires the [Encoding API](https://developer.mozilla.org/en-US/docs/Web/API/Encoding_API) to work a peak performance. If the Encoding API is unavailable, there is a fallback JS implementation. ## Benchmarks The lastest code benchmarks and profiling is stored in `last-benchmark-results.txt`. This also compares this implementation to other msgpack libraries. Note, that the decoding results should be comparable to @msgpack/msgpack, but encoding will be slower because NEAT requires that map keys be sorted by binary value. ## License [MIT](https://github.com/JoshuaWise/tiny-msgpack/blob/trunk/LICENSE) <file_sep>/* eslint-env jest */ import { PathElements } from 'a-msgpack'; import Parser, { decodeNotifications, decodePathElements, encodeNotifications, encodePathElementsAndKeysInQuery, sortTimestamp, } from '../src/Parser'; import { DEVICE_DATASET_TYPE, GET, PUBLISH } from '../src/constants'; import { BatchPublishRequest, CloudVisionBatchedNotifications, CloudVisionNotifs, CloudVisionQueryMessage, CloudVisionRawNotifs, PublishRequest, RawNotification, } from '../types'; import { encodedPath1, encodedPath2, encodedQuery, encodedQueryWithKeys, expectedFifthNotif, expectedFirstNotif, expectedFourthNotif, expectedRootNotif, expectedSecondNotif, expectedSixthNotif, expectedThirdNotif, fifthNotif, firstNotif, firstNotifPublishRaw, fourthNotif, fourthNotifPublishRaw, path1, path2, query, queryWithKeys, rootNotif, rootNotifPublishRaw, secondNotif, secondNotifPublishRaw, sixthNotif, sixthNotifPublishRaw, thirdNotif, thirdNotifPublishRaw, } from './fixtures'; describe('encode/decode path elements', () => { test('encodePathElementsAndKeysInQuery just path elements', () => { const clonedQuery = JSON.parse(JSON.stringify(query)); expect(encodePathElementsAndKeysInQuery(query)).toEqual(encodedQuery); expect(clonedQuery).toEqual(query); }); test('encodePathElementsAndKeysInQuery with keys', () => { const clonedQuery = JSON.parse(JSON.stringify(queryWithKeys)); expect(encodePathElementsAndKeysInQuery(queryWithKeys)).toEqual(encodedQueryWithKeys); expect(clonedQuery).toEqual(queryWithKeys); }); test('decodePathElements', () => { const clonedEncodedPath1 = JSON.parse(JSON.stringify(encodedPath1)); const clonedEncodedPath2 = JSON.parse(JSON.stringify(encodedPath2)); expect(decodePathElements(clonedEncodedPath2)).toEqual(path2); expect(decodePathElements(clonedEncodedPath1)).toEqual(path1); expect(clonedEncodedPath2).toEqual(encodedPath2); expect(clonedEncodedPath1).toEqual(encodedPath1); expect(decodePathElements([])).toEqual<PathElements>([]); }); }); describe('Parser', () => { const encodedData: CloudVisionRawNotifs = { dataset: { type: DEVICE_DATASET_TYPE, name: 'Dodgers' }, notifications: [firstNotif, secondNotif, thirdNotif, fourthNotif, sixthNotif], }; describe('parse', () => { const batchedResult: CloudVisionBatchedNotifications = { dataset: { type: DEVICE_DATASET_TYPE, name: 'Dodgers' }, metadata: {}, notifications: { [JSON.stringify(path1)]: [ expectedThirdNotif, expectedFirstNotif, expectedFourthNotif, expectedSixthNotif, ], [JSON.stringify(path2)]: [expectedSecondNotif], }, }; const rawResult: CloudVisionNotifs = { dataset: { type: DEVICE_DATASET_TYPE, name: 'Dodgers' }, metadata: {}, notifications: [ expectedThirdNotif, expectedFirstNotif, expectedSecondNotif, expectedFourthNotif, expectedSixthNotif, ], }; const data = { result: encodedData, status: {}, token: 'someToken', }; const expectedBatchData = { error: undefined, result: batchedResult, status: {}, token: 'someToken', }; const expectedRawFormat = { result: rawResult, status: {}, token: 'someToken', }; test('decode messages in batch format', () => { expect(Parser.parse(JSON.stringify(data), true)).toEqual(expectedBatchData); }); test('decode messages in raw format', () => { expect(Parser.parse(JSON.stringify(data), false)).toEqual(expectedRawFormat); }); test('decode empty result', () => { expect(Parser.parse(JSON.stringify({}), false)).toEqual({ result: undefined, status: undefined, token: undefined, }); }); }); describe('stringify', () => { const batchedResult: BatchPublishRequest = { dataset: { type: DEVICE_DATASET_TYPE, name: 'Dodgers' }, notifications: { [JSON.stringify(path1)]: [ firstNotifPublishRaw, secondNotifPublishRaw, thirdNotifPublishRaw, fourthNotifPublishRaw, sixthNotifPublishRaw, ], }, }; const rawResult: PublishRequest = { dataset: { type: DEVICE_DATASET_TYPE, name: 'Dodgers' }, notifications: [ firstNotifPublishRaw, secondNotifPublishRaw, thirdNotifPublishRaw, fourthNotifPublishRaw, sixthNotifPublishRaw, ], }; const expectedPublishData: CloudVisionQueryMessage = { command: PUBLISH, token: 'someToken', params: { sync: true, batch: encodedData, }, }; test('encode messages given in batch format', () => { const publishBatchParams: CloudVisionQueryMessage = { command: PUBLISH, token: 'someToken', params: { sync: true, batch: batchedResult, }, }; const publishBatchParamsClone = JSON.parse(JSON.stringify(publishBatchParams)); expect(JSON.parse(Parser.stringify(publishBatchParams))).toEqual(expectedPublishData); expect(publishBatchParams).toEqual(publishBatchParamsClone); }); test('encode messages given in raw format', () => { const publishRawParams: CloudVisionQueryMessage = { command: PUBLISH, token: 'someToken', params: { sync: true, batch: rawResult, }, }; const publishRawParamsClone = JSON.parse(JSON.stringify(publishRawParams)); expect(JSON.parse(Parser.stringify(publishRawParams))).toEqual(expectedPublishData); expect(publishRawParamsClone).toEqual(publishRawParams); }); test('encode query message', () => { const queryParams: CloudVisionQueryMessage = { command: GET, token: 'someToken', params: { query: [ { dataset: { name: 'Dodgers', type: DEVICE_DATASET_TYPE }, paths: [{ path_elements: path1 }], }, ], }, }; const expectedQueryParams: CloudVisionQueryMessage = { command: GET, token: 'someToken', params: { query: [ { dataset: { name: 'Dodgers', type: DEVICE_DATASET_TYPE }, paths: [{ path_elements: encodedPath1 }], }, ], }, }; const expectedQueryParamsClone = JSON.parse(JSON.stringify(expectedQueryParams)); expect(JSON.parse(Parser.stringify(queryParams))).toEqual(expectedQueryParams); expect(expectedQueryParamsClone).toEqual(expectedQueryParams); }); }); }); describe('decodeNotifications', () => { test('should properly batch requests for multiple paths', () => { const notif: CloudVisionRawNotifs = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, notifications: [firstNotif, secondNotif, thirdNotif, fourthNotif], }; const expectedNotif: CloudVisionBatchedNotifications = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, metadata: {}, notifications: { [JSON.stringify(path1)]: [expectedThirdNotif, expectedFirstNotif, expectedFourthNotif], [JSON.stringify(path2)]: [expectedSecondNotif], }, }; const decodedNotif = decodeNotifications(notif, true); expect(decodedNotif).toEqual(expectedNotif); expect(decodedNotif).not.toBe(expectedNotif); }); test('should properly batch requests for one path', () => { const notif: CloudVisionRawNotifs = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, notifications: [firstNotif, thirdNotif], }; const expectedNotif: CloudVisionBatchedNotifications = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, metadata: {}, notifications: { [JSON.stringify(path1)]: [expectedThirdNotif, expectedFirstNotif], }, }; const batchedNotif = decodeNotifications(notif, true); expect(batchedNotif).toEqual(expectedNotif); expect(batchedNotif).not.toBe(expectedNotif); }); test('should properly batch requests for the root path', () => { const notif: CloudVisionRawNotifs = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, notifications: [rootNotif], }; const expectedNotif: CloudVisionBatchedNotifications = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, metadata: {}, notifications: { [JSON.stringify([])]: [expectedRootNotif], }, }; const batchedNotif = decodeNotifications(notif, true); expect(batchedNotif).toEqual(expectedNotif); expect(batchedNotif).not.toBe(expectedNotif); }); test('should properly decode metadata when batched', () => { const notif: CloudVisionRawNotifs = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, metadata: { Dodgers: 'Rule!' }, notifications: [firstNotif, thirdNotif], }; const expectedNotif: CloudVisionBatchedNotifications = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, metadata: { Dodgers: 'Rule!' }, notifications: { [JSON.stringify(path1)]: [expectedThirdNotif, expectedFirstNotif], }, }; const batchedNotif = decodeNotifications(notif, true); expect(batchedNotif).toEqual(expectedNotif); expect(batchedNotif).not.toBe(expectedNotif); }); test('should properly decode non batch requests for multiple paths', () => { const notif: CloudVisionRawNotifs = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, notifications: [firstNotif, secondNotif, thirdNotif, fourthNotif], }; const expectedNotif: CloudVisionNotifs = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, metadata: {}, notifications: [ expectedThirdNotif, expectedFirstNotif, expectedSecondNotif, expectedFourthNotif, ], }; const decodedNotif = decodeNotifications(notif, false); expect(decodedNotif).toEqual(expectedNotif); expect(decodedNotif).not.toBe(expectedNotif); }); test('should properly decode non batch requests for for one path', () => { const notif: CloudVisionRawNotifs = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, notifications: [firstNotif, thirdNotif], }; const expectedNotif: CloudVisionNotifs = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, metadata: {}, notifications: [expectedThirdNotif, expectedFirstNotif], }; const batchedNotif = decodeNotifications(notif, false); expect(batchedNotif).toEqual(expectedNotif); expect(batchedNotif).not.toBe(expectedNotif); }); test('should properly decode metadata when not batched', () => { const notif: CloudVisionRawNotifs = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, metadata: { Dodgers: 'Rule!' }, notifications: [firstNotif, thirdNotif], }; const expectedNotif: CloudVisionNotifs = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, metadata: { Dodgers: 'Rule!' }, notifications: [expectedThirdNotif, expectedFirstNotif], }; const batchedNotif = decodeNotifications(notif, false); expect(batchedNotif).toEqual(expectedNotif); expect(batchedNotif).not.toBe(expectedNotif); }); test('should properly decode delete all', () => { const notif: CloudVisionRawNotifs = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, notifications: [firstNotif, sixthNotif], }; const expectedNotif: CloudVisionBatchedNotifications = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, metadata: {}, notifications: { [JSON.stringify(path1)]: [expectedFirstNotif, expectedSixthNotif], }, }; const decodedNotif = decodeNotifications(notif, true); expect(decodedNotif).toEqual(expectedNotif); expect(decodedNotif).not.toBe(expectedNotif); }); test('should properly sort out of order notifications within the batch', () => { const notif: CloudVisionRawNotifs = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, notifications: [fourthNotif, fifthNotif, firstNotif, thirdNotif], }; const expectedNotif: CloudVisionNotifs = { dataset: { type: DEVICE_DATASET_TYPE, name: 'device1' }, metadata: {}, notifications: [ expectedThirdNotif, expectedFirstNotif, expectedFifthNotif, expectedFourthNotif, ], }; const batchedNotif = decodeNotifications(notif, false); expect(batchedNotif).toEqual(expectedNotif); expect(batchedNotif).not.toBe(expectedNotif); }); }); describe('encodeNotifications', () => { const rawNotifs: PublishRequest = { dataset: { type: DEVICE_DATASET_TYPE, name: 'Dodgers' }, notifications: [ rootNotifPublishRaw, firstNotifPublishRaw, secondNotifPublishRaw, thirdNotifPublishRaw, fourthNotifPublishRaw, ], }; const batchedNotifs: BatchPublishRequest = { dataset: { type: DEVICE_DATASET_TYPE, name: 'Dodgers' }, notifications: { [JSON.stringify(path1)]: [ rootNotifPublishRaw, firstNotifPublishRaw, secondNotifPublishRaw, thirdNotifPublishRaw, fourthNotifPublishRaw, ], }, }; const encodedNotifs: CloudVisionRawNotifs = { dataset: { type: DEVICE_DATASET_TYPE, name: 'Dodgers' }, notifications: [rootNotif, firstNotif, secondNotif, thirdNotif, fourthNotif], }; test('should properly encode raw CloudVision notifications', () => { expect(encodeNotifications(rawNotifs)).toEqual(encodedNotifs); }); test('should properly encode CloudVision notifications with no path_elements', () => { const emptyPathElementNotif = { timestamp: { seconds: 1539822631, nanos: 883496 }, updates: [ { key: 'Basketball', value: 'NBA', }, ], }; const emptyPathElementEncoded = { timestamp: { seconds: 1539822631, nanos: 883496 }, updates: [ { key: '<KEY>', value: 'xANOQkE=', }, ], }; const notifs: PublishRequest = { dataset: { type: DEVICE_DATASET_TYPE, name: 'Dodgers' }, notifications: [emptyPathElementNotif], }; const encoded: CloudVisionRawNotifs = { dataset: { type: DEVICE_DATASET_TYPE, name: 'Dodgers' }, notifications: [emptyPathElementEncoded], }; expect(encodeNotifications(notifs)).toEqual(encoded); }); test('should properly encode batched CloudVision notifications', () => { expect(encodeNotifications(batchedNotifs)).toEqual(encodedNotifs); }); }); describe('sortTimestamp', () => { const t1: RawNotification = { timestamp: { seconds: 99, nanos: 18 } }; const t2: RawNotification = { timestamp: { seconds: 22, nanos: 74 } }; const t3: RawNotification = { timestamp: { seconds: 10, nanos: 35 } }; const t4: RawNotification = { timestamp: { seconds: 10, nanos: 31 } }; const t5: RawNotification = { timestamp: { seconds: 30, nanos: 14 } }; const t6: RawNotification = { timestamp: { seconds: 30 } }; test('should return 1 if the seconds in the first element are larger', () => { expect(sortTimestamp(t1, t2)).toBe(1); }); test('should return -1 if the seconds in the first element are smaller', () => { expect(sortTimestamp(t2, t1)).toBe(-1); }); test('should return 1 if the seconds are equal and the nanos in first element are larger', () => { expect(sortTimestamp(t3, t4)).toBe(1); }); test('should return -1 if the seconds are equal and the nanos in first element are smaller', () => { expect(sortTimestamp(t4, t3)).toBe(-1); }); test('should return 1 if the seconds are equal and there are no nanos in the second element', () => { expect(sortTimestamp(t5, t6)).toBe(1); }); test('should return -1 if the seconds are equal and there are no nanos in the first element', () => { expect(sortTimestamp(t6, t5)).toBe(-1); }); test('should return 0 if the seconds and nanos are equal', () => { expect(sortTimestamp(t1, t1)).toBe(0); }); }); <file_sep>export interface PlainObject<T> { [key: string]: T; } export * from './neat'; <file_sep>import JSBI from 'jsbi'; // DataView extension to handle int64 / uint64, // where the actual range is 53-bits integer (a.k.a. safe integer) export function bufferToString(high: number, low: number, unsigned: boolean): string { let highNum = high; let lowNum = low; const radix = 10; const sign = !unsigned && high & 0x80000000; if (sign) { highNum = ~high; lowNum = 0x1_0000_0000 - low; } let str = ''; // eslint-disable-next-line no-constant-condition while (true) { const mod = (highNum % radix) * 0x1_0000_0000 + lowNum; highNum = Math.floor(highNum / radix); lowNum = Math.floor(mod / radix); str = (mod % radix).toString(radix) + str; if (!highNum && !lowNum) { break; } } if (sign) { str = '-' + str; } return str; } function fromStringToBuffer(view: DataView, offset: number, str: string): void { const radix = 10; let pos = 0; const len = str.length; let highNum = 0; let lowNum = 0; if (str.startsWith('-')) { pos++; } const sign = pos; while (pos < len) { const chr = parseInt(str[pos++], radix); if (Number.isNaN(chr) || chr < 0) { // NaN break; } lowNum = lowNum * radix + chr; highNum = highNum * radix + Math.floor(lowNum / 0x1_0000_0000); lowNum %= 0x1_0000_0000; } if (sign) { highNum = ~highNum; if (lowNum) { lowNum = 0x1_0000_0000 - lowNum; } else { highNum++; } } view.setUint32(offset, highNum); view.setUint32(offset + 4, lowNum); } export function setUint64(view: DataView, offset: number, value: bigint | string | number): void { if (typeof value === 'number') { const high = value / 0x1_0000_0000; const low = value; // high bits are truncated by DataView view.setUint32(offset, high); view.setUint32(offset + 4, low); } else if (typeof value === 'bigint') { view.setBigUint64(offset, value); } else if (typeof value === 'string') { fromStringToBuffer(view, offset, value); } } export function setInt64(view: DataView, offset: number, value: bigint | string | number): void { if (typeof value === 'number') { const high = Math.floor(value / 0x1_0000_0000); const low = value; // high bits are truncated by DataView view.setUint32(offset, high); view.setUint32(offset + 4, low); } else if (typeof value === 'bigint') { view.setBigInt64(offset, value); } else if (typeof value === 'string') { fromStringToBuffer(view, offset, value); } } export function getInt64(view: DataView, offset: number, useJSBI: boolean): bigint | JSBI { if (!view.getBigInt64 || useJSBI) { const high = view.getInt32(offset); const low = view.getUint32(offset + 4); return JSBI.BigInt(bufferToString(high, low, false)); } return view.getBigInt64(offset); } export function getUint64(view: DataView, offset: number, useJSBI: boolean): bigint | JSBI { if (!view.getBigUint64 || useJSBI) { const high = view.getUint32(offset); const low = view.getUint32(offset + 4); return JSBI.BigInt(bufferToString(high, low, true)); } return view.getBigUint64(offset); } <file_sep>/* eslint-env jest */ import { ERROR, INFO, WARN } from '../src/constants'; import { log } from '../src/logger'; import { LogLevel } from '../types'; describe.each<[LogLevel, string]>([ [ERROR, 'error'], [INFO, 'log'], [WARN, 'warn'], ])('log', (level, fn) => { const groupSpy = jest.spyOn(console, 'groupCollapsed'); // @ts-expect-error spyOn uses the string name of the function const consoleSpy = jest.spyOn(console, fn); const message = 'Dodgers rule'; const status = { code: 0, message: 'Giants not that great' }; const token = 'MLB'; beforeEach(() => { groupSpy.mockReset(); consoleSpy.mockReset(); }); test(`${level} should log a console group with the default message there is no message`, () => { log(level, null); expect(groupSpy).toHaveBeenCalledTimes(1); expect(consoleSpy).toHaveBeenNthCalledWith(1, `${level}: No message provided`); }); test(`${level} should log a console group for just a message`, () => { log(level, message); expect(groupSpy).toHaveBeenCalledTimes(1); expect(consoleSpy).toHaveBeenNthCalledWith(1, `${level}: ${message}`); }); test(`${level} should log a console group for a message and status`, () => { log(level, message, status); expect(groupSpy).toHaveBeenCalledTimes(1); expect(consoleSpy).toHaveBeenNthCalledWith(1, `${level}: ${message}`); expect(consoleSpy).toHaveBeenNthCalledWith( 2, `Status Code: ${status.code}, Status Message: ${status.message}`, ); }); test(`${level} should log a console group for a message, status and token`, () => { log(level, message, status, token); expect(groupSpy).toHaveBeenCalledTimes(1); expect(consoleSpy).toHaveBeenNthCalledWith(1, `Request Token: ${token}`); expect(consoleSpy).toHaveBeenNthCalledWith(2, `${level}: ${message}`); expect(consoleSpy).toHaveBeenNthCalledWith( 3, `Status Code: ${status.code}, Status Message: ${status.message}`, ); }); }); <file_sep>/* eslint-env jest */ import JSBI from 'jsbi'; import { setInt64, getInt64, getUint64, setUint64 } from '../../src/utils/int'; describe('codec: int64 / uint64', () => { describe.each([ ['ZERO', 0], ['ONE', 1], ['MINUS_ONE', -1], ['X_FF', 0xff], ['MINUS_X_FF', -0xff], ['INT32_MAX', 0x7fffffff], ['INT32_MIN', -0x7fffffff - 1], ['MAX_SAFE_INTEGER', Number.MAX_SAFE_INTEGER], ['MIN_SAFE_INTEGER', Number.MIN_SAFE_INTEGER], ['MAX_SAFE_INTEGER as String', Number.MAX_SAFE_INTEGER.toString()], ['MIN_SAFE_INTEGER as String', Number.MIN_SAFE_INTEGER.toString()], ['positive int64 as BigInt', BigInt(Number.MAX_SAFE_INTEGER + 1)], ['positive int64 as Number', Number.MAX_SAFE_INTEGER + 1], ['positive int64 as String', (Number.MAX_SAFE_INTEGER + 1).toString()], ['negative int64 as BigInt', BigInt(Number.MIN_SAFE_INTEGER - 1)], ['negative int64 as Number', Number.MIN_SAFE_INTEGER - 1], ['negative int64 as String', (Number.MIN_SAFE_INTEGER - 1).toString()], ])('int 64', (name, value) => { test(`sets and gets ${name} ${value}`, () => { const b = new Uint8Array(8); const view = new DataView(b.buffer); setInt64(view, 0, value); expect(getInt64(view, 0, false)).toEqual(BigInt(value)); }); test(`sets and gets ${name} ${value} as JSBI when forced`, () => { const b = new Uint8Array(8); const view = new DataView(b.buffer); setInt64(view, 0, value); const result = typeof value === 'bigint' ? value.toString() : value; expect(getInt64(view, 0, true)).toEqual(JSBI.BigInt(result)); }); test(`sets and gets ${name} ${value} as JSBI when BigInt not available`, () => { const b = new Uint8Array(8); const view = new DataView(b.buffer); // @ts-expect-error This is for testing DataViews that do not implement int64 view.getBigInt64 = undefined; setInt64(view, 0, value); const result = typeof value === 'bigint' ? value.toString() : value; expect(getInt64(view, 0, false)).toEqual(JSBI.BigInt(result)); }); }); describe.each([ ['ZERO', 0], ['ONE', 1], ['X_FF', 0xff], ['INT32_MAX', 0x7fffffff], ['MAX_SAFE_INTEGER', Number.MAX_SAFE_INTEGER], ['positive int64 as BigInt', BigInt(Number.MAX_SAFE_INTEGER + 1)], ['positive int64 as Number', Number.MAX_SAFE_INTEGER + 1], ['positive int64 as String', (Number.MAX_SAFE_INTEGER + 1).toString()], ])('uint 64', (name, value) => { test(`sets and gets ${name} ${value}`, () => { const b = new Uint8Array(8); const view = new DataView(b.buffer); setUint64(view, 0, value); expect(getUint64(view, 0, false)).toEqual(BigInt(value)); }); test(`sets and gets ${name} ${value} as JSBI when forced`, () => { const b = new Uint8Array(8); const view = new DataView(b.buffer); setUint64(view, 0, value); const result = typeof value === 'bigint' ? value.toString() : value; expect(getUint64(view, 0, true)).toEqual(JSBI.BigInt(result)); }); test(`sets and gets ${name} ${value} as JSBI when BigInt not available`, () => { const b = new Uint8Array(8); const view = new DataView(b.buffer); // @ts-expect-error This is for testing DataViews that do not implement int64 view.getBigUint64 = undefined; setUint64(view, 0, value); const result = typeof value === 'bigint' ? value.toString() : value; expect(getUint64(view, 0, false)).toEqual(JSBI.BigInt(result)); }); }); describe.each([ ['NaN', NaN], ['NaN as String', 'NaN'], ['UNDEFINED', undefined], ['UNDEFINED as String', 'undefined'], ])('edge cases', (name, value) => { test(`int64 sets and gets ${name} ${value}`, () => { const b = new Uint8Array(8); const view = new DataView(b.buffer); // @ts-expect-error So that we can test undefined setInt64(view, 0, value); expect(getInt64(view, 0, false)).toEqual(BigInt(0)); }); test(`uint64 sets and gets ${name} ${value}`, () => { const b = new Uint8Array(8); const view = new DataView(b.buffer); // @ts-expect-error So that we can test undefined setUint64(view, 0, value); expect(getUint64(view, 0, false)).toEqual(BigInt(0)); }); }); }); <file_sep>/* eslint-disable @typescript-eslint/prefer-for-of */ // Allow usage of for loops, since here performance is paramount // Copyright (c) 2018, Arista Networks, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import { PlainObject } from '../../types'; import { BaseType } from '../../types/neat'; import { Bool, Float64, Int, Nil, Str } from './NeatTypes'; export function createBaseType(value: unknown): BaseType { const type = typeof value; if (type === 'number') { const decimals = String(value).split('.'); if (decimals.length > 1) { return new Float64(value); } return new Int(value); } if (type === 'boolean') { return new Bool(value); } if (type === 'string') { return new Str(value); } if (value !== null && type === 'object') { let proto = value; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } if (Object.getPrototypeOf(value) === proto) { // eslint-disable-next-line @typescript-eslint/no-use-before-define return createTypedMap(value as PlainObject<unknown>); } } return new Nil(); } export function createTypedMap(object: PlainObject<unknown>): Map<BaseType, BaseType> { const map = new Map(); const keys = Object.keys(object); for (let i = 0; i < keys.length; i += 1) { const key = keys[i]; const value = object[key]; const keyType = createBaseType(key); const valueType = createBaseType(value); map.set(keyType, valueType); } return map; } <file_sep>import { EpochTimestamp, PathElements, Timestamp } from 'a-msgpack'; import { CloudVisionDatapoint, CloudVisionNotification } from './notifications'; import { CloudVisionParams, DatasetObject, WsCommand } from './params'; /** * Please refer to the [[CloudVisionNotification]] definition. */ export type PublishNotification<K = unknown, V = unknown> = CloudVisionNotification< PathElements, Timestamp, CloudVisionDatapoint<K, V>[], K[] >; /** * The request type of a publish command. * * @dataset is the root of the path. * @notifications is the data to write to. For the type */ export interface PublishRequest { dataset: DatasetObject; notifications: PublishNotification[]; } export interface BatchPublishRequest { dataset: DatasetObject; notifications: { [path: string]: PublishNotification[]; }; } export interface PublishCallback { (success: boolean, err?: string): void; } /** * There are a number of options you can supply which limit the scope of * the [[Query]]. Options are passed as an object, where the key is the * name of the option and the value is the value for that option. * * There are different combinations of options that are valid, each of them is * listed below. * * @example * ```typescript * * // Range query (returns one or more data points) * { * start: 1505760134000, * end: 1505760184000, * } * * // Point in time query (returns exactly one data point) * { * end: 1505760184000, * } * * // Limit query (returns `versions` + 1 number of data points) * { * versions: 1, * end: 1505760184000, * } * ``` */ export interface Options { end?: EpochTimestamp; start?: EpochTimestamp; versions?: number; } export interface CloudVisionPublishRequest { batch: PublishRequest | BatchPublishRequest; sync: boolean; } export interface ServiceRequest { body: {}; method: string; service: string; } export interface CloudVisionQueryMessage { command: WsCommand; params: CloudVisionParams | CloudVisionPublishRequest | ServiceRequest; token: string; } <file_sep>import { DatasetParams, NotifCallback, Options, PublishCallback, PublishRequest, Query, QueryParams, SearchOptions, SearchParams, ServiceRequest, SubscriptionIdentifier, } from '../types'; import Wrpc from './Wrpc'; import { ALL_DATASET_TYPES, APP_DATASET_TYPE, CLOSE, CONFIG_DATASET_TYPE, DEVICES_DATASET_ID, DEVICE_DATASET_TYPE, GET, GET_AND_SUBSCRIBE, GET_DATASETS, GET_REGIONS_AND_CLUSTERS, ID, PUBLISH, SEARCH, SEARCH_SUBSCRIBE, SERVICE_REQUEST, SUBSCRIBE, } from './constants'; import { makeNotifCallback, makePublishCallback, sanitizeOptions, sanitizeSearchOptions, validateOptions, validateQuery, } from './utils'; /** * The Connector uses WebSocket to enable transmission of data over an * open connection with the CloudVision API server. * It supports subscriptions, which allows clients to receive streaming * updates as data changes in real-time. */ export default class Connector extends Wrpc { public static CLOSE: typeof CLOSE = CLOSE; public static DEVICES_DATASET_ID: typeof DEVICES_DATASET_ID = DEVICES_DATASET_ID; public static GET_DATASETS: typeof GET_DATASETS = GET_DATASETS; public static GET: typeof GET = GET; public static GET_AND_SUBSCRIBE: typeof GET_AND_SUBSCRIBE = GET_AND_SUBSCRIBE; public static ID: typeof ID = ID; public static PUBLISH: typeof PUBLISH = PUBLISH; public static SEARCH_SUBSCRIBE: typeof SEARCH_SUBSCRIBE = SEARCH_SUBSCRIBE; public static SEARCH: typeof SEARCH = SEARCH; public static SERVICE_REQUEST: typeof SERVICE_REQUEST = SERVICE_REQUEST; public static SUBSCRIBE: typeof SUBSCRIBE = SUBSCRIBE; /** * Close multiple subscriptions in one `close` call. The subscription * identifier return in the `subscribe` call along with the close function * can be passed in here to close the subscription together with others. * * @example * ```typescript * * const query = [{ * dataset: { * type: 'app', * name: 'analytics' * }, * paths: [{ * path_elements: ['events', 'activeEvents'], * }], * }]; * const handleResponse = (err, res) => {...}; * * // Send the request * const subscriptionCloseFn = connector.subscribe(query, handleResponse); * * // Close the subscription via `closeSubscriptions` * const closeSubscriptions([subscriptionCloseFn.identifier]); * ``` */ public closeSubscriptions( subscriptions: SubscriptionIdentifier[], callback: NotifCallback, ): string | null { return this.closeStreams(subscriptions, makeNotifCallback(callback)); } /** * Returns all notifications that match the given [[Query]] and [[Options]], in * addition to subscribing to updates. This will return notifications as * new updates to the data requested come in. * * A `getAndSubscribe` is done in such a way that no notifications are lost. * Before doing a `get`, a `subscribe` is initiated and we wait for an active * status message to be returned before initiating a `get`. This means no notifications * are missed, but there is a chance of duplicate notifications. * * @example * ```typescript * * const query = [{ * dataset: { * type: 'app', * name: 'analytics' * }, * paths: [{ * path_elements: ['events', 'activeEvents'], * }], * }]; * const options = { * start: 1504113817725, * end: 1504113917725, * }; * const handleResponse = (err, res) => {...}; * * // open the stream * const closeSubscription = connector.getAndSubscribe( * query, handleResponse, options); * * closeSubscription(); // close the stream when finished * ``` */ public getAndSubscribe( query: Query, callback: NotifCallback, options: Options, ): SubscriptionIdentifier | null { if (!validateQuery(query, callback)) { return null; } if (!validateOptions(options, callback)) { return null; } const sanitizedOptions = sanitizeOptions(options); const params: QueryParams = { query, start: sanitizedOptions.start, end: sanitizedOptions.end, versions: sanitizedOptions.versions, }; return this.stream(GET_AND_SUBSCRIBE, params, makeNotifCallback(callback)); } /** * Returns a list of apps (datasets with type == 'app'). */ public getApps(callback: NotifCallback): string | null { const appType: typeof APP_DATASET_TYPE[] = [APP_DATASET_TYPE]; const params: DatasetParams = { types: appType }; return this.get(GET_DATASETS, params, makeNotifCallback(callback)); } /** * Returns a list of configs (datasets with type == 'config'). */ public getConfigs(callback: NotifCallback): string | null { const configType: typeof CONFIG_DATASET_TYPE[] = [CONFIG_DATASET_TYPE]; const params: DatasetParams = { types: configType }; return this.get(GET_DATASETS, params, makeNotifCallback(callback)); } /** * Returns a list of datasets (datasets with type 'app', 'config' or 'device'). */ public getDatasets(callback: NotifCallback): string | null { const params: DatasetParams = { types: ALL_DATASET_TYPES }; return this.get(GET_DATASETS, params, makeNotifCallback(callback)); } /** * Returns a list of devices (datasets with type == 'device'). */ public getDevices(callback: NotifCallback): string | null { const deviceType: typeof DEVICE_DATASET_TYPE[] = [DEVICE_DATASET_TYPE]; const params: DatasetParams = { types: deviceType }; return this.get(GET_DATASETS, params, makeNotifCallback(callback)); } /** * Returns a list of regions and associated clusters. */ public getRegionsAndClusters(callback: NotifCallback): string | null { return this.get(GET_REGIONS_AND_CLUSTERS, {}, makeNotifCallback(callback)); } /** * Returns all notifications that match the given query and options. * * @example * ```typescript * * const query = [{ * dataset: { * type: 'app', * name: 'analytics' * }, * paths: [{ * path_elements: ['events', 'activeEvents'], * }], * }]; * const options = { * start: 1504113817725, * end: 1504113917725, * }; * const handleResponse = (err, res) => {...}; * * // Send the request * connector.getWithOptions(query, handleResponse, options); * ``` */ public getWithOptions( query: Query | typeof DEVICES_DATASET_ID, callback: NotifCallback, options: Options, ): string | null { if (query === DEVICES_DATASET_ID) { this.getDatasets(callback); return null; } if (!validateQuery(query, callback)) { return null; } if (!validateOptions(options, callback)) { return null; } const { start, end, versions } = sanitizeOptions(options); const params: QueryParams = { query, start, end, versions, }; return this.get(GET, params, makeNotifCallback(callback, options)); } public runService(request: ServiceRequest, callback: NotifCallback): void { this.requestService(request, makeNotifCallback(callback)); } public runStreamingService( request: ServiceRequest, callback: NotifCallback, ): SubscriptionIdentifier | null { if (!request) { callback('`request` param cannot be empty'); return null; } return this.stream(SERVICE_REQUEST, request, makeNotifCallback(callback)); } public searchWithOptions( query: Query, callback: NotifCallback, options: Options & SearchOptions, ): string | null { if (!validateQuery(query, callback, true)) { return null; } if (!validateOptions(options, callback)) { return null; } const { start, end } = sanitizeOptions(options); const sanitizedSearchOptions = sanitizeSearchOptions(options); const params: SearchParams = { query, start, end, search: sanitizedSearchOptions.search, searchType: sanitizedSearchOptions.searchType, }; return this.search(params, makeNotifCallback(callback, options)); } public searchSubscribe( query: Query, callback: NotifCallback, options: SearchOptions = { search: '' }, ): SubscriptionIdentifier | null { if (!validateQuery(query, callback, true)) { return null; } const sanitizedSearchOptions = sanitizeSearchOptions(options); return this.stream( SEARCH_SUBSCRIBE, { query, search: sanitizedSearchOptions.search, searchType: sanitizedSearchOptions.searchType, }, makeNotifCallback(callback), ); } /** * Creates a subscription to the given query, which will return * notifications as they happen. Note that this will not return any * historical data. The first update that is sent will be when the state * of the data in the query changes. * * @example * ```typescript * * const query = [{ * dataset: { * type: 'app', * name: 'analytics' * }, * paths: [{ * path_elements: ['events', 'activeEvents'], * }], * }]; * const handleResponse = (err, res) => {...}; * * // Send the request * const subscriptionCloseFn = connector.subscribe(query, handleResponse); * ``` */ public subscribe(query: Query, callback: NotifCallback): SubscriptionIdentifier | null { if (!validateQuery(query, callback)) { return null; } return this.stream(SUBSCRIBE, { query }, makeNotifCallback(callback)); } /** * Write data to the CloudVision API server, where the update is a * series of notifications of a certain dataset. * * The writeSync operation is synchronous. */ public writeSync(publishRequest: PublishRequest, callback: PublishCallback): void { this.publish( { sync: true, batch: { dataset: publishRequest.dataset, notifications: publishRequest.notifications, }, }, makePublishCallback(callback), ); } } <file_sep>import { Bool, Float32, Float64, Int, Nil, Pointer, Str } from '../src/neat/NeatTypes'; export type Element = string | number | Record<string, unknown> | {} | unknown[] | boolean; export type PathElements = readonly Element[]; /** * The epoch timestamp in (milliseconds) */ export type EpochTimestamp = number; export interface Timestamp { seconds: number; nanos?: number; } export type BaseType = Bool | Float32 | Float64 | Int | Nil | Pointer | Str | Map<unknown, unknown>; export type NeatType = BaseType | Element; export interface BasicNeatType { type: Bool['type'] | Float32['type'] | Float64['type'] | Int['type'] | Nil['type'] | Str['type']; value: unknown; } export type NeatTypeClass = | typeof Bool | typeof Float32 | typeof Float64 | typeof Int | typeof Nil | typeof Pointer | typeof Str; <file_sep>import { ContextCommand, RequestContext, WsCommand } from '../types'; export interface InstrumentationConfig { commands: WsCommand[]; start(context: RequestContext): void; info(context: RequestContext): void; end(context: RequestContext): void; } interface Info { error?: string; message?: string; } // Use empty function as a default placeholder /* istanbul ignore next */ function emptyFunction(): void {} // eslint-disable-line @typescript-eslint/no-empty-function export default class Instrumentation { private enableInstrumentation = false; private instrumentedCommands: WsCommand[]; private startFunction: (context: RequestContext) => void; private infoFunction: (context: RequestContext, info: Info) => void; private endFunction: (context: RequestContext) => void; public constructor(config?: InstrumentationConfig) { if (config) { this.enableInstrumentation = true; } this.instrumentedCommands = config ? config.commands : []; this.startFunction = config ? config.start : emptyFunction; this.infoFunction = config ? config.info : emptyFunction; this.endFunction = config ? config.end : emptyFunction; } public callStart(command: ContextCommand, context: RequestContext): void { if (this.enableInstrumentation && this.instrumentedCommands.includes(command as WsCommand)) { this.startFunction(context); } } public callInfo(command: ContextCommand, context: RequestContext, info: Info): void { if (this.enableInstrumentation && this.instrumentedCommands.includes(command as WsCommand)) { this.infoFunction(context, info); } } public callEnd(command: ContextCommand, context: RequestContext): void { if (this.enableInstrumentation && this.instrumentedCommands.includes(command as WsCommand)) { this.endFunction(context); } } } <file_sep>import { Operation } from '@generated/arista/subscriptions/subscriptions'; import type { GrpcSource, ResourceRpcOptions } from '@types'; import { map, merge, Observable, partition } from 'rxjs'; import { grpc } from '@arista/grpc-web'; import { fromGrpcSource } from '../grpc'; import { INITIAL_SYNC_COMPLETE_MESSAGE } from './constants'; import { isStreamResponse } from './utils'; export * from '@generated/arista/subscriptions/subscriptions'; export * from './constants'; export * from './operators'; export * from './utils'; /** * Calls `fromGrpcSource` and adds some resource specific handling for stream control messages that * do not contain data, but are sent as data messages. * This implements the special handleing for the `INITIAL_SYNC_COMPLETE` message. * * @param methodDescriptor The GRPC service method definition to be queried. * @param options Options to pass to the GRPC call. */ export function fromResourceGrpcSource< Req extends grpc.ProtobufMessage, Res extends grpc.ProtobufMessage, >( methodDescriptor: grpc.MethodDefinition<Req, Res>, options: ResourceRpcOptions<Req, Res>, ): Observable<GrpcSource<Res>> { return fromGrpcSource(methodDescriptor, options).pipe( // Move `INITIAL_SYNC_COMPLETE` response to control message stream map(({ data$, message$ }): GrpcSource<Res> => { const [initialSyncCompleteData$, otherData$] = partition(data$, (response) => { return isStreamResponse(response) && response.type === Operation.INITIAL_SYNC_COMPLETE; }); const initialSyncCompleteMessage$ = initialSyncCompleteData$.pipe( map(() => INITIAL_SYNC_COMPLETE_MESSAGE), ); return { data$: otherData$, message$: merge(message$, initialSyncCompleteMessage$), }; }), ); } <file_sep>import { NeatType, PathElements } from 'a-msgpack'; import { CLOSE, GET, GET_AND_SUBSCRIBE, GET_DATASETS, GET_REGIONS_AND_CLUSTERS, PUBLISH, SEARCH, SEARCH_SUBSCRIBE, SEARCH_TYPE_ANY, SEARCH_TYPE_IP, SEARCH_TYPE_MAC, SERVICE_REQUEST, SUBSCRIBE, } from '../src/constants'; export type GetCommand = | typeof GET | typeof GET_DATASETS | typeof GET_REGIONS_AND_CLUSTERS | typeof SEARCH; /** @deprecated: Use `GetCommand`. */ export type GetCommands = GetCommand; export type StreamCommand = | typeof SERVICE_REQUEST | typeof SEARCH_SUBSCRIBE | typeof SUBSCRIBE | typeof GET_AND_SUBSCRIBE; /** @deprecated: Use `StreamCommand`. */ export type StreamCommands = StreamCommand; export type WsCommand = GetCommand | StreamCommand | typeof CLOSE | typeof PUBLISH; export type SearchType = typeof SEARCH_TYPE_ANY | typeof SEARCH_TYPE_IP | typeof SEARCH_TYPE_MAC; export interface PathObject { path_elements: PathElements; // eslint-disable-line @typescript-eslint/naming-convention keys?: readonly NeatType[]; } export interface SearchOptions { search: string; searchType?: SearchType; } export interface DatasetObject { name: string; type: string; parent?: DatasetObject; } export interface QueryObject { dataset: DatasetObject; paths: PathObject[]; } /** * A query is a list of one or more objects. Each of these objects has two keys: * **dataset** (an object with keys **type** and **name**), and **paths** * (an array of path objects (with keys **type**, **path** and **keys**). * * Dataset object: * type (string): can be 'device' or 'app'. The 'device' type is for physical * devices (switches), whereas 'app' is for any analytics engines. * name (string): the name of the dataset. * * Path object: * path_elements (array): An array of path elements representing the path to * the requested data. * keys (object): an optional property so that only data with such keys are returned. * Sample keys object: { 'any_custom_key': { key: 'speed'} } * * @example * ```typescript * * [{ * dataset: { * type: 'app', * name: 'analytics' * }, * paths: [{ * path_elements: ['events', 'activeEvents'], * }], * }, { * dataset: { * type: 'device', * name: 'JAS11070002' * }, * paths: [{ * path_elements: ['Logs', 'var', 'log', 'messages'], * keys: { * logMessage: { * key: 'text', * }, * }, * }], * }] * ``` */ export type Query = QueryObject[]; export interface QueryParams { query: Query; start?: number; end?: number; versions?: number; } export interface DatasetParams { types?: string[]; } export interface SearchParams { query: Query; search: string; searchType: SearchType; end?: number; start?: number; } /** * Parameters passed to the [[Connector.close]] request. */ export interface CloseParams { [token: string]: boolean; } export type CloudVisionParams = CloseParams | DatasetParams | QueryParams | SearchParams; <file_sep>// Copyright (c) 2018, Arista Networks, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import { v4 as uuidv4 } from 'uuid'; import { CloseParams, CloudVisionBatchedResult, CloudVisionMessage, CloudVisionMetaData, CloudVisionParams, CloudVisionPublishRequest, CloudVisionResult, CloudVisionStatus, ConnectionCallback, EventCallback, GetCommand, NotifCallback, RequestContext, ServiceRequest, StreamCommand, SubscriptionIdentifier, WsCommand, } from '../types'; import Parser from './Parser'; import { ACTIVE_CODE, CLOSE, CONNECTED, DISCONNECTED, EOF, EOF_CODE, ERROR, GET_REQUEST_COMPLETED, ID, PUBLISH, SEARCH, SERVICE_REQUEST, } from './constants'; import Emitter from './emitter'; import Instrumentation, { InstrumentationConfig } from './instrumentation'; import { log } from './logger'; import { createCloseParams, toBinaryKey, validateResponse } from './utils'; /** * Options passed to the constructor, that configure some global options */ interface ConnectorOptions { batchResults: boolean; debugMode: boolean; instrumentationConfig?: InstrumentationConfig; } /** * Wraps a given WebSocket with CloudVision API streaming and data querying * methods. */ export default class Wrpc { public static CONNECTED: typeof CONNECTED = CONNECTED; public static DISCONNECTED: typeof DISCONNECTED = DISCONNECTED; private connectionEvents: Emitter; private connectorOptions: ConnectorOptions; private events: Emitter; public isRunning: boolean; private Parser: typeof Parser; private instrumentation: Instrumentation; private ws!: WebSocket; private WebSocket: typeof WebSocket; public constructor( options: ConnectorOptions = { batchResults: true, debugMode: false, }, websocketClass = WebSocket, parser = Parser, ) { this.connectorOptions = options; this.isRunning = false; this.connectionEvents = new Emitter(); // State of the websocket connection this.events = new Emitter(); this.WebSocket = websocketClass; this.Parser = parser; this.instrumentation = new Instrumentation(options.instrumentationConfig); } public get websocket(): WebSocket { return this.ws; } public get connectionEmitter(): Emitter { return this.connectionEvents; } public get eventsEmitter(): Emitter { return this.events; } /** * PRIVATE METHOD * Sends the `get` command along with params to the API. The response is * received via the provided callback function. * This request encompasses only historical data, so the callback is * immediately unbound once the data is received. * * **NOTE**: This method does not check if the WebSocket is correctly * initialized or connected. */ private callCommand( command: WsCommand, params: CloudVisionParams | CloudVisionPublishRequest | ServiceRequest, callback: NotifCallback, ): string | null { if (!this.isRunning) { callback('Connection is down'); return null; } const token: string = uuidv4(); const requestContext = { command, encodedParams: toBinaryKey(params), token }; const callbackWithUnbind = this.makeCallbackWithUnbind(token, callback); this.events.bind(token, requestContext, callbackWithUnbind); this.sendMessageOrError(token, command, params, requestContext); return token; } /** * Cleans up all event emitters. * All bound callbacks will be unbound. */ public cleanUpConnections(): void { this.events.close(); } /** * Closes connection to the server and cleans up all event emitters. * All bound callbacks will be unbound. */ public close(): void { this.closeWs(new CloseEvent('close')); this.connectionEvents.close(); this.ws.close(); } private closeWs(event: CloseEvent): void { this.isRunning = false; this.cleanUpConnections(); this.connectionEvents.emit('connection', Wrpc.DISCONNECTED, event); } private closeCommand( streams: SubscriptionIdentifier[] | SubscriptionIdentifier, closeParams: CloseParams, callback: NotifCallback, ): string { const closeToken: string = uuidv4(); const requestContext: RequestContext = { command: CLOSE, encodedParams: toBinaryKey(streams), token: closeToken, }; const callbackWithUnbind = this.makeCallbackWithUnbind(closeToken, callback); this.events.bind(closeToken, requestContext, callbackWithUnbind); try { this.sendMessage(closeToken, CLOSE, requestContext, closeParams); } catch (err) { log(ERROR, err as string); callback(err as string, undefined, undefined, closeToken); } return closeToken; } /** * Closes multiple streams in one `close` call. */ public closeStreams(streams: SubscriptionIdentifier[], callback: NotifCallback): string | null { const closeParams = createCloseParams(streams, this.events); if (closeParams) { return this.closeCommand(streams, closeParams, callback); } return null; } /** * Closes one single stream. */ public closeStream(stream: SubscriptionIdentifier, callback: NotifCallback): string | null { const closeParams = createCloseParams(stream, this.events); if (closeParams) { return this.closeCommand(stream, closeParams, callback); } return null; } /** * Subscribes a callback to connection events. * The callback can receive either `Wrpc.CONNECTED or `Wrpc.DISCONNECTED`. */ public connection(callback: ConnectionCallback): () => void { const connectionCallback = ( _requestContext: RequestContext, connEvent: string, wsEvent: Event, ): void => { callback(connEvent, wsEvent); }; this.connectionEvents.bind( 'connection', { command: 'connection', encodedParams: '', token: '' }, connectionCallback, ); return (): void => { this.connectionEvents.unbind('connection', connectionCallback); }; } /** * Sends the command along with the params to the API, if the WebSocket is * connected. The response is received via the provided callback function. */ public get( command: GetCommand, params: CloudVisionParams, callback: NotifCallback, ): string | null { return this.callCommand(command, params, callback); } private makeCallbackWithUnbind(token: string, callback: NotifCallback): EventCallback { const callbackWithUnbind = ( requestContext: RequestContext, err: string | null, result?: CloudVisionBatchedResult | CloudVisionResult, status?: CloudVisionStatus, ): void => { if (err) { // Unbind callback when any error message is received this.events.unbind(token, callbackWithUnbind); this.instrumentation.callInfo(requestContext.command, requestContext, { error: err, }); } this.instrumentation.callEnd(requestContext.command, requestContext); callback(err, result, status, token, requestContext); }; return callbackWithUnbind; } /** * Writes data in params to the CloudVision API. It receives one message via * the provided callback, to indicate whether the write is successful or not. */ public publish(params: CloudVisionPublishRequest, callback: NotifCallback): string | null { return this.callCommand(PUBLISH, params, callback); } /** * Send a service request command to the CloudVision API */ public requestService(request: ServiceRequest, callback: NotifCallback): string | null { return this.callCommand(SERVICE_REQUEST, request, callback); } /** * Run connects connector to the specified url */ public run(url: string): void { this.runWithWs(new this.WebSocket(url)); } /** * PRIVATE METHOD * Sets the specified WebSocket on the class and binds `onopen`, `onclose`, and * `onmessage` listeners. * * - onopen: The `Wrpc.CONNECTED` event is emitted, and the WebSocket is set * to isRunning equals `true`. * - onclose: The `Wrpc.DISCONNECTED` event is emitted, and the WebSocket is * set to isRunning equals `false`. * - onmessage: The message is parsed and the event type `msg.token` is * emitted. This results in the calling of all callbacks bound to that event * type. */ private runWithWs(ws: WebSocket): void { this.ws = ws; this.ws.onopen = (event): void => { if (!this.isRunning) { this.isRunning = true; this.connectionEvents.emit('connection', Wrpc.CONNECTED, event); } }; this.ws.onclose = (event): void => { this.closeWs(event); }; this.ws.onmessage = (event): void => { if (typeof event.data !== 'string') { // messages that aren't strings are invalid return; } let msg: CloudVisionMessage; try { msg = this.Parser.parse(event.data, this.connectorOptions.batchResults); if (this.connectorOptions.debugMode) { // Used for debugging self.postMessage( { response: msg, source: ID, timestamp: Date.now(), }, '*', ); } } catch (err) { log(ERROR, err as string); return; } if (!msg || !msg.token) { log(ERROR, 'No message body or message token'); return; } const { error, status, token } = msg; if (error) { this.events.emit(token, error, msg.result, status); return; } validateResponse(msg.result, status, token, this.connectorOptions.batchResults); this.events.emit(token, null, msg.result, status); if ( msg.result?.metadata && (msg.result.metadata as CloudVisionMetaData<string>)[GET_REQUEST_COMPLETED] === EOF ) { this.events.emit(token, null, null, { message: GET_REQUEST_COMPLETED, code: EOF_CODE }); } }; } public search(params: CloudVisionParams, callback: NotifCallback): string | null { return this.callCommand(SEARCH, params, callback); } /** * Sends a message on the WebSocket with the proper parameters, so that the * CloudVision API can respond accordingly. */ private sendMessage( token: string, command: WsCommand, requestContext: RequestContext, params: CloudVisionParams | CloudVisionPublishRequest | ServiceRequest, ): void { if (this.connectorOptions.debugMode) { // Used for debugging self.postMessage( { request: { token, command, params, }, source: ID, timestamp: Date.now(), }, '*', ); } this.instrumentation.callStart(command, requestContext); this.ws.send( this.Parser.stringify({ token, command, params, }), ); } private sendMessageOrError( token: string, command: WsCommand, params: CloudVisionParams | CloudVisionPublishRequest | ServiceRequest, requestContext: RequestContext, ): void { try { this.sendMessage(token, command, requestContext, params); } catch (err) { log(ERROR, err as string); // notifAndUnBindCallback(err, undefined, undefined, token); this.events.emit(token, err, undefined, undefined); } } /** * Sends the command along with the params to the API, which creates a * subscriptions on the server. It receives a stream of messages via the * provided callback, as these messages get produced. * The client can close the stream with returned close function, or use the * attached identifier (`closeFunction.identifier`) to close multiple streams * at once via `closeStream`. */ public stream( command: StreamCommand, params: CloudVisionParams | ServiceRequest, callback: NotifCallback, ): SubscriptionIdentifier | null { if (!this.isRunning) { callback('Connection is down'); return null; } const token = uuidv4(); const callerRequestContext = { command, encodedParams: toBinaryKey(params), token }; const callbackWithUnbind: EventCallback = ( requestContext: RequestContext, err: string | null, result?: CloudVisionBatchedResult | CloudVisionResult, status?: CloudVisionStatus, ): void => { if (err) { // Unbind callback when any error message is received. // No need to send close to server because it will close them automatically. this.events.unbind(token, callbackWithUnbind); this.instrumentation.callInfo(callerRequestContext.command, callerRequestContext, { error: err, }); this.instrumentation.callEnd(requestContext.command, requestContext); } if (status && status.code === ACTIVE_CODE) { this.instrumentation.callInfo(callerRequestContext.command, callerRequestContext, { message: 'stream active', }); } callback(err, result, status, token, requestContext); }; this.events.bind(token, callerRequestContext, callbackWithUnbind); this.sendMessageOrError(token, command, params, callerRequestContext); return { token, callback: callbackWithUnbind }; } } <file_sep>/** * @jest-environment jsdom */ // Copyright (c) 2018, Arista Networks, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Parser from '../src/Parser'; import Wrpc from '../src/Wrpc'; import { ACTIVE_CODE, CLOSE, EOF, EOF_CODE, GET, GET_DATASETS, GET_REQUEST_COMPLETED, ID, PUBLISH, SEARCH, SEARCH_SUBSCRIBE, SERVICE_REQUEST, SUBSCRIBE, } from '../src/constants'; import { log } from '../src/logger'; import { toBinaryKey } from '../src/utils'; import { CloudVisionParams, CloudVisionQueryMessage, CloudVisionStatus, NotifCallback, QueryParams, RequestContext, StreamCommand, SubscriptionIdentifier, WsCommand, CloudVisionMetaData, } from '../types'; interface PolymorphicCommandFunction { (command: WsCommand, params: CloudVisionParams, callback: NotifCallback): string; } interface CommandFunction { (p: CloudVisionParams, cb: NotifCallback): string; } interface PostedMessage { source: string; timestamp: number; request?: CloudVisionQueryMessage; response?: | { result: { dataset: string }; token: string; } | { error: string; status: CloudVisionStatus; token: string; }; } type WrpcMethod = 'get' | 'publish' | 'requestService' | 'search'; const query: QueryParams = { query: [] }; jest.mock('../src/Parser', () => ({ parse: (res: string) => JSON.parse(res), stringify: (msg: CloudVisionQueryMessage) => JSON.stringify(msg), })); jest.mock('../src/logger', () => { return { log: jest.fn() }; }); jest.spyOn(console, 'groupCollapsed').mockImplementation(); function stringifyMessage(msg: Record<string, unknown>) { return JSON.stringify(msg); } function createRequestContext(command: WsCommand, token: string, params: unknown): RequestContext { return { command, token, encodedParams: toBinaryKey(params), }; } describe('open/close/connection', () => { let wrpc: Wrpc; let ws: WebSocket; let eventsEmitterSpy: jest.SpyInstance; let eventsEmitterUnbindSpy: jest.SpyInstance; let eventsEmitterBindSpy: jest.SpyInstance; let eventsEmitterCloseSpy: jest.SpyInstance; let connectionEmitterCloseSpy: jest.SpyInstance; let connectionEmitterSpy: jest.SpyInstance; let connectionEmitterUnbindSpy: jest.SpyInstance; let onCloseSpy: jest.SpyInstance; const connectionSpy = jest.fn(); beforeEach(() => { wrpc = new Wrpc(); wrpc.run('ws://localhost:8080'); ws = wrpc.websocket; connectionSpy.mockClear(); onCloseSpy = jest.spyOn(ws, 'close'); eventsEmitterSpy = jest.spyOn(wrpc.eventsEmitter, 'emit'); eventsEmitterBindSpy = jest.spyOn(wrpc.eventsEmitter, 'bind'); eventsEmitterUnbindSpy = jest.spyOn(wrpc.eventsEmitter, 'unbind'); eventsEmitterCloseSpy = jest.spyOn(wrpc.eventsEmitter, 'close'); connectionEmitterCloseSpy = jest.spyOn(wrpc.connectionEmitter, 'close'); connectionEmitterSpy = jest.spyOn(wrpc.connectionEmitter, 'emit'); connectionEmitterUnbindSpy = jest.spyOn(wrpc.connectionEmitter, 'unbind'); }); test('should set isRunning and emit connection event on WS open messages', () => { wrpc.connection(connectionSpy); ws.dispatchEvent(new MessageEvent('open', {})); expect(connectionEmitterSpy).toHaveBeenCalledTimes(1); expect(connectionEmitterUnbindSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).not.toHaveBeenCalled(); expect(wrpc.isRunning).toBe(true); expect(connectionSpy).toHaveBeenCalledTimes(1); expect(connectionSpy).toHaveBeenCalledWith(Wrpc.CONNECTED, expect.any(Event)); }); test('should not re emit connection event on subsequent WS open messages', () => { wrpc.connection(connectionSpy); ws.dispatchEvent(new MessageEvent('open', {})); ws.dispatchEvent(new MessageEvent('open', {})); expect(connectionEmitterSpy).toHaveBeenCalledTimes(1); expect(connectionEmitterUnbindSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).not.toHaveBeenCalled(); expect(wrpc.isRunning).toBe(true); expect(connectionSpy).toHaveBeenCalledTimes(1); expect(connectionSpy).toHaveBeenCalledWith(Wrpc.CONNECTED, expect.any(Event)); }); test('should close emitters and call close WS on close call and emit disconnection event', () => { wrpc.connection(connectionSpy); ws.dispatchEvent(new MessageEvent('open', {})); connectionEmitterSpy.mockClear(); connectionSpy.mockClear(); wrpc.close(); expect(onCloseSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterCloseSpy).toHaveBeenCalledTimes(1); expect(connectionEmitterCloseSpy).toHaveBeenCalledTimes(1); expect(connectionEmitterSpy).toHaveBeenCalledTimes(1); expect(connectionEmitterSpy).toHaveBeenCalledWith( 'connection', Wrpc.DISCONNECTED, expect.any(CloseEvent), ); expect(connectionEmitterUnbindSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).not.toHaveBeenCalled(); expect(wrpc.connectionEmitter.getEventsMap().size).toBe(0); expect(wrpc.eventsEmitter.getEventsMap().size).toBe(0); expect(wrpc.isRunning).toBe(false); expect(connectionSpy).toHaveBeenCalledTimes(1); expect(connectionSpy).toHaveBeenCalledWith(Wrpc.DISCONNECTED, expect.any(CloseEvent)); }); test('should emit close event on WS close message and emit disconnection event', () => { wrpc.connection(connectionSpy); ws.dispatchEvent(new MessageEvent('open', {})); connectionEmitterSpy.mockClear(); connectionSpy.mockClear(); ws.dispatchEvent(new CloseEvent('close', {})); expect(wrpc.isRunning).toBe(false); expect(eventsEmitterCloseSpy).toHaveBeenCalledTimes(1); expect(connectionEmitterCloseSpy).not.toHaveBeenCalled(); expect(onCloseSpy).not.toHaveBeenCalled(); expect(connectionEmitterSpy).toHaveBeenCalledTimes(1); expect(connectionEmitterSpy).toHaveBeenCalledWith( 'connection', Wrpc.DISCONNECTED, expect.any(CloseEvent), ); expect(connectionSpy).toHaveBeenCalledTimes(1); expect(connectionSpy).toHaveBeenCalledWith(Wrpc.DISCONNECTED, expect.any(CloseEvent)); }); test('should unbind connection event callback', () => { const connectionEventCallback = wrpc.connection(connectionSpy); ws.dispatchEvent(new MessageEvent('open', {})); connectionEmitterSpy.mockClear(); connectionSpy.mockClear(); connectionEventCallback(); expect(connectionEmitterUnbindSpy).toHaveBeenCalledTimes(1); expect(connectionEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).not.toHaveBeenCalled(); expect(wrpc.isRunning).toBe(true); expect(connectionSpy).not.toHaveBeenCalled(); }); }); describe.each<[WsCommand, WrpcMethod, boolean]>([ [GET, 'get', true], [GET_DATASETS, 'get', true], [PUBLISH, 'publish', false], [SEARCH, 'search', false], [SERVICE_REQUEST, 'requestService', false], ])('Call Commands', (command, fn, polymorphic) => { let wrpc: Wrpc; let ws: WebSocket; let sendSpy: jest.SpyInstance; let eventsEmitterSpy: jest.SpyInstance; let eventsEmitterUnbindSpy: jest.SpyInstance; let eventsEmitterBindSpy: jest.SpyInstance; let polymorphicCommandFn: PolymorphicCommandFunction; let commandFn: CommandFunction; const callbackSpy = jest.fn(); const ERROR_MESSAGE = 'error'; const ERROR_STATUS: CloudVisionStatus = { code: 3, message: ERROR_MESSAGE, }; const RESULT = { dataset: 'Dodgers' }; beforeEach(() => { jest.resetAllMocks(); wrpc = new Wrpc(); // @ts-expect-error Easier than to type everything commandFn = wrpc[fn]; // @ts-expect-error Easier than to type everything polymorphicCommandFn = wrpc[fn]; wrpc.run('ws://localhost:8080'); ws = wrpc.websocket; sendSpy = jest.spyOn(ws, 'send'); eventsEmitterSpy = jest.spyOn(wrpc.eventsEmitter, 'emit'); eventsEmitterBindSpy = jest.spyOn(wrpc.eventsEmitter, 'bind'); eventsEmitterUnbindSpy = jest.spyOn(wrpc.eventsEmitter, 'unbind'); }); afterEach(() => { sendSpy.mockClear(); eventsEmitterSpy.mockClear(); eventsEmitterBindSpy.mockClear(); eventsEmitterUnbindSpy.mockClear(); callbackSpy.mockClear(); }); test(`'${fn} + ${command}' should not send message if socket is not running`, () => { let token; if (polymorphic) { token = polymorphicCommandFn.call(wrpc, command, {}, callbackSpy); } else { token = commandFn.call(wrpc, {}, callbackSpy); } expect(callbackSpy).toHaveBeenCalledWith('Connection is down'); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(token).toBe(null); }); test(`'${fn} + ${command}' should send message if socket is running`, () => { ws.dispatchEvent(new MessageEvent('open', {})); let token; if (polymorphic) { token = polymorphicCommandFn.call(wrpc, command, {}, callbackSpy); } else { token = commandFn.call(wrpc, {}, callbackSpy); } if (token) { expect(callbackSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, createRequestContext(command, token, {}), expect.any(Function), ); expect(sendSpy).toHaveBeenCalledTimes(1); expect(sendSpy).toHaveBeenCalledWith( Parser.stringify({ token, command, params: {}, }), ); expect(token).not.toBeNull(); } expect(token).not.toBeNull(); }); test(`'${fn} + ${command}' call callback with error on message that throws a send error`, () => { ws.dispatchEvent(new MessageEvent('open', {})); sendSpy.mockImplementation(() => { throw new Error(ERROR_MESSAGE); }); let token; if (polymorphic) { token = polymorphicCommandFn.call(wrpc, command, {}, callbackSpy); } else { token = commandFn.call(wrpc, {}, callbackSpy); } if (token) { const requestContext = createRequestContext(command, token, {}); expect(log).toHaveBeenCalledTimes(1); expect(sendSpy).toHaveBeenCalledTimes(1); expect(sendSpy).toHaveBeenCalledWith( Parser.stringify({ token, command, params: {}, }), ); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith( new Error(ERROR_MESSAGE), undefined, undefined, token, requestContext, ); expect(eventsEmitterSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); } expect(token).not.toBeNull(); }); test(`'${fn} + ${command}' should call callback and unbind on all errors`, () => { ws.dispatchEvent(new MessageEvent('open', {})); let token; if (polymorphic) { token = polymorphicCommandFn.call(wrpc, command, {}, callbackSpy); } else { token = commandFn.call(wrpc, {}, callbackSpy); } if (token) { const requestContext = createRequestContext(command, token, {}); ws.dispatchEvent( new MessageEvent('message', { data: stringifyMessage({ token, error: ERROR_MESSAGE, status: ERROR_STATUS }), }), ); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith( ERROR_MESSAGE, undefined, ERROR_STATUS, token, requestContext, ); expect(eventsEmitterSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterSpy).toHaveBeenCalledWith(token, ERROR_MESSAGE, undefined, ERROR_STATUS); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterUnbindSpy).toHaveBeenCalledWith(token, expect.any(Function)); expect(sendSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); } expect(token).not.toBeNull(); }); test(`'${fn} + ${command}' should call callback and unbind on all EOF`, () => { const EOF_STATUS: CloudVisionStatus = { code: EOF_CODE }; ws.dispatchEvent(new MessageEvent('open', {})); let token; if (polymorphic) { token = polymorphicCommandFn.call(wrpc, command, {}, callbackSpy); } else { token = commandFn.call(wrpc, {}, callbackSpy); } if (token) { const requestContext = createRequestContext(command, token, {}); ws.dispatchEvent( new MessageEvent('message', { data: stringifyMessage({ token, error: EOF, status: EOF_STATUS }), }), ); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith(EOF, undefined, EOF_STATUS, token, requestContext); expect(eventsEmitterSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterSpy).toHaveBeenCalledWith(token, EOF, undefined, EOF_STATUS); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterUnbindSpy).toHaveBeenCalledWith(token, expect.any(Function)); expect(sendSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); } expect(token).not.toBeNull(); }); test(`'${fn} + ${command}' should call callback on message and not unbind`, () => { ws.dispatchEvent(new MessageEvent('open', {})); let token; if (polymorphic) { token = polymorphicCommandFn.call(wrpc, command, {}, callbackSpy); } else { token = commandFn.call(wrpc, {}, callbackSpy); } if (token) { const requestContext = createRequestContext(command, token, {}); ws.dispatchEvent( new MessageEvent('message', { data: stringifyMessage({ token, result: RESULT }) }), ); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith(null, RESULT, undefined, token, requestContext); expect(eventsEmitterSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterSpy).toHaveBeenCalledWith(token, null, RESULT, undefined); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(sendSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); } expect(token).not.toBeNull(); }); test(`'${fn} + ${command}' should not call callback on message that is not a string`, () => { ws.dispatchEvent(new MessageEvent('open', {})); let token; if (polymorphic) { token = polymorphicCommandFn.call(wrpc, command, {}, callbackSpy); } else { token = commandFn.call(wrpc, {}, callbackSpy); } if (token) { ws.dispatchEvent(new MessageEvent('message', { data: RESULT })); expect(callbackSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, createRequestContext(command, token, {}), expect.any(Function), ); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(sendSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); } expect(token).not.toBeNull(); }); test(`'${fn} + ${command}' should not call callback on message without token`, () => { ws.dispatchEvent(new MessageEvent('open', {})); let token; if (polymorphic) { token = polymorphicCommandFn.call(wrpc, command, {}, callbackSpy); } else { token = commandFn.call(wrpc, {}, callbackSpy); } if (token) { ws.dispatchEvent(new MessageEvent('message', { data: stringifyMessage({ result: RESULT }) })); expect(callbackSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, createRequestContext(command, token, {}), expect.any(Function), ); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(sendSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); } expect(token).not.toBeNull(); }); test(`'${fn} + ${command}' should not call callback on message that throws error`, () => { ws.dispatchEvent(new MessageEvent('open', {})); const result = '{ data: 1'; let token; if (polymorphic) { token = polymorphicCommandFn.call(wrpc, command, {}, callbackSpy); } else { token = commandFn.call(wrpc, {}, callbackSpy); } if (token) { ws.dispatchEvent(new MessageEvent('message', { data: result })); expect(log).toHaveBeenCalledTimes(1); expect(callbackSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, createRequestContext(command, token, {}), expect.any(Function), ); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(sendSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); } expect(token).not.toBeNull(); }); }); describe.each<[WsCommand, WrpcMethod, boolean]>([ [GET_DATASETS, 'get', true], [GET, 'get', true], [PUBLISH, 'publish', false], [SEARCH, 'search', false], [SERVICE_REQUEST, 'requestService', false], ])('Call Commands in debug mode', (command, fn, polymorphic) => { let NOW = 0; let wrpc: Wrpc; let ws: WebSocket; let sendSpy: jest.SpyInstance; let postMessageSpy: jest.SpyInstance; let eventsEmitterSpy: jest.SpyInstance; let eventsEmitterUnbindSpy: jest.SpyInstance; let eventsEmitterBindSpy: jest.SpyInstance; let commandFn: CommandFunction; let polymorphicCommandFn: PolymorphicCommandFunction; const callbackSpy = jest.fn(); const ERROR_MESSAGE = 'error'; const ERROR_STATUS: CloudVisionStatus = { code: 3, message: ERROR_MESSAGE, }; const RESULT = { dataset: 'Dodgers' }; beforeEach(() => { jest.resetAllMocks(); NOW = Date.now(); Date.now = jest.fn(() => NOW); wrpc = new Wrpc({ batchResults: true, debugMode: true, }); // @ts-expect-error Easier than to type everything commandFn = wrpc[fn]; // @ts-expect-error Easier than to type everything polymorphicCommandFn = wrpc[fn]; wrpc.run('ws://localhost:8080'); ws = wrpc.websocket; sendSpy = jest.spyOn(ws, 'send'); postMessageSpy = jest.spyOn(global.window, 'postMessage'); eventsEmitterSpy = jest.spyOn(wrpc.eventsEmitter, 'emit'); eventsEmitterBindSpy = jest.spyOn(wrpc.eventsEmitter, 'bind'); eventsEmitterUnbindSpy = jest.spyOn(wrpc.eventsEmitter, 'unbind'); }); afterEach(() => { sendSpy.mockClear(); postMessageSpy.mockClear(); eventsEmitterSpy.mockClear(); eventsEmitterBindSpy.mockClear(); eventsEmitterUnbindSpy.mockClear(); callbackSpy.mockClear(); }); test(`'${fn} + ${command}' should send message and 'postMessage' to window`, () => { ws.dispatchEvent(new MessageEvent('open', {})); const params: CloudVisionParams = {}; let token; if (polymorphic) { token = polymorphicCommandFn.call(wrpc, command, params, callbackSpy); } else { token = commandFn.call(wrpc, {}, callbackSpy); } const expectedMessage: CloudVisionQueryMessage = { token, command, params, }; const expectedPostedMessage: PostedMessage = { request: expectedMessage, source: ID, timestamp: NOW, }; if (token) { expect(postMessageSpy).toHaveBeenCalledWith(expectedPostedMessage, '*'); expect(callbackSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, createRequestContext(command, token, params), expect.any(Function), ); expect(sendSpy).toHaveBeenCalledTimes(1); expect(sendSpy).toHaveBeenCalledWith( Parser.stringify({ token, command, params: {}, }), ); expect(token).not.toBeNull(); } expect(token).not.toBeNull(); }); test(`'${fn} + ${command}' should call callback and 'postMessage' to window on message`, () => { ws.dispatchEvent(new MessageEvent('open', {})); const params: CloudVisionParams = {}; let token; if (polymorphic) { token = polymorphicCommandFn.call(wrpc, command, params, callbackSpy); } else { token = commandFn.call(wrpc, {}, callbackSpy); } const expectedPostedMessage: PostedMessage = { response: { token, result: RESULT }, source: ID, timestamp: NOW, }; if (token) { const requestContext = createRequestContext(command, token, params); postMessageSpy.mockClear(); ws.dispatchEvent( new MessageEvent('message', { data: stringifyMessage({ token, result: RESULT }) }), ); expect(postMessageSpy).toHaveBeenCalledTimes(1); expect(postMessageSpy).toHaveBeenCalledWith(expectedPostedMessage, '*'); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith(null, RESULT, undefined, token, requestContext); expect(eventsEmitterSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(token).not.toBeNull(); } expect(token).not.toBeNull(); }); test(`'${fn} + ${command}' should call callback and 'postMessage' to window with error on error message`, () => { ws.dispatchEvent(new MessageEvent('open', {})); const params: CloudVisionParams = {}; let token; if (polymorphic) { token = polymorphicCommandFn.call(wrpc, command, params, callbackSpy); } else { token = commandFn.call(wrpc, {}, callbackSpy); } const expectedPostedMessage: PostedMessage = { response: { token, error: ERROR_MESSAGE, status: ERROR_STATUS }, source: ID, timestamp: NOW, }; if (token) { const requestContext = createRequestContext(command, token, params); postMessageSpy.mockClear(); ws.dispatchEvent( new MessageEvent('message', { data: stringifyMessage({ token, error: ERROR_MESSAGE, status: ERROR_STATUS }), }), ); expect(postMessageSpy).toHaveBeenCalledTimes(1); expect(postMessageSpy).toHaveBeenCalledWith(expectedPostedMessage, '*'); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith( ERROR_MESSAGE, undefined, ERROR_STATUS, token, requestContext, ); expect(eventsEmitterSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterUnbindSpy).toHaveBeenCalledWith(token, expect.any(Function)); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(token).not.toBeNull(); } expect(token).not.toBeNull(); }); test(`'${fn} + ${command}' should call callback and 'postMessage' to window with error on EOF message`, () => { const EOF_STATUS: CloudVisionStatus = { code: EOF_CODE }; ws.dispatchEvent(new MessageEvent('open', {})); const params: CloudVisionParams = {}; let token; if (polymorphic) { token = polymorphicCommandFn.call(wrpc, command, params, callbackSpy); } else { token = commandFn.call(wrpc, {}, callbackSpy); } const expectedPostedMessage: PostedMessage = { response: { token, error: EOF, status: EOF_STATUS }, source: ID, timestamp: NOW, }; if (token) { const requestContext = createRequestContext(command, token, params); postMessageSpy.mockClear(); ws.dispatchEvent( new MessageEvent('message', { data: stringifyMessage({ token, error: EOF, status: EOF_STATUS }), }), ); expect(postMessageSpy).toHaveBeenCalledTimes(1); expect(postMessageSpy).toHaveBeenCalledWith(expectedPostedMessage, '*'); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith(EOF, undefined, EOF_STATUS, token, requestContext); expect(eventsEmitterSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterUnbindSpy).toHaveBeenCalledWith(token, expect.any(Function)); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(token).not.toBeNull(); } expect(token).not.toBeNull(); }); }); describe.each<[StreamCommand, 'stream']>([ [SUBSCRIBE, 'stream'], [SEARCH_SUBSCRIBE, 'stream'], [SERVICE_REQUEST, 'stream'], ])('Stream Commands', (command, fn) => { let wrpc: Wrpc; let ws: WebSocket; let sendSpy: jest.SpyInstance; let eventsEmitterSpy: jest.SpyInstance; let eventsEmitterUnbindSpy: jest.SpyInstance; let eventsEmitterBindSpy: jest.SpyInstance; let commandFn: Wrpc['stream']; const callbackSpy = jest.fn(); const ERROR_MESSAGE = 'error'; const ERROR_STATUS: CloudVisionStatus = { code: 3, message: ERROR_MESSAGE, }; const ACTIVE_STATUS: CloudVisionStatus = { code: ACTIVE_CODE }; const RESULT = { dataset: 'Dodgers' }; beforeEach(() => { jest.resetAllMocks(); wrpc = new Wrpc(); commandFn = wrpc[fn]; wrpc.run('ws://localhost:8080'); ws = wrpc.websocket; sendSpy = jest.spyOn(ws, 'send'); eventsEmitterSpy = jest.spyOn(wrpc.eventsEmitter, 'emit'); eventsEmitterBindSpy = jest.spyOn(wrpc.eventsEmitter, 'bind'); eventsEmitterUnbindSpy = jest.spyOn(wrpc.eventsEmitter, 'unbind'); }); afterEach(() => { sendSpy.mockClear(); eventsEmitterSpy.mockClear(); eventsEmitterBindSpy.mockClear(); eventsEmitterUnbindSpy.mockClear(); callbackSpy.mockClear(); }); test(`'${fn} + ${command}' should not send message if socket is not running`, () => { const subscriptionId = commandFn.call(wrpc, command, query, callbackSpy); expect(callbackSpy).toHaveBeenCalledWith('Connection is down'); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(subscriptionId).toBe(null); }); test(`'${fn} + ${command}' should send message if socket is running`, () => { ws.dispatchEvent(new MessageEvent('open', {})); const subscriptionId = commandFn.call(wrpc, command, query, callbackSpy); if (subscriptionId?.token) { const token = subscriptionId.token; expect(callbackSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, createRequestContext(command, token, query), expect.any(Function), ); expect(sendSpy).toHaveBeenCalledTimes(1); expect(sendSpy).toHaveBeenCalledWith( Parser.stringify({ token, command, params: query, }), ); expect(subscriptionId).not.toBeNull(); } expect(subscriptionId).not.toBeNull(); }); test(`'${fn} + ${command}' should add to activeStreams if ACK message is received`, () => { ws.dispatchEvent(new MessageEvent('open', {})); const subscriptionId = commandFn.call(wrpc, command, query, callbackSpy); if (subscriptionId?.token) { const token = subscriptionId.token; const requestContext = createRequestContext(command, token, query); ws.dispatchEvent( new MessageEvent('message', { data: stringifyMessage({ token, status: ACTIVE_STATUS }), }), ); expect(sendSpy).toHaveBeenCalledTimes(1); expect(sendSpy).toHaveBeenCalledWith( Parser.stringify({ token, command, params: query, }), ); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith( null, undefined, ACTIVE_STATUS, token, requestContext, ); expect(eventsEmitterSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterSpy).toHaveBeenCalledWith(token, null, undefined, ACTIVE_STATUS); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(token).not.toBeNull(); } expect(subscriptionId).not.toBeNull(); }); test(`'${fn} + ${command}' should call callback with error on message that throws a send error`, () => { ws.dispatchEvent(new MessageEvent('open', {})); sendSpy.mockImplementation(() => { throw new Error(ERROR_MESSAGE); }); const subscriptionId = commandFn.call(wrpc, command, query, callbackSpy); if (subscriptionId?.token) { const token = subscriptionId.token; const requestContext = createRequestContext(command, token, query); expect(log).toHaveBeenCalledTimes(1); expect(sendSpy).toHaveBeenCalledTimes(1); expect(sendSpy).toHaveBeenCalledWith( Parser.stringify({ token, command, params: query, }), ); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith( new Error(ERROR_MESSAGE), undefined, undefined, token, requestContext, ); expect(eventsEmitterSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); } expect(subscriptionId).not.toBeNull(); }); test(`'${fn} + ${command}' should call callback and unbind on all errors`, () => { ws.dispatchEvent(new MessageEvent('open', {})); const subscriptionId = commandFn.call(wrpc, command, query, callbackSpy); if (subscriptionId?.token) { const token = subscriptionId.token; const requestContext = createRequestContext(command, token, query); ws.dispatchEvent( new MessageEvent('message', { data: stringifyMessage({ token, error: ERROR_MESSAGE, status: ERROR_STATUS }), }), ); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith( ERROR_MESSAGE, undefined, ERROR_STATUS, token, requestContext, ); expect(eventsEmitterSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterSpy).toHaveBeenCalledWith(token, ERROR_MESSAGE, undefined, ERROR_STATUS); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterUnbindSpy).toHaveBeenCalledWith(token, expect.any(Function)); expect(sendSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); } expect(subscriptionId).not.toBeNull(); }); test(`'${fn} + ${command}' should call callback and unbind on all EOF`, () => { const EOF_STATUS: CloudVisionStatus = { code: EOF_CODE }; ws.dispatchEvent(new MessageEvent('open', {})); const subscriptionId = commandFn.call(wrpc, command, query, callbackSpy); if (subscriptionId?.token) { const token = subscriptionId.token; const requestContext = createRequestContext(command, token, query); ws.dispatchEvent( new MessageEvent('message', { data: stringifyMessage({ token, error: EOF, status: EOF_STATUS }), }), ); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith(EOF, undefined, EOF_STATUS, token, requestContext); expect(eventsEmitterSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterSpy).toHaveBeenCalledWith(token, EOF, undefined, EOF_STATUS); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterUnbindSpy).toHaveBeenCalledWith(token, expect.any(Function)); expect(sendSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); } expect(subscriptionId).not.toBeNull(); }); test(`'${fn} + ${command}' should call callback and not unbind on get request EOF`, () => { const METADATA: CloudVisionMetaData<string> = { [GET_REQUEST_COMPLETED]: EOF }; const EOF_STATUS: CloudVisionStatus = { code: EOF_CODE, message: GET_REQUEST_COMPLETED }; const RESULT_WITH_META = { ...RESULT, metadata: METADATA }; ws.dispatchEvent(new MessageEvent('open', {})); const subscriptionId = commandFn.call(wrpc, command, query, callbackSpy); if (subscriptionId?.token) { const token = subscriptionId.token; const requestContext = createRequestContext(command, token, query); ws.dispatchEvent( new MessageEvent('message', { data: stringifyMessage({ token, result: RESULT_WITH_META }), }), ); expect(callbackSpy).toHaveBeenCalledTimes(2); expect(callbackSpy).toHaveBeenNthCalledWith( 1, null, RESULT_WITH_META, undefined, token, requestContext, ); expect(callbackSpy).toHaveBeenNthCalledWith(2, null, null, EOF_STATUS, token, requestContext); expect(eventsEmitterSpy).toHaveBeenCalledTimes(2); expect(eventsEmitterSpy).toHaveBeenNthCalledWith(1, token, null, RESULT_WITH_META, undefined); expect(eventsEmitterSpy).toHaveBeenNthCalledWith(2, token, null, null, EOF_STATUS); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(0); expect(sendSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); } expect(subscriptionId).not.toBeNull(); }); test(`'${fn} + ${command}' should call callback on message and not unbind`, () => { ws.dispatchEvent(new MessageEvent('open', {})); const subscriptionId = commandFn.call(wrpc, command, query, callbackSpy); if (subscriptionId?.token) { const token = subscriptionId.token; const requestContext = createRequestContext(command, token, query); ws.dispatchEvent( new MessageEvent('message', { data: stringifyMessage({ token, result: RESULT }) }), ); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith(null, RESULT, undefined, token, requestContext); expect(eventsEmitterSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterSpy).toHaveBeenCalledWith(token, null, RESULT, undefined); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(sendSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); } expect(subscriptionId).not.toBeNull(); }); test(`'${fn} + ${command}' should not call callback on message that is not a string`, () => { ws.dispatchEvent(new MessageEvent('open', {})); const subscriptionId = commandFn.call(wrpc, command, query, callbackSpy); if (subscriptionId?.token) { const token = subscriptionId.token; ws.dispatchEvent(new MessageEvent('message', { data: RESULT })); expect(callbackSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, createRequestContext(command, token, query), expect.any(Function), ); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(sendSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); } expect(subscriptionId).not.toBeNull(); }); test(`'${fn} + ${command}' should not call callback on message without token`, () => { ws.dispatchEvent(new MessageEvent('open', {})); const subscriptionId = commandFn.call(wrpc, command, query, callbackSpy); if (subscriptionId?.token) { const token = subscriptionId.token; ws.dispatchEvent(new MessageEvent('message', { data: stringifyMessage({ result: RESULT }) })); expect(callbackSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, createRequestContext(command, token, query), expect.any(Function), ); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(sendSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); } expect(subscriptionId).not.toBeNull(); }); test(`'${fn} + ${command}' should not call callback on message that throws error`, () => { ws.dispatchEvent(new MessageEvent('open', {})); const result = '{ data: 1'; const subscriptionId = commandFn.call(wrpc, command, query, callbackSpy); if (subscriptionId?.token) { const token = subscriptionId.token; ws.dispatchEvent(new MessageEvent('message', { data: result })); expect(log).toHaveBeenCalledTimes(1); expect(callbackSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, createRequestContext(command, token, query), expect.any(Function), ); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(sendSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); } expect(subscriptionId).not.toBeNull(); }); }); describe.each<[StreamCommand, 'stream']>([ [SUBSCRIBE, 'stream'], // [SEARCH_SUBSCRIBE, 'stream'], // [SERVICE_REQUEST, 'stream'], ])('Close Stream Commands', (command, fn) => { let wrpc: Wrpc; let ws: WebSocket; let subscriptionId: SubscriptionIdentifier; let subscriptionIdTwo: SubscriptionIdentifier; let sendSpy: jest.SpyInstance; let eventsEmitterSpy: jest.SpyInstance; let eventsEmitterUnbindSpy: jest.SpyInstance; let eventsEmitterBindSpy: jest.SpyInstance; let commandFn: Wrpc['stream']; const callbackSpy = jest.fn(); const callbackSpyTwo = jest.fn(); const closeCallback = jest.fn(); const ERROR_MESSAGE = 'error'; const ACTIVE_STATUS: CloudVisionStatus = { code: ACTIVE_CODE }; beforeEach(() => { jest.resetAllMocks(); wrpc = new Wrpc(); commandFn = wrpc[fn]; wrpc.run('ws://localhost:8080'); ws = wrpc.websocket; ws.dispatchEvent(new MessageEvent('open', {})); const subIdOrNull = commandFn.call(wrpc, command, query, callbackSpy); if (subIdOrNull) { subscriptionId = subIdOrNull; } expect(subIdOrNull).not.toBeNull(); expect(subscriptionId).toBeDefined(); const subIdOrNullTwo = commandFn.call(wrpc, command, {}, callbackSpyTwo); if (subIdOrNullTwo) { subscriptionIdTwo = subIdOrNullTwo; } expect(subIdOrNullTwo).not.toBeNull(); expect(subscriptionIdTwo).toBeDefined(); ws.dispatchEvent( new MessageEvent('message', { data: stringifyMessage({ token: subscriptionId.token, status: ACTIVE_STATUS }), }), ); sendSpy = jest.spyOn(ws, 'send'); eventsEmitterSpy = jest.spyOn(wrpc.eventsEmitter, 'emit'); eventsEmitterBindSpy = jest.spyOn(wrpc.eventsEmitter, 'bind'); eventsEmitterUnbindSpy = jest.spyOn(wrpc.eventsEmitter, 'unbind'); callbackSpy.mockClear(); callbackSpyTwo.mockClear(); }); afterEach(() => { sendSpy.mockClear(); eventsEmitterSpy.mockClear(); eventsEmitterBindSpy.mockClear(); eventsEmitterUnbindSpy.mockClear(); callbackSpy.mockClear(); callbackSpyTwo.mockClear(); closeCallback.mockClear(); }); describe('single stream', () => { test(`'${fn} + ${command}' should send close stream message`, () => { const token = wrpc.closeStream(subscriptionId, closeCallback); if (token) { expect(closeCallback).not.toHaveBeenCalled(); expect(callbackSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterUnbindSpy).toHaveBeenCalledWith( subscriptionId.token, subscriptionId.callback, ); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); } expect(token).not.toBeNull(); }); test(`'${fn} + ${command}' should callback with error on close message that throws a send error`, () => { sendSpy.mockImplementation(() => { throw new Error(ERROR_MESSAGE); }); const token = wrpc.closeStream(subscriptionId, closeCallback); if (token) { expect(closeCallback).toHaveBeenCalledTimes(1); expect(closeCallback).toHaveBeenCalledWith( new Error(ERROR_MESSAGE), undefined, undefined, token, ); expect(callbackSpy).not.toHaveBeenCalled(); expect(log).toHaveBeenCalledTimes(1); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterUnbindSpy).toHaveBeenCalledWith( subscriptionId.token, subscriptionId.callback, ); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); } expect(token).not.toBeNull(); }); test(`'${fn} + ${command}' should not send close stream message if no streams are present`, () => { const token = wrpc.closeStream( { token: 'random token', callback: callbackSpy }, closeCallback, ); expect(token).toBeNull(); expect(closeCallback).not.toHaveBeenCalled(); expect(callbackSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).not.toHaveBeenCalled(); expect(sendSpy).not.toHaveBeenCalled(); }); }); describe('multiple streams', () => { test(`'${fn} + ${command}' should send close message`, () => { const streams = [subscriptionId, subscriptionIdTwo]; const token = wrpc.closeStreams(streams, closeCallback); if (token) { const requestContext = createRequestContext(CLOSE, token, streams); expect(closeCallback).not.toHaveBeenCalled(); expect(callbackSpy).not.toHaveBeenCalled(); expect(callbackSpyTwo).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(2); expect(eventsEmitterUnbindSpy).toHaveBeenNthCalledWith( 1, subscriptionId.token, subscriptionId.callback, ); expect(eventsEmitterUnbindSpy).toHaveBeenNthCalledWith( 2, subscriptionIdTwo.token, subscriptionIdTwo.callback, ); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(sendSpy).toHaveBeenCalledTimes(1); expect(sendSpy).toHaveBeenCalledWith( Parser.stringify({ token, command: CLOSE, params: { [subscriptionId.token]: true, [subscriptionIdTwo.token]: true }, }), ); } expect(token).not.toBeNull(); }); test(`'${fn} + ${command}' should callback with error on close message that throws a send error`, () => { sendSpy.mockImplementation(() => { throw new Error(ERROR_MESSAGE); }); const streams = [subscriptionId, subscriptionIdTwo]; const token = wrpc.closeStreams(streams, closeCallback); if (token) { const requestContext = createRequestContext(CLOSE, token, streams); expect(closeCallback).toHaveBeenCalledTimes(1); expect(log).toHaveBeenCalledTimes(1); expect(callbackSpy).not.toHaveBeenCalled(); expect(callbackSpyTwo).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(2); expect(eventsEmitterUnbindSpy).toHaveBeenNthCalledWith( 1, subscriptionId.token, subscriptionId.callback, ); expect(eventsEmitterUnbindSpy).toHaveBeenNthCalledWith( 2, subscriptionIdTwo.token, subscriptionIdTwo.callback, ); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(sendSpy).toHaveBeenCalledTimes(1); expect(sendSpy).toHaveBeenCalledWith( Parser.stringify({ token, command: CLOSE, params: { [subscriptionId.token]: true, [subscriptionIdTwo.token]: true }, }), ); } expect(token).not.toBeNull(); }); test(`'${fn} + ${command}' should not send close stream message if no streams are present`, () => { const streams = [ { token: 'random token', callback: callbackSpy }, { token: 'another random token', callback: callbackSpyTwo }, ]; const token = wrpc.closeStreams(streams, closeCallback); expect(token).toBeNull(); expect(callbackSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(2); expect(eventsEmitterBindSpy).not.toHaveBeenCalled(); expect(sendSpy).not.toHaveBeenCalled(); }); }); }); <file_sep>/* eslint-env jest */ // Copyright (c) 2018, Arista Networks, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. /* eslint-disable @typescript-eslint/no-non-null-assertion */ import { APP_DATASET_TYPE, CONFIG_DATASET_TYPE, DEVICE_DATASET_TYPE, EOF, EOF_CODE, ERROR, GET, SEARCH_TYPE_ANY, SEARCH_TYPE_IP, SEARCH_TYPE_MAC, SUBSCRIBE, } from '../src/constants'; import Emitter from '../src/emitter'; import { log } from '../src/logger'; import { createCloseParams, invalidParamMsg, isMicroSeconds, isValidArg, makeNotifCallback, makePublishCallback, sanitizeOptions, sanitizeSearchOptions, toBinaryKey, validateOptions, validateQuery, validateResponse, } from '../src/utils'; import { CloseParams, CloudVisionDatasets, CloudVisionNotifs, CloudVisionServiceResult, CloudVisionStatus, Options, Query, RequestContext, SearchOptions, SubscriptionIdentifier, WsCommand, } from '../types'; const EOF_STATUS: CloudVisionStatus = { code: EOF_CODE, }; jest.mock('../src/logger', () => { return { log: jest.fn() }; }); jest.spyOn(console, 'groupCollapsed').mockImplementation(); function createRequestContext(command: WsCommand, token: string, params: unknown): RequestContext { return { command, token, encodedParams: toBinaryKey(params), }; } describe('invalidParamMsg', () => { test('should generate a proper error message given parameters', () => { const message = invalidParamMsg(10, 20, 1); expect(message).toBe('invalid params: start: 10, end: 20, versions: 1'); }); }); describe('sanitizeOptions', () => { test('should convert millisecond timestamps to microseconds', () => { const options: Options = { start: 1498053512, end: 1498093512, }; expect(sanitizeOptions(options)).toEqual<Options>({ start: options.start! * 1e6, end: options.end! * 1e6, versions: undefined, }); }); test('should not convert microseconds timestamps', () => { const options: Options = { start: 1498053512 * 1e6, end: 1498093512 * 1e6, }; expect(sanitizeOptions(options)).toEqual<Options>({ ...options, versions: undefined, }); }); test('should convert float timestamps', () => { const options: Options = { start: 1498053512.589, end: 1498093512.1, }; expect(sanitizeOptions(options)).toEqual<Options>({ start: 1498053512 * 1e6, end: 1498093512 * 1e6, versions: undefined, }); }); test('should convert float version', () => { const options: Options = { versions: 10.5, }; expect(sanitizeOptions(options)).toEqual<Options>({ start: undefined, end: undefined, versions: 10, }); }); }); describe('isValidArg', () => { test('should return true for numbers', () => { expect(isValidArg(2)).toBe(true); }); test('should return false for numbers less than 0', () => { expect(isValidArg(-1)).toBe(false); }); test('should return false for 0', () => { expect(isValidArg(0)).toBe(false); }); test('should return true for floats', () => { expect(isValidArg(2.2)).toBe(true); }); }); describe('isMicroSeconds', () => { test('should return true for microsecond timestamps', () => { expect(isMicroSeconds(1505254217000000)).toBe(true); }); test('should return false for non microseconds timestamps', () => { expect(isMicroSeconds(1505254217)).toBe(false); }); }); describe('validateOptions', () => { const spyCallback = jest.fn(); beforeEach(() => { spyCallback.mockReset(); }); test('should pass validation if start < end', () => { const options: Options = { start: 1000, end: 2000, }; expect(validateOptions(options, spyCallback)).toBe(true); expect(spyCallback).not.toHaveBeenCalled(); }); test('should pass validation if start given but not end', () => { const options: Options = { start: 2000, }; expect(validateOptions(options, spyCallback)).toBe(true); expect(spyCallback).not.toHaveBeenCalled(); }); test('should not pass validation if start > end', () => { const options: Options = { start: 2000, end: 1000, }; expect(validateOptions(options, spyCallback)).toBe(false); expect(spyCallback).toHaveBeenCalledTimes(1); }); test('should not pass validation if start === end', () => { const options: Options = { start: 2000, end: 2000, }; expect(validateOptions(options, spyCallback)).toBe(false); expect(spyCallback).toHaveBeenCalledTimes(1); }); test('should not pass validation if start and versions are defined', () => { const options: Options = { start: 2000, versions: 10, }; expect(validateOptions(options, spyCallback)).toBe(false); expect(spyCallback).toHaveBeenCalledTimes(1); }); }); describe('validateQuery', () => { const spyCallback = jest.fn(); beforeEach(() => { spyCallback.mockReset(); }); test('should pass validation if query is an array with elements', () => { const query = [{}]; // @ts-expect-error explicity testings an invalid input expect(validateQuery(query, spyCallback)).toBe(true); expect(spyCallback).not.toHaveBeenCalled(); }); test('should fail validation if query is an array without elements', () => { const query: Query = []; expect(validateQuery(query, spyCallback)).toBe(false); expect(spyCallback).toHaveBeenCalledTimes(1); }); test('should pass validation if query is an empty array and we explicitly allow it', () => { const query: Query = []; expect(validateQuery(query, spyCallback, true)).toBe(true); expect(spyCallback).not.toHaveBeenCalled(); }); test('should fail validation if query is not an array', () => { const query = {}; // @ts-expect-error explicity testings an invalid input expect(validateQuery(query, spyCallback)).toBe(false); expect(spyCallback).toHaveBeenCalledTimes(1); }); test('should fail validation if query is undefined', () => { const query = undefined; // @ts-expect-error explicity testings an invalid input expect(validateQuery(query, spyCallback)).toBe(false); expect(spyCallback).toHaveBeenCalledTimes(1); }); }); describe('makeNotifCallback', () => { const token = 'Dodgers'; const callbackSpy = jest.fn(); const requestContext = createRequestContext(GET, token, {}); beforeEach(() => { callbackSpy.mockReset(); }); test('not invoke the callback if there is no data', () => { const notifCallback = makeNotifCallback(callbackSpy); notifCallback(null, undefined); expect(callbackSpy).not.toHaveBeenCalled(); }); test('should send undefined on `EOF`', () => { const notifCallback = makeNotifCallback(callbackSpy); notifCallback(EOF, undefined, EOF_STATUS, token, requestContext); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith(null, undefined, EOF_STATUS, token, requestContext); }); test('should invoke a callack with the result, when there is no error', () => { const notifCallback = makeNotifCallback(callbackSpy); const notif: CloudVisionNotifs = { dataset: { name: 'device1', type: DEVICE_DATASET_TYPE }, metadata: {}, notifications: [ { path_elements: ['path1'], timestamp: 101000002000000 }, { path_elements: ['path1'], timestamp: 103000004000000 }, ], }; notifCallback(null, notif, undefined, token, requestContext); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith(null, notif, undefined, token, requestContext); }); test('should invoke the callback properly for dataset responses', () => { const notifCallback = makeNotifCallback(callbackSpy); const notif: CloudVisionDatasets = { datasets: [ { type: DEVICE_DATASET_TYPE, name: 'device1', }, { type: APP_DATASET_TYPE, name: 'app1', }, { type: CONFIG_DATASET_TYPE, name: 'config1', }, ], metadata: {}, }; notifCallback(null, notif, undefined, token, requestContext); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith(null, notif, undefined, token, requestContext); }); test('should invoke the callback properly for service responses', () => { const notifCallback = makeNotifCallback(callbackSpy); const notif: CloudVisionServiceResult = { Dodgers: 'the best team in baseball', }; notifCallback(null, notif, undefined, token, requestContext); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith(null, notif, undefined, token, requestContext); }); test('should invoke the callback if there is an error', () => { const notifCallback = makeNotifCallback(callbackSpy); const errorText = 'Some Error'; notifCallback(errorText, undefined, undefined, token, requestContext); expect(callbackSpy).toHaveBeenCalledTimes(2); expect(callbackSpy).toHaveBeenLastCalledWith( null, undefined, { code: EOF_CODE }, token, requestContext, ); expect(callbackSpy.mock.calls[0][0]).toContain(errorText); }); }); describe('createCloseParams', () => { let emitter: Emitter; const streamCallback = jest.fn(); const streamToken = 'Dod<PASSWORD>'; const stream: SubscriptionIdentifier = { token: streamToken, callback: streamCallback, }; const streamCallback2 = jest.fn(); const streamToken2 = 'V<PASSWORD>'; const stream2: SubscriptionIdentifier = { token: streamToken2, callback: streamCallback2, }; const requestContext = createRequestContext(SUBSCRIBE, streamToken, {}); const requestContext2 = createRequestContext(SUBSCRIBE, streamToken2, {}); beforeEach(() => { emitter = new Emitter(); emitter.bind(streamToken, requestContext, streamCallback); emitter.bind(streamToken2, requestContext2, streamCallback2); }); test('should create the proper stream close params for one stream', () => { const expectedCloseParams: CloseParams = { [streamToken]: true }; const closeParams = createCloseParams(stream, emitter); expect(closeParams).toEqual(expectedCloseParams); expect(streamCallback).not.toHaveBeenCalled(); expect(emitter.getEventsMap().get(streamToken)).toBeUndefined(); }); test('should create the proper stream close params for multiple streams', () => { const streams = [stream, stream2]; const expectedCloseParams: CloseParams = { [streamToken]: true, [streamToken2]: true }; const closeParams = createCloseParams(streams, emitter); expect(closeParams).toEqual(expectedCloseParams); expect(streamCallback).not.toHaveBeenCalled(); expect(emitter.getEventsMap().get(streamToken)).toBeUndefined(); expect(streamCallback2).not.toHaveBeenCalled(); expect(emitter.getEventsMap().get(streamToken2)).toBeUndefined(); }); test( 'should create the proper stream close params if a stream has multiple callbacks and only ' + 'one is unbound', () => { const anotherCallback = jest.fn(); const expectedCloseParams = null; emitter.bind(streamToken, requestContext, anotherCallback); const closeParams = createCloseParams(stream, emitter); expect(closeParams).toEqual(expectedCloseParams); expect(streamCallback).not.toHaveBeenCalled(); expect(emitter.getEventsMap().get(streamToken)).toEqual([anotherCallback]); expect(anotherCallback).not.toHaveBeenCalled(); }, ); test( 'should create the proper stream close params if a stream has multiple callbacks and ' + 'all are unbound', () => { const anotherCallback = jest.fn(); const expectedCloseParams: CloseParams = { [streamToken]: true }; const annotherStream: SubscriptionIdentifier = { token: streamToken, callback: anotherCallback, }; const streams = [stream, annotherStream]; emitter.bind(streamToken, requestContext, anotherCallback); const closeParams = createCloseParams(streams, emitter); expect(closeParams).toEqual(expectedCloseParams); expect(streamCallback).not.toHaveBeenCalled(); expect(emitter.getEventsMap().get(streamToken)).toBeUndefined(); expect(anotherCallback).not.toHaveBeenCalled(); }, ); }); describe('makePublishCallback', () => { const callbackSpy = jest.fn(); beforeEach(() => { callbackSpy.mockReset(); }); test('should have proper callback on EOF', () => { const publishCallback = makePublishCallback(callbackSpy); publishCallback(EOF, undefined, EOF_STATUS); expect(callbackSpy).toHaveBeenCalledWith(true); }); test('should have proper callback on Error', () => { const publishCallback = makePublishCallback(callbackSpy); const err = 'SomeError'; const expectedErrMsg = `Error: ${err}\n`; publishCallback(err); expect(callbackSpy).toHaveBeenCalledWith(false, expectedErrMsg); }); test('should not callback when no error or no EOF', () => { const publishCallback = makePublishCallback(callbackSpy); const err = null; publishCallback(err); expect(callbackSpy).not.toHaveBeenCalled(); }); }); describe('validateResponse', () => { const token = 'some token'; beforeEach(() => { jest.resetAllMocks(); }); test('should not log an error for a valid response', () => { const notifResponse: CloudVisionNotifs = { dataset: { name: 'Max', type: APP_DATASET_TYPE }, metadata: {}, notifications: [{ path_elements: ['Muncy'], timestamp: 1 }], }; const datasetResponse: CloudVisionDatasets = { datasets: [{ name: 'Max', type: APP_DATASET_TYPE }], metadata: {}, }; validateResponse(notifResponse, {}, token, false); validateResponse(datasetResponse, {}, token, false); expect(log).not.toHaveBeenCalled(); }); test('should log an error for a response with a non array type for notifications', () => { const response: CloudVisionNotifs = { dataset: { name: 'Max', type: APP_DATASET_TYPE }, // @ts-expect-error explicity testings an invalid input notifications: { lastName: 'Muncy' }, }; validateResponse(response, {}, token, false); expect(log).toHaveBeenCalledWith( ERROR, "Key 'notifications' is not an array", undefined, token, ); }); test('should log an error for a response without notifications', () => { // @ts-expect-error explicity testings an invalid input const response: CloudVisionNotifs = { dataset: { name: 'Max', type: 'beast' } }; validateResponse(response, {}, token, false); expect(log).toHaveBeenCalledWith( ERROR, "No key 'notifications' found in response", undefined, token, ); }); test('should log an error for a response without type for dataset', () => { // @ts-expect-error explicity testings an invalid input const response: CloudVisionNotifs = { dataset: { name: 'Max' } }; validateResponse(response, {}, token, false); expect(log).toHaveBeenCalledWith(ERROR, "No key 'type' found in dataset", undefined, token); }); test('should log an error for a response without name for dataset', () => { // @ts-expect-error explicity testings an invalid input const response: CloudVisionNotifs = { dataset: {} }; validateResponse(response, {}, token, false); expect(log).toHaveBeenCalledWith(ERROR, "No key 'name' found in dataset", undefined, token); }); test('should not log an error for a status response', () => { // @ts-expect-error explicity testings an invalid input const response: CloudVisionNotifs = {}; validateResponse(response, { code: 1101 }, token, false); expect(log).not.toHaveBeenCalledWith(); }); /* eslint-enable no-console */ }); describe('sanitizeSearchOptions', () => { test('should return `ANY` as search type if none is given', () => { const searchOptions: SearchOptions = { search: 'Dodgers' }; expect(sanitizeSearchOptions(searchOptions)).toEqual<SearchOptions>({ search: 'Dodgers', searchType: SEARCH_TYPE_ANY, }); }); test('should return `ANY` as search type, if the type does not match a proper search type', () => { const searchOptions: SearchOptions = { search: 'Dodgers' }; expect(sanitizeSearchOptions(searchOptions)).toEqual<SearchOptions>({ search: 'Dodgers', searchType: SEARCH_TYPE_ANY, }); }); test('should return the given search type, if it matches a proper search type', () => { const searchOptionsMac: SearchOptions = { search: 'Dodgers', searchType: SEARCH_TYPE_MAC }; const searchOptionsAny: SearchOptions = { search: 'Dodgers', searchType: SEARCH_TYPE_ANY }; const searchOptionsIp: SearchOptions = { search: 'Dodgers', searchType: SEARCH_TYPE_IP }; expect(sanitizeSearchOptions(searchOptionsMac)).toEqual<SearchOptions>({ search: 'Dodgers', searchType: SEARCH_TYPE_MAC, }); expect(sanitizeSearchOptions(searchOptionsAny)).toEqual<SearchOptions>({ search: 'Dodgers', searchType: SEARCH_TYPE_ANY, }); expect(sanitizeSearchOptions(searchOptionsIp)).toEqual<SearchOptions>({ search: 'Dodgers', searchType: SEARCH_TYPE_IP, }); }); }); <file_sep>const util = require('util'); global.TextDecoder = util.TextDecoder; global.TextEncoder = util.TextEncoder; <file_sep># cloudvision-grpc-web A grpc-web client for requesting CloudVision data from the frontend. This libraries exposed functions and utils that convert the grpc-web calls to Observable streams that can be manipulated using [RXJS](https://rxjs.dev/). The package expects protobuf definitions to be generated via [ts-proto](https://github.com/stephenh/ts-proto) ## Installation ```bash npm install cloudvision-grpc-web ``` or ```bash yarn install cloudvision-grpc-web ``` ## Usage ```js import { fromResourceGrpcInvoke } from 'cloudvision-grpc-web'; import { DeviceServiceGetAllDesc, DeviceStreamRequest } from '../generated/arista/inventory.v1/services.gen'; const requestAllMessage = DeviceStreamRequest.fromPartial({}); const grpcRequest = fromResourceGrpcInvoke(DeviceServiceGetAllDesc, { host: 'http://cvphost', request: { ...requestAllMessage, ...DeviceServiceGetAllDesc.requestType }, }); // Will print out each data message as it arrives grpcRequest.data.subscribe({ next: (val) => console.log('data', val)) }) // Will print out any Grpc metadata or errors as they happen grpcRequest.messages.subscribe({ next: (val) => console.log('control message', val)) }) ``` <file_sep>/** * ExtData is used to handle Extension Types that are not registered to ExtensionCodec. */ export class ExtData { constructor(readonly type: number, readonly data: Uint8Array) { this.type = type; this.data = data; } } <file_sep>/** * @jest-environment jsdom */ // Copyright (c) 2018, Arista Networks, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import { PathElements } from 'a-msgpack'; import Connector from '../src/Connector'; import { ALL_DATASET_TYPES, APP_DATASET_TYPE, CONFIG_DATASET_TYPE, DEVICES_DATASET_ID, DEVICE_DATASET_TYPE, GET, GET_AND_SUBSCRIBE, GET_DATASETS, GET_REGIONS_AND_CLUSTERS, SEARCH, SEARCH_SUBSCRIBE, SEARCH_TYPE_ANY, SERVICE_REQUEST, SUBSCRIBE, } from '../src/constants'; import { sanitizeOptions, sanitizeSearchOptions, toBinaryKey } from '../src/utils'; import { CloudVisionStatus, NotifCallback, Options, PublishRequest, Query, QueryParams, RequestContext, SearchOptions, SearchParams, ServiceRequest, SubscriptionIdentifier, WsCommand, } from '../types'; const dataset = 'deviceFoo'; const rootPath: PathElements = []; const rootQuery: Query = [ { dataset: { type: DEVICE_DATASET_TYPE, name: dataset }, paths: [{ path_elements: rootPath }], }, ]; const singlePathQuery: Query = [ { dataset: { type: DEVICE_DATASET_TYPE, name: dataset }, paths: [{ path_elements: ['this', 'is', 'the', 'first', 'path'] }], }, ]; const serviceQuery: ServiceRequest = { service: 'A', method: 'B', body: { param1: 'param1', param2: 'param2', }, }; const multiplePathQuery: Query = [ { dataset: { type: DEVICE_DATASET_TYPE, name: dataset }, paths: [ { path_elements: ['this', 'is', 'the', 'first', 'path'] }, { path_elements: ['and', 'this', 'is', 'the', 'second'] }, ], }, ]; const SEARCH_OPTIONS: SearchOptions = { search: '', searchType: SEARCH_TYPE_ANY, }; const ERROR_MESSAGE = 'error'; const ERROR_STATUS: CloudVisionStatus = { code: 3, message: ERROR_MESSAGE, }; jest.spyOn(console, 'groupCollapsed').mockImplementation(); function setupConnector(): Connector { const conn = new Connector(); conn.run('ws://localhost:8080'); conn.websocket.dispatchEvent(new MessageEvent('open', {})); return conn; } describe('closeSubscriptions', () => { const streamCallback = jest.fn(); const streamToken = 'Dod<PASSWORD>'; const streamCallback2 = jest.fn(); const streamToken2 = 'V<PASSWORD>'; const subscriptions = [ { token: streamToken, callback: streamCallback }, { token: streamToken2, callback: streamCallback2 }, ]; test('should close multiple subscriptions in one call', () => { const conn = setupConnector(); jest.spyOn(conn, 'closeStreams'); const spyCallback = jest.fn(); conn.closeSubscriptions(subscriptions, spyCallback); expect(conn.closeStreams).toHaveBeenCalledWith(subscriptions, expect.any(Function)); expect(spyCallback).not.toHaveBeenCalled(); }); }); describe('writeSync', () => { test('should call writeSync with proper params', () => { const publishRequest: PublishRequest = { dataset: { name: 'analytics', type: APP_DATASET_TYPE }, notifications: [ { timestamp: { seconds: 1 }, path_elements: ['test'], updates: [{ key: 'someKey', value: 'somevalue' }], }, ], }; const conn = setupConnector(); jest.spyOn(conn, 'writeSync'); const spyCallback = jest.fn(); conn.writeSync(publishRequest, spyCallback); expect(conn.writeSync).toHaveBeenCalledTimes(1); expect(conn.writeSync).toHaveBeenCalledWith(publishRequest, expect.any(Function)); expect(spyCallback).not.toHaveBeenCalled(); }); }); describe('runService', () => { test('should call runService with proper params', () => { const conn = setupConnector(); jest.spyOn(conn, 'requestService'); const spyCallback = jest.fn(); conn.runService(serviceQuery, spyCallback); expect(conn.requestService).toHaveBeenCalledTimes(1); expect(conn.requestService).toHaveBeenCalledWith(serviceQuery, expect.any(Function)); expect(spyCallback).not.toHaveBeenCalled(); }); }); describe('runStreamingService', () => { test('should call runStreamingService with proper params and receive streamIdentifier', () => { const conn = setupConnector(); jest.spyOn(conn, 'runStreamingService'); const spyCallback = jest.fn(); const streamIdentifier = conn.runStreamingService(serviceQuery, spyCallback); if (streamIdentifier !== null) { expect(streamIdentifier.token).toEqual(expect.any(String)); expect(typeof streamIdentifier.callback).toBe('function'); } expect(conn.runStreamingService).toHaveBeenCalledTimes(1); expect(conn.runStreamingService).toHaveBeenCalledWith(serviceQuery, expect.any(Function)); expect(spyCallback).not.toHaveBeenCalled(); }); }); describe('getDatasets', () => { let conn: Connector; let spyCallback: () => void; beforeEach(() => { conn = setupConnector(); jest.spyOn(conn, 'get'); spyCallback = jest.fn(); }); test('should get all datasets', () => { conn.getDatasets(spyCallback); expect(conn.get).toHaveBeenCalledWith( GET_DATASETS, { types: [APP_DATASET_TYPE, CONFIG_DATASET_TYPE, DEVICE_DATASET_TYPE] }, expect.any(Function), ); }); test('should get all device type datasets', () => { conn.getDevices(spyCallback); expect(conn.get).toHaveBeenCalledWith( GET_DATASETS, { types: [DEVICE_DATASET_TYPE] }, expect.any(Function), ); }); test('should get all app type datasets', () => { conn.getApps(spyCallback); expect(conn.get).toHaveBeenCalledWith( GET_DATASETS, { types: [APP_DATASET_TYPE] }, expect.any(Function), ); }); test('should get all config type datasets', () => { conn.getConfigs(spyCallback); expect(conn.get).toHaveBeenCalledWith( GET_DATASETS, { types: [CONFIG_DATASET_TYPE] }, expect.any(Function), ); }); test('should get all datasets using `getWithOptions` ', () => { conn.getWithOptions(DEVICES_DATASET_ID, spyCallback, {}); expect(conn.get).toHaveBeenCalledWith( GET_DATASETS, { types: ALL_DATASET_TYPES }, expect.any(Function), ); }); }); describe('getRegionsAndClusters', () => { let conn: Connector; let spyCallback: () => void; beforeEach(() => { conn = setupConnector(); jest.spyOn(conn, 'get'); spyCallback = jest.fn(); }); test('should get all datasets', () => { conn.getRegionsAndClusters(spyCallback); expect(conn.get).toHaveBeenCalledWith(GET_REGIONS_AND_CLUSTERS, {}, expect.any(Function)); }); }); describe.each([ ['getWithOptions', GET, 'get'], ['searchWithOptions', SEARCH, 'search', true], ])('Get Queries', (fn, command, wrpcFn, isSearch?) => { const options = {} as Options & SearchOptions; const callback = jest.fn(); let conn: Connector; let commandFnSpy: jest.SpyInstance; let connFn: (q: Query, cb: NotifCallback, o: Options) => string | null; const RESULT = { dataset: 'Dodgers' }; function createRequestContext( c: string, token: string, query: Query, o: Options & SearchOptions, ): RequestContext { const { start, end, versions } = sanitizeOptions(o); let params: SearchParams | QueryParams = { query, start, end, versions }; if (isSearch) { const sanitizedSearchOptions = sanitizeSearchOptions(o); params = { query, start, end, search: sanitizedSearchOptions.search, searchType: sanitizedSearchOptions.searchType, }; } return { command: c as WsCommand, token, encodedParams: toBinaryKey(params), }; } beforeEach(() => { conn = new Connector(); // @ts-expect-error Easier than typing everything connFn = conn[fn]; // @ts-expect-error Easier than typing everything commandFnSpy = jest.spyOn(conn, wrpcFn); conn.run('ws://localhost:8080'); conn.websocket.dispatchEvent(new MessageEvent('open', {})); }); afterEach(() => { callback.mockClear(); commandFnSpy.mockClear(); }); test(`'${fn}' should handle empty query`, () => { const query: Query = []; const token = connFn.call(conn, query, callback, options); if (isSearch) { // empty is valid for search expect(commandFnSpy).toHaveBeenCalledTimes(1); expect(callback).not.toHaveBeenCalled(); expect(token).not.toBeNull(); } else { expect(commandFnSpy).not.toHaveBeenCalled(); expect(callback).toHaveBeenCalledTimes(1); expect(token).toBeNull(); } }); test(`'${fn}' should handle invalid query`, () => { const query = undefined; // @ts-expect-error Easier than typing everything const token = connFn.call(conn, query, callback, options); expect(commandFnSpy).not.toHaveBeenCalled(); expect(callback).toHaveBeenCalledTimes(1); expect(token).toBeNull(); }); test(`'${fn}' should handle invalid options`, () => { const token = connFn.call(conn, singlePathQuery, callback, { start: 4, end: 1 }); expect(commandFnSpy).not.toHaveBeenCalled(); expect(callback).toHaveBeenCalledTimes(1); expect(token).toBeNull(); }); test(`'${fn}' should handle multiple paths`, () => { const token = connFn.call(conn, multiplePathQuery, callback, options); expect(callback).not.toHaveBeenCalled(); if (isSearch) { expect(commandFnSpy).toHaveBeenCalledWith( { query: multiplePathQuery, ...SEARCH_OPTIONS }, expect.any(Function), ); } else { expect(commandFnSpy).toHaveBeenCalledWith( command, { query: multiplePathQuery }, expect.any(Function), ); } expect(token).not.toBeNull(); }); test(`'${fn}' should handle single path`, () => { const token = connFn.call(conn, singlePathQuery, callback, options); expect(callback).not.toHaveBeenCalled(); if (isSearch) { expect(commandFnSpy).toHaveBeenCalledWith( { query: singlePathQuery, ...SEARCH_OPTIONS }, expect.any(Function), ); } else { expect(commandFnSpy).toHaveBeenCalledWith( command, { query: singlePathQuery }, expect.any(Function), ); } expect(token).not.toBeNull(); }); test(`'${fn}' should handle root path`, () => { const token = connFn.call(conn, rootQuery, callback, options); expect(callback).not.toHaveBeenCalled(); if (isSearch) { expect(commandFnSpy).toHaveBeenCalledWith( { query: rootQuery, ...SEARCH_OPTIONS }, expect.any(Function), ); } else { expect(commandFnSpy).toHaveBeenCalledWith( command, { query: rootQuery }, expect.any(Function), ); } expect(token).not.toBeNull(); }); test('should call callback with data', () => { const token = connFn.call(conn, rootQuery, callback, options); if (token) { // Send message conn.websocket.dispatchEvent( new MessageEvent('message', { data: JSON.stringify({ token, result: RESULT }), }), ); expect(callback).toHaveBeenCalledWith( null, RESULT, undefined, token, createRequestContext(command, token, rootQuery, options), ); } expect(token).not.toBeNull(); }); test('should call callback with error', () => { const token = connFn.call(conn, rootQuery, callback, options); if (token) { // Send message conn.websocket.dispatchEvent( new MessageEvent('message', { data: JSON.stringify({ token, error: ERROR_MESSAGE, status: ERROR_STATUS, }), }), ); expect(callback).toHaveBeenCalledWith( expect.stringContaining(ERROR_MESSAGE), undefined, ERROR_STATUS, token, createRequestContext(command, token, rootQuery, options), ); } expect(token).not.toBeNull(); }); }); describe.each([ ['getAndSubscribe', GET_AND_SUBSCRIBE], ['subscribe', SUBSCRIBE], ['searchSubscribe', SEARCH_SUBSCRIBE, true], ['runStreamingService', SERVICE_REQUEST, false, true], ])('Subscribe Queries', (fn, command, isSearch?, isService?) => { const callback = jest.fn(); const options = {} as Options & SearchOptions; let conn: Connector; let commandFnSpy: jest.SpyInstance; let connFn: ( q: Query | ServiceRequest, cb: NotifCallback, o?: SearchOptions | Options, ) => SubscriptionIdentifier | null; const RESULT = { dataset: 'Dodgers' }; function createRequestContext( c: string, token: string, queryOrRequest: Query | ServiceRequest, o: SearchOptions | Options, ): RequestContext { let params: ServiceRequest | SearchParams | QueryParams = { query: queryOrRequest as Query }; if (isSearch && !isService) { const sanitizedSearchOptions = sanitizeSearchOptions(o as SearchOptions); params = { query: queryOrRequest as Query, search: sanitizedSearchOptions.search, searchType: sanitizedSearchOptions.searchType, }; } if (command === GET_AND_SUBSCRIBE) { const sanitizedOptions = sanitizeOptions(o as Options); params = { query: queryOrRequest as Query, start: sanitizedOptions.start, end: sanitizedOptions.end, versions: sanitizedOptions.versions, }; } if (isService) { params = queryOrRequest as ServiceRequest; } return { command: c as WsCommand, token, encodedParams: toBinaryKey(params), }; } beforeEach(() => { conn = new Connector(); // @ts-expect-error Easier than typing everything connFn = conn[fn]; commandFnSpy = jest.spyOn(conn, 'stream'); conn.run('ws://localhost:8080'); conn.websocket.dispatchEvent(new MessageEvent('open', {})); }); afterEach(() => { callback.mockClear(); commandFnSpy.mockClear(); }); test(`'${fn}' should handle empty query`, () => { const query: Query = []; if (isSearch || isService) { const subscriptionId = connFn.call(conn, query, callback); expect(commandFnSpy).toHaveBeenCalledTimes(1); expect(callback).not.toHaveBeenCalled(); expect(subscriptionId).not.toBeNull(); } else { const subscriptionId = connFn.call(conn, query, callback); expect(commandFnSpy).not.toHaveBeenCalled(); expect(callback).toHaveBeenCalledTimes(1); expect(subscriptionId).toBeNull(); } }); test(`'${fn}' should handle invalid query`, () => { const query = undefined; // @ts-expect-error Easier than typing everything const subscriptionId = connFn.call(conn, query, callback); expect(commandFnSpy).not.toHaveBeenCalled(); expect(callback).toHaveBeenCalledTimes(1); expect(subscriptionId).toBeNull(); }); test(`'${fn}' should handle invalid options`, () => { const subscriptionId = connFn.call(conn, isService ? serviceQuery : singlePathQuery, callback, { start: 10, end: 5, }); if (isSearch) { expect(subscriptionId).not.toBeNull(); expect(callback).not.toHaveBeenCalled(); expect(commandFnSpy).toHaveBeenCalledWith( command, { query: singlePathQuery, ...SEARCH_OPTIONS }, expect.any(Function), ); } else if (isService) { expect(subscriptionId).not.toBeNull(); expect(callback).not.toHaveBeenCalled(); expect(commandFnSpy).toHaveBeenCalledWith(command, serviceQuery, expect.any(Function)); } else if (command === GET_AND_SUBSCRIBE) { expect(commandFnSpy).not.toHaveBeenCalled(); expect(callback).toHaveBeenCalledTimes(1); expect(subscriptionId).toBeNull(); } else { expect(subscriptionId).not.toBeNull(); expect(callback).not.toHaveBeenCalled(); expect(commandFnSpy).toHaveBeenCalledWith( command, { query: singlePathQuery }, expect.any(Function), ); } }); test(`'${fn}' should handle multiple paths`, () => { // Service does not support multiple path query; if (isService) { return; } const subscriptionId = connFn.call(conn, multiplePathQuery, callback, options); expect(callback).not.toHaveBeenCalled(); if (isSearch) { expect(commandFnSpy).toHaveBeenCalledWith( command, { query: multiplePathQuery, ...SEARCH_OPTIONS }, expect.any(Function), ); } else { expect(commandFnSpy).toHaveBeenCalledWith( command, { query: multiplePathQuery }, expect.any(Function), ); } expect(subscriptionId).not.toBeNull(); }); test(`'${fn}' should handle single path`, () => { const subscriptionId = connFn.call( conn, isService ? serviceQuery : singlePathQuery, callback, options, ); expect(callback).not.toHaveBeenCalled(); if (isSearch) { expect(commandFnSpy).toHaveBeenCalledWith( command, { query: singlePathQuery, ...SEARCH_OPTIONS }, expect.any(Function), ); } else if (isService) { expect(commandFnSpy).toHaveBeenCalledWith(command, serviceQuery, expect.any(Function)); } else { expect(commandFnSpy).toHaveBeenCalledWith( command, { query: singlePathQuery }, expect.any(Function), ); } expect(subscriptionId).not.toBeNull(); }); test(`'${fn}' should handle root path`, () => { // This test is not valid for service if (isService) { return; } const subscriptionId = connFn.call(conn, rootQuery, callback, options); expect(callback).not.toHaveBeenCalled(); if (isSearch) { expect(commandFnSpy).toHaveBeenCalledWith( command, { query: rootQuery, ...SEARCH_OPTIONS }, expect.any(Function), ); } else { expect(commandFnSpy).toHaveBeenCalledWith( command, { query: rootQuery }, expect.any(Function), ); } expect(subscriptionId).not.toBeNull(); }); test(`'${fn}' should call callback with data`, () => { const q = isService ? serviceQuery : rootQuery; const subscriptionId = connFn.call(conn, q, callback, options); if (subscriptionId) { // Send message conn.websocket.dispatchEvent( new MessageEvent('message', { data: JSON.stringify({ token: subscriptionId.token, result: RESULT }), }), ); expect(callback).toHaveBeenCalledWith( null, RESULT, undefined, subscriptionId.token, createRequestContext(command, subscriptionId.token, q, { search: '' }), ); } expect(subscriptionId).not.toBeNull(); }); test(`'${fn}' should call callback with error`, () => { const q = isService ? serviceQuery : rootQuery; const subscriptionId = connFn.call(conn, q, callback, options); if (subscriptionId) { // Send message conn.websocket.dispatchEvent( new MessageEvent('message', { data: JSON.stringify({ token: subscriptionId.token, error: ERROR_MESSAGE, status: ERROR_STATUS, }), }), ); expect(callback).toHaveBeenCalledWith( expect.stringContaining(ERROR_MESSAGE), undefined, ERROR_STATUS, subscriptionId.token, createRequestContext(command, subscriptionId.token, q, { search: '' }), ); } expect(subscriptionId).not.toBeNull(); }); }); <file_sep>// Copyright (c) 2018, Arista Networks, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import { encode, decode, Codec } from 'a-msgpack'; import { fromByteArray, toByteArray } from 'base64-js'; import { CloseParams, CloudVisionBatchedNotifications, CloudVisionBatchedResult, CloudVisionDatasets, CloudVisionNotifs, CloudVisionResult, CloudVisionServiceResult, CloudVisionStatus, NotifCallback, Options, PublishCallback, Query, RequestContext, SearchOptions, SearchType, SubscriptionIdentifier, } from '../types'; import { ALL_SEARCH_TYPES, EOF_CODE, ERROR, SEARCH_TYPE_ANY } from './constants'; import Emitter from './emitter'; import { log } from './logger'; interface ExplicitSearchOptions extends SearchOptions { searchType: SearchType; } export interface ExplicitOptions extends Options { end: number | undefined; start: number | undefined; versions?: number; } /** * Checks if an argument is valid (a number larger than 0). */ export function isValidArg(val?: number): val is number { return typeof val === 'number' && val > 0; } /** * Checks if a timestamp value is specified in microseconds. */ export function isMicroSeconds(val: number): boolean { return val / 1e15 > 1; } /** * Returns sanitized version of [[Options]]. * It does a number of things: * - If a timestamp is passed as a millisecond timestamp, it will * be converted to microseconds. * - If start, end and versions are invalid, the value for the * option will be set as `undefined` * @param options a map of all **unsanitized** connector [[Options]] * @return a map of all [[Options]] with their **sanitized** values */ export function sanitizeOptions(options: Options): ExplicitOptions { const { start, end, versions } = options; let startInt: number | undefined; let endInt: number | undefined; let versionsInt: number | undefined; if (isValidArg(start)) { startInt = Math.floor(start) * (isMicroSeconds(start) ? 1 : 1e6); } if (isValidArg(end)) { endInt = Math.floor(end) * (isMicroSeconds(end) ? 1 : 1e6); } if (isValidArg(versions)) { versionsInt = Math.floor(versions); } return { start: startInt, end: endInt, versions: versionsInt, }; } /** * Formats a message specifying all invalid params */ export function invalidParamMsg(start: number, end: number, versions?: number): string { return `invalid params: start: ${start}, end: ${end}, versions: ${versions || 'undefined'}`; } /** * Validates all [[Options]]. If validation passes, `true` will be returned. * If there are errors the callback ([[NotifCallback]]) is trigged with an error message. */ export function validateOptions(options: Options, callback: NotifCallback): boolean { const { start, end, versions } = options; if (start && end && start >= end) { callback(invalidParamMsg(start, end, versions)); return false; } if (start && versions) { callback('Defining start and versions is invalid'); return false; } return true; } /** * Validates the [[Query]]. If validation passes `true` will be returned. * If there are errors the callback is trigged with an error message. */ export function validateQuery(query: Query, callback: NotifCallback, allowEmpty = false): boolean { if (!Array.isArray(query)) { callback('`query` param must be an array'); return false; } if (!allowEmpty && (!query || !query.length)) { callback('`query` param cannot be empty'); return false; } return true; } /** * Creates a notification callback that properly formats the result for the * passed callback. */ export function makeNotifCallback(callback: NotifCallback, options: Options = {}): NotifCallback { const notifCallback = ( err: string | null, result?: CloudVisionResult | CloudVisionBatchedResult | CloudVisionServiceResult, status?: CloudVisionStatus, token?: string, requestContext?: RequestContext, ): void => { if (status && status.code === EOF_CODE) { callback(null, undefined, status, token, requestContext); return; } if (err) { callback( `Error: ${err}\nOptions: ${JSON.stringify(options)}`, undefined, status, token, requestContext, ); // Send an extra EOF response to mark notification as complete. callback(null, undefined, { code: EOF_CODE }, token, requestContext); return; } const datasets = result as CloudVisionDatasets; if (datasets?.datasets) { callback(null, datasets, status, token, requestContext); return; } const notifs = result as CloudVisionNotifs | CloudVisionBatchedNotifications; if (notifs?.dataset) { callback(null, notifs, status, token, requestContext); return; } // if none of the cases above apply, then it's a service request if (notifs) { callback(null, notifs, status, token, requestContext); } }; return notifCallback; } /** * Creates the proper params for a [[Connector.close]] call. This will make sure that all * callbacks attached to the token are unbound before adding the token to the * close params. */ export function createCloseParams( streams: SubscriptionIdentifier[] | SubscriptionIdentifier, eventsMap: Emitter, ): CloseParams | null { const closeParams: CloseParams = {}; if (Array.isArray(streams)) { const streamsLen = streams.length; for (let i = 0; i < streamsLen; i += 1) { const { token, callback } = streams[i]; const remainingCallbacks = eventsMap.unbind(token, callback); // Get number of registered callbacks for each stream, to determine which to close if (remainingCallbacks === 0) { closeParams[token] = true; } } } else { const { token, callback } = streams; const remainingCallbacks = eventsMap.unbind(token, callback); // Get number of registered callbacks for each stream, to determine which to close if (remainingCallbacks === 0) { closeParams[token] = true; } } return Object.keys(closeParams).length ? closeParams : null; } /** * Creates a publish callback that properly formats the result for the * passed callback. When the status code is [[EOF_CODE]], the callback will be * called with its first argument being `true`, indicating that the publish has * succeeded. * Otherwise the callback will be called with its first argument being `false`, * indicating that the publish has failed, and the second will contain the * error message. */ export function makePublishCallback(callback: PublishCallback): NotifCallback { const publishCallback = ( err: string | null, _result?: | CloudVisionBatchedNotifications | CloudVisionDatasets | CloudVisionNotifs | CloudVisionServiceResult | undefined, status?: CloudVisionStatus, ): void => { if (status && status.code === EOF_CODE) { callback(true); return; } if (err) { callback(false, `Error: ${err}\n`); } }; return publishCallback; } /** * Validates a response from the server. This will log any errors to the console * but will not attempt to fix the response. */ export function validateResponse( response: CloudVisionResult | CloudVisionBatchedResult | CloudVisionServiceResult, status: CloudVisionStatus | {}, token: string, batch: boolean, ): void { if (status && Object.keys(status).length) { // This is a status message which does not need to be validated return; } const notifResponse = response as CloudVisionNotifs; /* eslint-disable no-console */ if (notifResponse.dataset && !notifResponse.dataset.name) { log(ERROR, "No key 'name' found in dataset", undefined, token); return; } if (notifResponse.dataset && !notifResponse.dataset.type) { log(ERROR, "No key 'type' found in dataset", undefined, token); return; } if (notifResponse.dataset && !notifResponse.notifications) { log(ERROR, "No key 'notifications' found in response", undefined, token); return; } if (!batch && notifResponse.dataset && !Array.isArray(notifResponse.notifications)) { log(ERROR, "Key 'notifications' is not an array", undefined, token); } /* eslint-enable no-console */ } /** * Returns sanitized version of [[SearchOptions]]. * * If no search type is given, it will default to [[SEARCH_TYPE_ANY]]. * * @param searchOptions a map of all **unsanitized** connector [[SearchOptions]] * @return a map of all [[SearchOptions]] with their **sanitized** values */ export function sanitizeSearchOptions(searchOptions: SearchOptions): ExplicitSearchOptions { const actualSearchType = searchOptions.searchType; let explicitSearchType: SearchType = SEARCH_TYPE_ANY; if (actualSearchType && ALL_SEARCH_TYPES.has(actualSearchType)) { explicitSearchType = actualSearchType; } return { search: searchOptions.search || '', searchType: explicitSearchType, }; } /** * Returns the NEAT encoded version of the parameter `key`. * * @param key any value to encode. */ export function toBinaryKey(key: unknown): string { return fromByteArray(encode(key, { extensionCodec: Codec })); } /** * Returns the decoded value of a given base64, NEAT encoded string * * @param keyString base64, NEAT encoded value. */ export function fromBinaryKey(keyString: string, useJSBI = true): unknown { return decode(toByteArray(keyString), { extensionCodec: Codec, useJSBI }); } <file_sep>// Copyright (c) 2018, Arista Networks, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import { ExtensionCodec } from '../ExtensionCodec'; import { decode } from '../decode'; import { encode } from '../encode'; import { Pointer, Wildcard } from './NeatTypes'; type PointerEncoder = (data: Pointer) => Uint8Array; type PointerDecoder = (buffer: Uint8Array) => Pointer; type WildcardEncoder = () => Uint8Array; type WildcardDecoder = () => Wildcard; export function encodePointer(codec: ExtensionCodec): PointerEncoder { return (data: Pointer): Uint8Array => { return encode(data.value, { extensionCodec: codec }); }; } export function decodePointer(codec: ExtensionCodec): PointerDecoder { return (buffer: Uint8Array): Pointer => { const pointer = decode(buffer, { extensionCodec: codec }); if (Array.isArray(pointer)) { return new Pointer(pointer); } return new Pointer(); }; } export function encodeWildcard(): WildcardEncoder { return (): Uint8Array => { return new Uint8Array(); }; } export function decodeWildcard(): WildcardDecoder { return (): Wildcard => { return new Wildcard(); }; } <file_sep>import type { Observable } from 'rxjs'; import type { grpc } from '@arista/grpc-web'; export interface GrpcEnd { code: grpc.Code; message: string; trailers: grpc.Metadata; } export interface GrpcInvoke<T> { end$: Observable<GrpcEnd>; headers$: Observable<grpc.Metadata>; message$: Observable<T>; } /** Represents the combination of the GRPC code along with any message detailing the failure. */ export interface GrpcCodeWithMessage { code: grpc.Code; message: string; trailers?: grpc.Metadata; } export interface GrpcControlErrorMessage { error: GrpcCodeWithMessage; } export interface GrpcControlMetaDataMessage { metadata: grpc.Metadata; } export type GrpcControlMessage = GrpcControlErrorMessage | GrpcControlMetaDataMessage; export interface GrpcSource<T> { /** gRPC response messages. */ data$: Observable<T>; /** gRPC control messages. */ message$: Observable<GrpcControlMessage>; } /** * Includes all [grpc invoke options](https://github.com/improbable-eng/grpc-web/blob/master/client/grpc-web/docs/invoke.md#invokerpcoptions) * except for `onMessage`, `onEnd` and `onHeaders`. */ export type RpcOptions<Req extends grpc.ProtobufMessage, Res extends grpc.ProtobufMessage> = Omit< grpc.InvokeRpcOptions<Req, Res>, 'onEnd' | 'onHeaders' | 'onMessage' >; <file_sep>/* eslint-env jest */ import { Pointer } from 'a-msgpack'; import { fromBinaryKey, toBinaryKey } from '../src/utils'; const binaryKeyTestCases = [ { encodedValue: 'xAtEYXRhc2V0SW5mbw==', decodedValue: 'DatasetInfo', }, { encodedValue: 'gsQETmFtZcQSZnJvbnRUb0JhY2tBaXJmbG93xAVWYWx1ZQE=', decodedValue: { Name: 'frontToBackAirflow', Value: 1 }, }, { encodedValue: 'xzQAlcQFU3lzZGLEC2Vudmlyb25tZW50xAp0aGVybW9zdGF0xAZzdGF0dXPECWZhbkNvbmZpZw==', decodedValue: new Pointer(['Sysdb', 'environment', 'thermostat', 'status', 'fanConfig']), }, { encodedValue: 'Kg==', decodedValue: 42, }, { encodedValue: 'y0BFJmZmZmZm', decodedValue: 42.3, }, { encodedValue: 'lAEKCAs=', decodedValue: [1, 10, 8, 11], }, { encodedValue: 'ww==', decodedValue: true, }, { encodedValue: 'wg==', decodedValue: false, }, ]; describe('toBinaryKey', () => { test('should create the proper binary key given any key', () => { binaryKeyTestCases.forEach((testCase) => { expect(toBinaryKey(testCase.decodedValue)).toBe(testCase.encodedValue); }); }); }); describe('fromBinaryKey', () => { test('should create the proper binary key given any key', () => { binaryKeyTestCases.forEach((testCase) => { expect(fromBinaryKey(testCase.encodedValue)).toEqual(testCase.decodedValue); }); }); }); <file_sep>import type { GrpcControlMessage } from '@types'; import { filter, Observable, OperatorFunction } from 'rxjs'; import { bufferOnce } from '../operators'; import { isInitialSyncCompleteMessage } from './utils'; export function bufferUntilInitialSyncComplete<T>( message$: Observable<GrpcControlMessage>, ): OperatorFunction<T, T[]> { return bufferOnce(message$.pipe(filter(isInitialSyncCompleteMessage))); } <file_sep># Change Log All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. ## [5.0.2](https://github.com/aristanetworks/cloudvision/compare/v5.0.1...v5.0.2) (2023-01-18) **Note:** Version bump only for package cloudvision-grpc-web ## [5.0.1](https://github.com/aristanetworks/cloudvision/compare/v5.0.0...v5.0.1) (2022-07-18) **Note:** Version bump only for package cloudvision-grpc-web # [5.0.0](https://github.com/aristanetworks/cloudvision/compare/v4.14.0...v5.0.0) (2022-07-11) **Note:** Version bump only for package cloudvision-grpc-web # [4.14.0](https://github.com/aristanetworks/cloudvision/compare/v4.13.1...v4.14.0) (2022-05-30) ### Features * **grpc-web:** Refactor fromGrpcInvoke ([#786](https://github.com/aristanetworks/cloudvision/issues/786)) ([e8794e2](https://github.com/aristanetworks/cloudvision/commit/e8794e2f2d17d0884aeb695c7c8c1217323ab4a3)) ## [4.13.1](https://github.com/aristanetworks/cloudvision/compare/v4.13.0...v4.13.1) (2022-05-05) ### Bug Fixes * **cloudvision-grpc-web:** Defer requests until an observer is listening ([#785](https://github.com/aristanetworks/cloudvision/issues/785)) ([43e4281](https://github.com/aristanetworks/cloudvision/commit/43e4281b4e21ae74076eac6c8d4e7c9d0f760b24)) # [4.13.0](https://github.com/aristanetworks/cloudvision/compare/v4.12.2...v4.13.0) (2022-04-26) ### Bug Fixes * **cloudvision-grpc-web:** Add a try/catch around request close ([#773](https://github.com/aristanetworks/cloudvision/issues/773)) ([1350e56](https://github.com/aristanetworks/cloudvision/commit/1350e564d384f07440052d86e8d70d3b27137daa)) ### Features * **cloudvision-grpc-web:** Add support to close requests on unsubscribe ([#770](https://github.com/aristanetworks/cloudvision/issues/770)) ([4656263](https://github.com/aristanetworks/cloudvision/commit/46562635baedec15d2fb03c233992ec8e663d2a6)) ## [4.12.2](https://github.com/aristanetworks/cloudvision/compare/v4.12.1...v4.12.2) (2022-04-04) **Note:** Version bump only for package cloudvision-grpc-web ## [4.12.1](https://github.com/aristanetworks/cloudvision/compare/v4.12.0...v4.12.1) (2022-03-21) **Note:** Version bump only for package cloudvision-grpc-web # [4.12.0](https://github.com/aristanetworks/cloudvision/compare/v4.11.0...v4.12.0) (2021-10-05) ### Features * **grpc-web:** Export operators ([#578](https://github.com/aristanetworks/cloudvision/issues/578)) ([218a5de](https://github.com/aristanetworks/cloudvision/commit/218a5deac53a6de73eb01c4649710c7d836fbdc4)) # [4.11.0](https://github.com/aristanetworks/cloudvision/compare/v4.10.1...v4.11.0) (2021-10-04) ### Bug Fixes * **cloudvision-grpc-web:** hanging test in CI ([#563](https://github.com/aristanetworks/cloudvision/issues/563)) ([58a7e66](https://github.com/aristanetworks/cloudvision/commit/58a7e66af159defbec473dfe7ec7b88e262cb308)) ### Features * **grpc-web:** Refactor package ([#558](https://github.com/aristanetworks/cloudvision/issues/558)) ([eac7fc3](https://github.com/aristanetworks/cloudvision/commit/eac7fc31b8bd6a926090e30e92e555289a377a41)) ## [4.10.1](https://github.com/aristanetworks/cloudvision/compare/v4.10.0...v4.10.1) (2021-09-17) **Note:** Version bump only for package cloudvision-grpc-web # [4.10.0](https://github.com/aristanetworks/cloudvision/compare/v4.9.2...v4.10.0) (2021-09-08) ### Features * **cloudvision-grpc-web:** Use Arista fork of protobuf.js ([#541](https://github.com/aristanetworks/cloudvision/issues/541)) ([33d61d4](https://github.com/aristanetworks/cloudvision/commit/33d61d47fb5f7d9a85b829f027391e5b73fb2776)) ## [4.9.2](https://github.com/aristanetworks/cloudvision/compare/v4.9.1...v4.9.2) (2021-08-06) **Note:** Version bump only for package cloudvision-grpc-web ## [4.9.1](https://github.com/aristanetworks/cloudvision/compare/v4.9.0...v4.9.1) (2021-07-22) ### Bug Fixes * update packages ([#470](https://github.com/aristanetworks/cloudvision/issues/470)) ([264d1e0](https://github.com/aristanetworks/cloudvision/commit/264d1e04045ec9ae2efeaf1ff87cf4b9339626c5)) # [4.9.0](https://github.com/aristanetworks/cloudvision/compare/v4.8.0...v4.9.0) (2021-06-17) ### Features * **cloudvision-grpc-web:** Use RxJS Observables instead of Wonka + Use ts-proto + Fix alias resolutions ([#457](https://github.com/aristanetworks/cloudvision/issues/457)) ([6f84cf2](https://github.com/aristanetworks/cloudvision/commit/6f84cf2cfe9ef9da6df677bed9ef121feac6fd4f)) # [4.8.0](https://github.com/aristanetworks/cloudvision/compare/v4.7.0...v4.8.0) (2021-05-18) ### Features * **cloudvision-grpc-web:** add grpc-web client ([#407](https://github.com/aristanetworks/cloudvision/issues/407)) ([cc0ee18](https://github.com/aristanetworks/cloudvision/commit/cc0ee180b6d2371e807622fcd85dd81ee4440313)) <file_sep>/* eslint-env jest */ import JSBI from 'jsbi'; import { Bool, Float32, Float64, Int, Nil, Pointer, Str, Wildcard } from '../../src/neat/NeatTypes'; describe('NEAT types', () => { const maxInt = Number.MAX_SAFE_INTEGER; const maxIntStr = Number.MAX_SAFE_INTEGER + ''; const maxIntLastDigit = parseInt(maxIntStr[maxIntStr.length - 1], 10); const moreThanMaxInt = maxIntStr.substr(0, maxIntStr.length - 1) + (maxIntLastDigit + 1); test('Bool', () => { expect(new Bool(true).value).toEqual(true); expect(new Bool(false).value).toEqual(false); expect(new Bool(1).value).toEqual(true); expect(new Bool(0).value).toEqual(false); expect(new Bool('true').value).toEqual(true); expect(new Bool('').value).toEqual(false); expect(new Bool(true).toString()).toEqual('true'); expect(new Bool(false).toString()).toEqual('false'); }); test('Float32', () => { expect(new Float32(1).value).toEqual(1.0); expect(new Float32(1.2).value).toEqual(1.2); expect(new Float32(0.3).value).toEqual(0.3); expect(new Float32(1.0).value).toEqual(1.0); expect(new Float32('1.2').value).toEqual(1.2); expect(new Float32(1).toString()).toEqual('1.0'); expect(new Float32(1.2).toString()).toEqual('1.2'); expect(new Float32(0.3).toString()).toEqual('0.3'); expect(new Float32(1.0).toString()).toEqual('1.0'); }); test('Float64', () => { expect(new Float64(1).value).toEqual(1.0); expect(new Float64(1.2).value).toEqual(1.2); expect(new Float64(0.3).value).toEqual(0.3); expect(new Float64(1.0).value).toEqual(1.0); expect(new Float64('1.2').value).toEqual(1.2); expect(new Float64(1).toString()).toEqual('1.0'); expect(new Float64(1.2).toString()).toEqual('1.2'); expect(new Float64(0.3).toString()).toEqual('0.3'); expect(new Float64(1.0).toString()).toEqual('1.0'); }); test('Int', () => { expect(new Int(1.2).value).toEqual(1); expect(new Int(1).value).toEqual(1); expect(new Int('1.2').value).toEqual(1); expect(new Int('1').value).toEqual(1); expect(new Int(maxInt).value).toEqual(maxInt); expect(new Int(moreThanMaxInt).value).toEqual(BigInt(moreThanMaxInt)); expect(new Int(moreThanMaxInt, true).value).toEqual(JSBI.BigInt(moreThanMaxInt)); expect(new Int(maxInt * -1).value).toEqual(maxInt * -1); expect(new Int('-' + moreThanMaxInt).value).toEqual(BigInt(moreThanMaxInt) * BigInt(-1)); expect(new Int(1.2).toString()).toEqual('1'); expect(new Int(1).toString()).toEqual('1'); expect(new Int('1.2').toString()).toEqual('1'); expect(new Int('1').toString()).toEqual('1'); expect(new Int(maxInt).toString()).toEqual(maxInt.toString()); expect(new Int(moreThanMaxInt).toString()).toEqual(moreThanMaxInt); expect(new Int(moreThanMaxInt, true).toString()).toEqual(moreThanMaxInt); expect(new Int(maxInt * -1).toString()).toEqual((maxInt * -1).toString()); expect(new Int('-' + moreThanMaxInt).toString()).toEqual('-' + moreThanMaxInt); }); test('Nil', () => { // Explicitly test that nil will always return null regardless of what args are passed // @ts-expect-error Explicitly test nil expect(new Nil(1).value).toEqual(null); // @ts-expect-error Explicitly test nil expect(new Nil(true).value).toEqual(null); // @ts-expect-error Explicitly test nil expect(new Nil([]).value).toEqual(null); // @ts-expect-error Explicitly test nil expect(new Nil(false).value).toEqual(null); // @ts-expect-error Explicitly test nil expect(new Nil({}).value).toEqual(null); // @ts-expect-error Explicitly test nil expect(new Nil(1).toString()).toEqual('null'); // @ts-expect-error Explicitly test nil expect(new Nil(true).toString()).toEqual('null'); // @ts-expect-error Explicitly test nil expect(new Nil([]).toString()).toEqual('null'); // @ts-expect-error Explicitly test nil expect(new Nil(false).toString()).toEqual('null'); // @ts-expect-error Explicitly test nil expect(new Nil({}).toString()).toEqual('null'); }); test('Pointer', () => { const ptrArray = ['pointer', 'to', { some: 'stuff' }]; const ptrString = 'pointer/to/' + JSON.stringify({ some: 'stuff' }); expect(new Pointer(ptrArray).value).toEqual(ptrArray); expect(new Pointer(ptrString).value).toEqual(ptrArray); expect(new Pointer([]).value).toEqual([]); expect(new Pointer('').value).toEqual([]); expect(new Pointer('/').value).toEqual([]); expect(new Pointer(true).value).toEqual([true]); expect(new Pointer({ object: 'result' }).value).toEqual([{ object: 'result' }]); expect(new Pointer(ptrArray).toString()).toEqual(ptrString); expect(new Pointer(ptrString).toString()).toEqual(ptrString); expect(new Pointer([]).toString()).toEqual(''); expect(new Pointer('').toString()).toEqual(''); expect(new Pointer('/').toString()).toEqual(''); expect(new Pointer(true).toString()).toEqual('true'); expect(new Pointer({ object: 'result' }).toString()).toEqual('{"object":"result"}'); }); test('Str', () => { expect(new Str('string').value).toEqual('string'); expect(new Str(true).value).toEqual('true'); expect(new Str(false).value).toEqual('false'); expect(new Str(1).value).toEqual('1'); expect(new Str(BigInt(moreThanMaxInt)).value).toEqual(moreThanMaxInt); expect(new Str(JSBI.BigInt(moreThanMaxInt)).value).toEqual(moreThanMaxInt); expect(new Str(null).value).toEqual('null'); expect(new Str(undefined).value).toEqual(''); expect(new Str({ hello: 'world' }).value).toEqual(JSON.stringify({ hello: 'world' })); expect(new Str([1, 2]).value).toEqual('[1,2]'); expect(new Str('string').toString()).toEqual('string'); expect(new Str(true).toString()).toEqual('true'); expect(new Str(false).toString()).toEqual('false'); expect(new Str(1).toString()).toEqual('1'); expect(new Str(BigInt(moreThanMaxInt)).toString()).toEqual(moreThanMaxInt); expect(new Str(JSBI.BigInt(moreThanMaxInt)).toString()).toEqual(moreThanMaxInt); expect(new Str(null).toString()).toEqual('null'); expect(new Str(undefined).toString()).toEqual(''); expect(new Str({ hello: 'world' }).toString()).toEqual(JSON.stringify({ hello: 'world' })); expect(new Str([1, 2]).toString()).toEqual('[1,2]'); }); test('Wildcard', () => { const wildcardValue = '*'; // Explicitly test that Wildcard will always return null regardless of what args are passed // @ts-expect-error Explicitly test wildcard expect(new Wildcard(1).value).toEqual(null); // @ts-expect-error Explicitly test wildcard expect(new Wildcard(true).value).toEqual(null); // @ts-expect-error Explicitly test wildcard expect(new Wildcard([]).value).toEqual(null); // @ts-expect-error Explicitly test wildcard expect(new Wildcard(false).value).toEqual(null); // @ts-expect-error Explicitly test wildcard expect(new Wildcard({}).value).toEqual(null); // @ts-expect-error Explicitly test wildcard expect(new Wildcard(1).toString()).toEqual(wildcardValue); // @ts-expect-error Explicitly test wildcard expect(new Wildcard(true).toString()).toEqual(wildcardValue); // @ts-expect-error Explicitly test wildcard expect(new Wildcard([]).toString()).toEqual(wildcardValue); // @ts-expect-error Explicitly test wildcard expect(new Wildcard(false).toString()).toEqual(wildcardValue); // @ts-expect-error Explicitly test wildcard expect(new Wildcard({}).toString()).toEqual(wildcardValue); }); }); <file_sep>import { EventCallback, RequestContext } from './connection'; export type EmitterEvents = Map<string, EventCallback[]>; export type EmitterRequestContext = Map<string, RequestContext>; <file_sep>import type { GrpcControlMessage, GrpcEnd, GrpcInvoke, GrpcSource, RpcOptions } from '@types'; import { map, merge, Observable, Subject } from 'rxjs'; import { grpc } from '@arista/grpc-web'; /** * RxJs wrapper around `grpc.invoke` that creates an Observable. * On subscription, the underlying `grpc.invoke` is called. * On unsubscription, the active request is closed. */ export function fromGrpcInvoke<Req extends grpc.ProtobufMessage, Res extends grpc.ProtobufMessage>( methodDescriptor: grpc.MethodDefinition<Req, Res>, options: RpcOptions<Req, Res>, ): Observable<GrpcInvoke<Res>> { return new Observable((subscriber) => { const headers$ = new Subject<grpc.Metadata>(); const message$ = new Subject<Res>(); const end$ = new Subject<GrpcEnd>(); const rpcOptions: grpc.InvokeRpcOptions<Req, Res> = { ...options, onHeaders(headers) { headers$.next(headers); }, onMessage(response) { message$.next(response); }, onEnd(code, message, trailers) { end$.next({ code, message, trailers }); end$.complete(); headers$.complete(); message$.complete(); subscriber.complete(); }, }; const request = grpc.invoke(methodDescriptor, rpcOptions); subscriber.next({ headers$, message$, end$, }); return () => { try { request.close(); } catch (e) { // Do nothing for now } end$.complete(); headers$.complete(); message$.complete(); }; }); } export function fromGrpcSource<Req extends grpc.ProtobufMessage, Res extends grpc.ProtobufMessage>( methodDescriptor: grpc.MethodDefinition<Req, Res>, options: RpcOptions<Req, Res>, ): Observable<GrpcSource<Res>> { return fromGrpcInvoke(methodDescriptor, options).pipe( // Merge `end$` and `headers$` into a single control message stream map(({ end$, headers$, message$ }): GrpcSource<Res> => { const controlMessage$ = merge( headers$.pipe(map((headers): GrpcControlMessage => ({ metadata: headers }))), end$.pipe(map((end): GrpcControlMessage => ({ error: end }))), ); return { data$: message$, message$: controlMessage$, }; }), ); } <file_sep>import { WsCommand } from './params'; export type ContextCommand = WsCommand | 'connection' | 'NO_COMMAND'; export interface RequestContext { command: ContextCommand; encodedParams: string; token: string; } export interface EventCallback { // eslint-disable-next-line @typescript-eslint/no-explicit-any (requestContext: RequestContext, ...args: any[]): void; } export interface ConnectionCallback { (connEvent: string, wsEvent: Event): void; } /** * Uniquely identifies a `stream` (subscribe) call. Tokens are created based of the command * and request params, so identical calls with have identical tokens. This * means we use the callback to identify the call, if there are multiple of * the same calls. */ export interface SubscriptionIdentifier { callback: EventCallback; token: string; } <file_sep>// Copyright (c) 2018, Arista Networks, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import { EventCallback, RequestContext } from '../types'; import { EmitterEvents, EmitterRequestContext } from '../types/emitter'; import { DEFAULT_CONTEXT } from './constants'; /** * A class that tracks event callbacks by event type. * Callbacks get triggered, when an **emit** event is invoked for a given * event type. */ class Emitter { private events: EmitterEvents; private requestContext: EmitterRequestContext; public constructor() { this.events = new Map(); this.requestContext = new Map(); } /** * Returns the `Map` of events */ public getEventsMap(): EmitterEvents { return this.events; } /** * Returns the `Map` of requestContext */ public getRequestContextMap(): EmitterRequestContext { return this.requestContext; } /** * Returns true if and only if the emitter has callback(s) of the event type */ public has(eventType: string): boolean { return this.events.has(eventType); } /** * Adds the given callback to the event type. * * @returns The number of callbacks subscribed to the event type */ public bind(eventType: string, requestContext: RequestContext, callback: EventCallback): number { let callbacksForEvent = this.events.get(eventType); if (callbacksForEvent) { callbacksForEvent.push(callback); } else { callbacksForEvent = [callback]; this.events.set(eventType, callbacksForEvent); this.requestContext.set(eventType, requestContext); } return callbacksForEvent.length; } /** * Removes the given callback from the event type. * If this is the last callback subscribed to the given event type, then * the event type is removed from the `Map` of events. * * @returns The number of callbacks subscribed to the event type, or null * if the callback is not present in the `Map` of events. */ public unbind(eventType: string, callback: EventCallback): number | null { const callbacksForEvent = this.events.get(eventType); if (!callbacksForEvent) { return null; } const callbackIndex: number = callbacksForEvent.indexOf(callback); if (callbackIndex !== -1) { callbacksForEvent.splice(callbackIndex, 1); this.events.set(eventType, callbacksForEvent); } const callbacksForEventLen: number = callbacksForEvent.length; if (callbacksForEventLen === 0) { this.events.delete(eventType); this.requestContext.delete(eventType); } return callbacksForEventLen; } /** * Removes all callbacks for the given event. * This removes the event type from the `Map` of events. */ public unbindAll(eventType: string): void { this.events.delete(eventType); this.requestContext.delete(eventType); } /** * Triggers all callbacks bound to the given event type. The function can * take extra arguments, which are passed to the callback functions. */ public emit(eventType: string, ...args: unknown[]): void { const callbacksForEvent = this.events.get(eventType); if (!callbacksForEvent) { return; } // iterate in reverse order in case callback calls unbind on the eventType for (let i = callbacksForEvent.length - 1; i >= 0; i -= 1) { const requestContext = this.requestContext.get(eventType) || DEFAULT_CONTEXT; callbacksForEvent[i](requestContext, ...args); } } /** * Unbinds all callbacks for all events. * This clears the `Map` of events. */ public close(): void { this.events.clear(); this.requestContext.clear(); } } export default Emitter; <file_sep>/** * @jest-environment jsdom */ // Copyright (c) 2020, Arista Networks, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Parser from '../src/Parser'; import Wrpc from '../src/Wrpc'; import { ACTIVE_CODE, EOF, EOF_CODE, GET, GET_DATASETS, PUBLISH, SEARCH, SEARCH_SUBSCRIBE, SERVICE_REQUEST, SUBSCRIBE, } from '../src/constants'; import { toBinaryKey } from '../src/utils'; import { CloudVisionParams, CloudVisionQueryMessage, CloudVisionStatus, NotifCallback, QueryParams, RequestContext, StreamCommand, WsCommand, } from '../types'; jest.mock('../src/Parser', () => ({ parse: (res: string) => JSON.parse(res), stringify: (msg: CloudVisionQueryMessage) => JSON.stringify(msg), })); jest.mock('../src/logger', () => { return { log: jest.fn() }; }); type WrpcMethod = 'get' | 'publish' | 'requestService' | 'search'; interface PolymorphicCommandFunction { (command: WsCommand, params: CloudVisionParams, callback: NotifCallback): string; } interface CommandFunction { (p: CloudVisionParams, cb: NotifCallback): string; } const query: QueryParams = { query: [] }; function stringifyMessage(msg: Record<string, unknown>) { return JSON.stringify(msg); } function createRequestContext(command: WsCommand, token: string, params: unknown): RequestContext { return { command, token, encodedParams: toBinaryKey(params), }; } describe.each<[WsCommand, WrpcMethod, boolean]>([ [GET, 'get', true], [PUBLISH, 'publish', false], [GET_DATASETS, 'get', true], [SEARCH, 'search', false], [SERVICE_REQUEST, 'requestService', false], ])('Instrumented Call Commands', (command, fn, polymorphic) => { let wrpc: Wrpc; let ws: WebSocket; let sendSpy: jest.SpyInstance; let eventsEmitterSpy: jest.SpyInstance; let eventsEmitterUnbindSpy: jest.SpyInstance; let eventsEmitterBindSpy: jest.SpyInstance; let polymorphicCommandFn: PolymorphicCommandFunction; let commandFn: CommandFunction; const startSpy = jest.fn(); const infoSpy = jest.fn(); const endSpy = jest.fn(); const callbackSpy = jest.fn(); const ERROR_MESSAGE = 'error'; beforeEach(() => { jest.resetAllMocks(); wrpc = new Wrpc({ batchResults: false, debugMode: false, instrumentationConfig: { commands: [GET, PUBLISH, SEARCH, SERVICE_REQUEST, GET_DATASETS], start: startSpy, info: infoSpy, end: endSpy, }, }); // @ts-expect-error Easier than to type everything commandFn = wrpc[fn]; // @ts-expect-error Easier than to type everything polymorphicCommandFn = wrpc[fn]; wrpc.run('ws://localhost:8080'); ws = wrpc.websocket; sendSpy = jest.spyOn(ws, 'send'); eventsEmitterSpy = jest.spyOn(wrpc.eventsEmitter, 'emit'); eventsEmitterBindSpy = jest.spyOn(wrpc.eventsEmitter, 'bind'); eventsEmitterUnbindSpy = jest.spyOn(wrpc.eventsEmitter, 'unbind'); }); afterEach(() => { sendSpy.mockClear(); eventsEmitterSpy.mockClear(); eventsEmitterBindSpy.mockClear(); eventsEmitterUnbindSpy.mockClear(); callbackSpy.mockClear(); startSpy.mockClear(); infoSpy.mockClear(); endSpy.mockClear(); }); test(`'${fn} + ${command}' should not send instrumentation message start if socket is not running`, () => { let token; if (polymorphic) { token = polymorphicCommandFn.call(wrpc, command, {}, callbackSpy); } else { token = commandFn.call(wrpc, {}, callbackSpy); } expect(callbackSpy).toHaveBeenCalledWith('Connection is down'); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(startSpy).not.toHaveBeenCalled(); expect(infoSpy).not.toHaveBeenCalled(); expect(endSpy).not.toHaveBeenCalled(); expect(token).toBe(null); }); test(`'${fn} + ${command}' should send instrumentation message start if socket is running`, () => { ws.dispatchEvent(new MessageEvent('open', {})); let token; if (polymorphic) { token = polymorphicCommandFn.call(wrpc, command, {}, callbackSpy); } else { token = commandFn.call(wrpc, {}, callbackSpy); } if (token) { const requestContext = createRequestContext(command, token, {}); expect(callbackSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(sendSpy).toHaveBeenCalledTimes(1); expect(sendSpy).toHaveBeenCalledWith( Parser.stringify({ token, command, params: {}, }), ); expect(token).not.toBeNull(); expect(startSpy).toHaveBeenCalledWith(requestContext); expect(infoSpy).not.toHaveBeenCalled(); expect(endSpy).not.toHaveBeenCalled(); } expect(token).not.toBeNull(); }); test(`'${fn} + ${command}' should send instrumentation info message on error`, () => { ws.dispatchEvent(new MessageEvent('open', {})); sendSpy.mockImplementation(() => { throw new Error(ERROR_MESSAGE); }); let token; if (polymorphic) { token = polymorphicCommandFn.call(wrpc, command, {}, callbackSpy); } else { token = commandFn.call(wrpc, {}, callbackSpy); } if (token) { const requestContext = createRequestContext(command, token, {}); expect(sendSpy).toHaveBeenCalledTimes(1); expect(sendSpy).toHaveBeenCalledWith( Parser.stringify({ token, command, params: {}, }), ); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith( new Error(ERROR_MESSAGE), undefined, undefined, token, requestContext, ); expect(eventsEmitterSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); expect(startSpy).toHaveBeenCalledWith(requestContext); expect(infoSpy).toHaveBeenCalledWith(requestContext, { error: new Error(ERROR_MESSAGE) }); expect(endSpy).toHaveBeenCalledWith(requestContext); } expect(token).not.toBeNull(); }); test(`'${fn} + ${command}' should send instrumentation end message on EOF`, () => { const EOF_STATUS: CloudVisionStatus = { code: EOF_CODE }; ws.dispatchEvent(new MessageEvent('open', {})); let token; if (polymorphic) { token = polymorphicCommandFn.call(wrpc, command, {}, callbackSpy); } else { token = commandFn.call(wrpc, {}, callbackSpy); } if (token) { const requestContext = createRequestContext(command, token, {}); ws.dispatchEvent( new MessageEvent('message', { data: stringifyMessage({ token, error: EOF, status: EOF_STATUS }), }), ); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith(EOF, undefined, EOF_STATUS, token, requestContext); expect(eventsEmitterSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterSpy).toHaveBeenCalledWith(token, EOF, undefined, EOF_STATUS); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterUnbindSpy).toHaveBeenCalledWith(token, expect.any(Function)); expect(sendSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); expect(startSpy).toHaveBeenCalledWith(requestContext); expect(infoSpy).toHaveBeenCalledWith(requestContext, { error: EOF }); expect(endSpy).toHaveBeenCalledWith(requestContext); } expect(token).not.toBeNull(); }); }); describe.each<[StreamCommand, 'stream']>([ [SUBSCRIBE, 'stream'], [SEARCH_SUBSCRIBE, 'stream'], [SERVICE_REQUEST, 'stream'], ])('Instrumented Stream Commands', (command, fn) => { let wrpc: Wrpc; let ws: WebSocket; let sendSpy: jest.SpyInstance; let eventsEmitterSpy: jest.SpyInstance; let eventsEmitterUnbindSpy: jest.SpyInstance; let eventsEmitterBindSpy: jest.SpyInstance; let commandFn: Wrpc['stream']; const callbackSpy = jest.fn(); const startSpy = jest.fn(); const infoSpy = jest.fn(); const endSpy = jest.fn(); const ACTIVE_STATUS: CloudVisionStatus = { code: ACTIVE_CODE }; beforeEach(() => { jest.resetAllMocks(); wrpc = new Wrpc({ batchResults: false, debugMode: false, instrumentationConfig: { commands: [SUBSCRIBE, SERVICE_REQUEST, SEARCH_SUBSCRIBE], start: startSpy, info: infoSpy, end: endSpy, }, }); commandFn = wrpc[fn]; wrpc.run('ws://localhost:8080'); ws = wrpc.websocket; sendSpy = jest.spyOn(ws, 'send'); eventsEmitterSpy = jest.spyOn(wrpc.eventsEmitter, 'emit'); eventsEmitterBindSpy = jest.spyOn(wrpc.eventsEmitter, 'bind'); eventsEmitterUnbindSpy = jest.spyOn(wrpc.eventsEmitter, 'unbind'); }); afterEach(() => { sendSpy.mockClear(); eventsEmitterSpy.mockClear(); eventsEmitterBindSpy.mockClear(); eventsEmitterUnbindSpy.mockClear(); callbackSpy.mockClear(); startSpy.mockClear(); infoSpy.mockClear(); endSpy.mockClear(); }); test(`'${fn} + ${command}' should not send instrumentation info message if socket is not running`, () => { const subscriptionId = commandFn.call(wrpc, command, query, callbackSpy); expect(callbackSpy).toHaveBeenCalledWith('Connection is down'); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(subscriptionId).toBe(null); expect(startSpy).not.toHaveBeenCalled(); expect(infoSpy).not.toHaveBeenCalled(); expect(endSpy).not.toHaveBeenCalled(); }); test(`'${fn} + ${command}' should send instrumentation info message if socket is running`, () => { ws.dispatchEvent(new MessageEvent('open', {})); const subscriptionId = commandFn.call(wrpc, command, query, callbackSpy); if (subscriptionId?.token) { const token = subscriptionId.token; const requestContext = createRequestContext(command, token, query); expect(callbackSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(sendSpy).toHaveBeenCalledTimes(1); expect(sendSpy).toHaveBeenCalledWith( Parser.stringify({ token, command, params: query, }), ); expect(subscriptionId).not.toBeNull(); expect(startSpy).toHaveBeenCalledWith(requestContext); expect(infoSpy).not.toHaveBeenCalled(); expect(endSpy).not.toHaveBeenCalled(); } expect(subscriptionId).not.toBeNull(); }); test(`'${fn} + ${command}' should send instrumentation end message on EOF`, () => { const EOF_STATUS: CloudVisionStatus = { code: EOF_CODE }; ws.dispatchEvent(new MessageEvent('open', {})); const subscriptionId = commandFn.call(wrpc, command, query, callbackSpy); if (subscriptionId?.token) { const token = subscriptionId.token; const requestContext = createRequestContext(command, token, query); ws.dispatchEvent( new MessageEvent('message', { data: stringifyMessage({ token, error: EOF, status: EOF_STATUS }), }), ); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith(EOF, undefined, EOF_STATUS, token, requestContext); expect(eventsEmitterSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterSpy).toHaveBeenCalledWith(token, EOF, undefined, EOF_STATUS); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(eventsEmitterUnbindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterUnbindSpy).toHaveBeenCalledWith(token, expect.any(Function)); expect(sendSpy).toHaveBeenCalledTimes(1); expect(token).not.toBeNull(); expect(startSpy).toHaveBeenCalledWith(requestContext); expect(infoSpy).toHaveBeenCalledWith(requestContext, { error: EOF }); expect(endSpy).toHaveBeenCalledWith(requestContext); } expect(subscriptionId).not.toBeNull(); }); test(`'${fn} + ${command}' should send instrumentation message if ACK message is received`, () => { ws.dispatchEvent(new MessageEvent('open', {})); const subscriptionId = commandFn.call(wrpc, command, query, callbackSpy); if (subscriptionId?.token) { const token = subscriptionId.token; const requestContext = createRequestContext(command, token, query); ws.dispatchEvent( new MessageEvent('message', { data: stringifyMessage({ token, status: ACTIVE_STATUS }), }), ); expect(sendSpy).toHaveBeenCalledTimes(1); expect(sendSpy).toHaveBeenCalledWith( Parser.stringify({ token, command, params: query, }), ); expect(callbackSpy).toHaveBeenCalledTimes(1); expect(callbackSpy).toHaveBeenCalledWith( null, undefined, ACTIVE_STATUS, token, requestContext, ); expect(eventsEmitterSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterSpy).toHaveBeenCalledWith(token, null, undefined, ACTIVE_STATUS); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(token).not.toBeNull(); expect(startSpy).toHaveBeenCalledWith(requestContext); expect(infoSpy).toHaveBeenCalledWith(requestContext, { message: 'stream active' }); expect(endSpy).not.toHaveBeenCalled(); } expect(subscriptionId).not.toBeNull(); }); }); describe.each<[WsCommand, 'stream' | 'get']>([ [GET, 'get'], [SUBSCRIBE, 'stream'], [SEARCH_SUBSCRIBE, 'stream'], [SERVICE_REQUEST, 'stream'], ])('Non Instrumented Commands', (command, fn) => { let wrpc: Wrpc; let ws: WebSocket; let sendSpy: jest.SpyInstance; let eventsEmitterSpy: jest.SpyInstance; let eventsEmitterUnbindSpy: jest.SpyInstance; let eventsEmitterBindSpy: jest.SpyInstance; let commandFn: Wrpc['stream']; const callbackSpy = jest.fn(); const startSpy = jest.fn(); const infoSpy = jest.fn(); const endSpy = jest.fn(); beforeEach(() => { jest.resetAllMocks(); wrpc = new Wrpc({ batchResults: false, debugMode: false, instrumentationConfig: { commands: [PUBLISH], start: startSpy, info: infoSpy, end: endSpy, }, }); // @ts-expect-error Easier than to type everything commandFn = wrpc[fn]; wrpc.run('ws://localhost:8080'); ws = wrpc.websocket; sendSpy = jest.spyOn(ws, 'send'); eventsEmitterSpy = jest.spyOn(wrpc.eventsEmitter, 'emit'); eventsEmitterBindSpy = jest.spyOn(wrpc.eventsEmitter, 'bind'); eventsEmitterUnbindSpy = jest.spyOn(wrpc.eventsEmitter, 'unbind'); }); afterEach(() => { sendSpy.mockClear(); eventsEmitterSpy.mockClear(); eventsEmitterBindSpy.mockClear(); eventsEmitterUnbindSpy.mockClear(); callbackSpy.mockClear(); startSpy.mockClear(); infoSpy.mockClear(); endSpy.mockClear(); }); test(`'${fn} + ${command}' should not send instrumentation info message if socket is not running`, () => { // @ts-expect-error Easier than to type everything const subscriptionId = commandFn.call(wrpc, command, query, callbackSpy); expect(callbackSpy).toHaveBeenCalledWith('Connection is down'); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(subscriptionId).toBe(null); expect(startSpy).not.toHaveBeenCalled(); expect(infoSpy).not.toHaveBeenCalled(); expect(endSpy).not.toHaveBeenCalled(); }); test(`'${fn} + ${command}' should send instrumentation message if socket is running, but command is not instrumented`, () => { ws.dispatchEvent(new MessageEvent('open', {})); // @ts-expect-error Easier than to type everything const subscriptionId = commandFn.call(wrpc, command, query, callbackSpy); if (subscriptionId?.token) { const token = subscriptionId.token; const requestContext = createRequestContext(command, token, query); expect(callbackSpy).not.toHaveBeenCalled(); expect(eventsEmitterSpy).not.toHaveBeenCalled(); expect(eventsEmitterUnbindSpy).not.toHaveBeenCalled(); expect(eventsEmitterBindSpy).toHaveBeenCalledTimes(1); expect(eventsEmitterBindSpy).toHaveBeenCalledWith( token, requestContext, expect.any(Function), ); expect(sendSpy).toHaveBeenCalledTimes(1); expect(sendSpy).toHaveBeenCalledWith( Parser.stringify({ token, command, params: query, }), ); expect(subscriptionId).not.toBeNull(); expect(startSpy).not.toHaveBeenCalled(); expect(infoSpy).not.toHaveBeenCalled(); expect(endSpy).not.toHaveBeenCalled(); } expect(subscriptionId).not.toBeNull(); }); }); <file_sep>import JSBI from 'jsbi'; /** * Check if a value looks like a JSBI value. */ export function isJsbi(value: unknown): value is JSBI { // if it has __clzmsd it's probably jsbi return Array.isArray(value) && '__clzmsd' in value; } export function isPlainObject(object: {}): boolean { if (Object.getPrototypeOf(object) === null) { return true; } let proto = object; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(object) === proto; } <file_sep># Change Log All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. ## [5.0.2](https://github.com/aristanetworks/cloudvision/compare/v5.0.1...v5.0.2) (2023-01-18) **Note:** Version bump only for package cloudvision-connector ## [5.0.1](https://github.com/aristanetworks/cloudvision/compare/v5.0.0...v5.0.1) (2022-07-18) **Note:** Version bump only for package cloudvision-connector # [5.0.0](https://github.com/aristanetworks/cloudvision/compare/v4.14.0...v5.0.0) (2022-07-11) * chore(deps)!: update dependency jsbi to v4 (#598) ([c0672d9](https://github.com/aristanetworks/cloudvision/commit/c0672d92c0391a75e081246a4cbb25ff2fc3cfca)), closes [#598](https://github.com/aristanetworks/cloudvision/issues/598) ### BREAKING CHANGES * Upgrade to JSBI v4 # [4.14.0](https://github.com/aristanetworks/cloudvision/compare/v4.13.1...v4.14.0) (2022-05-30) **Note:** Version bump only for package cloudvision-connector ## [4.13.1](https://github.com/aristanetworks/cloudvision/compare/v4.13.0...v4.13.1) (2022-05-05) **Note:** Version bump only for package cloudvision-connector # [4.13.0](https://github.com/aristanetworks/cloudvision/compare/v4.12.2...v4.13.0) (2022-04-26) **Note:** Version bump only for package cloudvision-connector ## [4.12.2](https://github.com/aristanetworks/cloudvision/compare/v4.12.1...v4.12.2) (2022-04-04) ### Bug Fixes * **timestamps:** Add nanosecond support to timestamps ([#762](https://github.com/aristanetworks/cloudvision/issues/762)) ([93ae5cc](https://github.com/aristanetworks/cloudvision/commit/93ae5ccd3c395bcacf504cfa44181245cba16795)) ## [4.12.1](https://github.com/aristanetworks/cloudvision/compare/v4.12.0...v4.12.1) (2022-03-21) ### Bug Fixes * **timestamps:** Add nanosecond support to timestamps ([#672](https://github.com/aristanetworks/cloudvision/issues/672)) ([9f97468](https://github.com/aristanetworks/cloudvision/commit/9f97468c6cfd7a3156d4ff64d081e4d1b8213537)), closes [#673](https://github.com/aristanetworks/cloudvision/issues/673) [#677](https://github.com/aristanetworks/cloudvision/issues/677) [#675](https://github.com/aristanetworks/cloudvision/issues/675) [#674](https://github.com/aristanetworks/cloudvision/issues/674) [#679](https://github.com/aristanetworks/cloudvision/issues/679) [#678](https://github.com/aristanetworks/cloudvision/issues/678) [#680](https://github.com/aristanetworks/cloudvision/issues/680) [#682](https://github.com/aristanetworks/cloudvision/issues/682) [#681](https://github.com/aristanetworks/cloudvision/issues/681) [#683](https://github.com/aristanetworks/cloudvision/issues/683) [#685](https://github.com/aristanetworks/cloudvision/issues/685) [#684](https://github.com/aristanetworks/cloudvision/issues/684) [#686](https://github.com/aristanetworks/cloudvision/issues/686) [#687](https://github.com/aristanetworks/cloudvision/issues/687) [#688](https://github.com/aristanetworks/cloudvision/issues/688) [#689](https://github.com/aristanetworks/cloudvision/issues/689) [#690](https://github.com/aristanetworks/cloudvision/issues/690) [#692](https://github.com/aristanetworks/cloudvision/issues/692) [#694](https://github.com/aristanetworks/cloudvision/issues/694) [#693](https://github.com/aristanetworks/cloudvision/issues/693) [#691](https://github.com/aristanetworks/cloudvision/issues/691) [#695](https://github.com/aristanetworks/cloudvision/issues/695) [#697](https://github.com/aristanetworks/cloudvision/issues/697) [#696](https://github.com/aristanetworks/cloudvision/issues/696) [#698](https://github.com/aristanetworks/cloudvision/issues/698) [#700](https://github.com/aristanetworks/cloudvision/issues/700) [#701](https://github.com/aristanetworks/cloudvision/issues/701) [#699](https://github.com/aristanetworks/cloudvision/issues/699) [#702](https://github.com/aristanetworks/cloudvision/issues/702) [#703](https://github.com/aristanetworks/cloudvision/issues/703) [#704](https://github.com/aristanetworks/cloudvision/issues/704) [#705](https://github.com/aristanetworks/cloudvision/issues/705) [#706](https://github.com/aristanetworks/cloudvision/issues/706) [#707](https://github.com/aristanetworks/cloudvision/issues/707) [#709](https://github.com/aristanetworks/cloudvision/issues/709) [#710](https://github.com/aristanetworks/cloudvision/issues/710) [#711](https://github.com/aristanetworks/cloudvision/issues/711) [#713](https://github.com/aristanetworks/cloudvision/issues/713) [#712](https://github.com/aristanetworks/cloudvision/issues/712) [#714](https://github.com/aristanetworks/cloudvision/issues/714) [#708](https://github.com/aristanetworks/cloudvision/issues/708) [#715](https://github.com/aristanetworks/cloudvision/issues/715) [#716](https://github.com/aristanetworks/cloudvision/issues/716) [#718](https://github.com/aristanetworks/cloudvision/issues/718) [#719](https://github.com/aristanetworks/cloudvision/issues/719) [#722](https://github.com/aristanetworks/cloudvision/issues/722) [#720](https://github.com/aristanetworks/cloudvision/issues/720) [#723](https://github.com/aristanetworks/cloudvision/issues/723) [#724](https://github.com/aristanetworks/cloudvision/issues/724) [#725](https://github.com/aristanetworks/cloudvision/issues/725) [#726](https://github.com/aristanetworks/cloudvision/issues/726) [#727](https://github.com/aristanetworks/cloudvision/issues/727) [#728](https://github.com/aristanetworks/cloudvision/issues/728) [#730](https://github.com/aristanetworks/cloudvision/issues/730) [#731](https://github.com/aristanetworks/cloudvision/issues/731) [#729](https://github.com/aristanetworks/cloudvision/issues/729) [#732](https://github.com/aristanetworks/cloudvision/issues/732) [#733](https://github.com/aristanetworks/cloudvision/issues/733) [#734](https://github.com/aristanetworks/cloudvision/issues/734) [#735](https://github.com/aristanetworks/cloudvision/issues/735) [#736](https://github.com/aristanetworks/cloudvision/issues/736) [#737](https://github.com/aristanetworks/cloudvision/issues/737) [#738](https://github.com/aristanetworks/cloudvision/issues/738) [#740](https://github.com/aristanetworks/cloudvision/issues/740) [#739](https://github.com/aristanetworks/cloudvision/issues/739) [#741](https://github.com/aristanetworks/cloudvision/issues/741) [#744](https://github.com/aristanetworks/cloudvision/issues/744) [#745](https://github.com/aristanetworks/cloudvision/issues/745) [#746](https://github.com/aristanetworks/cloudvision/issues/746) [#747](https://github.com/aristanetworks/cloudvision/issues/747) [#748](https://github.com/aristanetworks/cloudvision/issues/748) [#749](https://github.com/aristanetworks/cloudvision/issues/749) [#750](https://github.com/aristanetworks/cloudvision/issues/750) [#751](https://github.com/aristanetworks/cloudvision/issues/751) [#752](https://github.com/aristanetworks/cloudvision/issues/752) [#753](https://github.com/aristanetworks/cloudvision/issues/753) [#754](https://github.com/aristanetworks/cloudvision/issues/754) # [4.12.0](https://github.com/aristanetworks/cloudvision/compare/v4.11.0...v4.12.0) (2021-10-05) **Note:** Version bump only for package cloudvision-connector # [4.11.0](https://github.com/aristanetworks/cloudvision/compare/v4.10.1...v4.11.0) (2021-10-04) **Note:** Version bump only for package cloudvision-connector ## [4.10.1](https://github.com/aristanetworks/cloudvision/compare/v4.10.0...v4.10.1) (2021-09-17) **Note:** Version bump only for package cloudvision-connector # [4.10.0](https://github.com/aristanetworks/cloudvision/compare/v4.9.2...v4.10.0) (2021-09-08) **Note:** Version bump only for package cloudvision-connector ## [4.9.2](https://github.com/aristanetworks/cloudvision/compare/v4.9.1...v4.9.2) (2021-08-06) **Note:** Version bump only for package cloudvision-connector ## [4.9.1](https://github.com/aristanetworks/cloudvision/compare/v4.9.0...v4.9.1) (2021-07-22) ### Bug Fixes * update packages ([#470](https://github.com/aristanetworks/cloudvision/issues/470)) ([264d1e0](https://github.com/aristanetworks/cloudvision/commit/264d1e04045ec9ae2efeaf1ff87cf4b9339626c5)) # [4.9.0](https://github.com/aristanetworks/cloudvision/compare/v4.8.0...v4.9.0) (2021-06-17) **Note:** Version bump only for package cloudvision-connector # [4.8.0](https://github.com/aristanetworks/cloudvision/compare/v4.7.0...v4.8.0) (2021-05-18) **Note:** Version bump only for package cloudvision-connector # [4.7.0](https://github.com/aristanetworks/cloudvision/compare/v4.6.5...v4.7.0) (2021-03-08) ### Features * **connector:** add GET_REGIONS_AND_CLUSTERS method ([#366](https://github.com/aristanetworks/cloudvision/issues/366)) ([c26369c](https://github.com/aristanetworks/cloudvision/commit/c26369c536d5910ecc772e1f2f7a7db1132cf227)) ## [4.6.5](https://github.com/aristanetworks/cloudvision/compare/v4.6.4...v4.6.5) (2021-01-20) ### Bug Fixes * **cloudvision-connector:** fix DatasetObject type ([#337](https://github.com/aristanetworks/cloudvision/issues/337)) ([b432bf9](https://github.com/aristanetworks/cloudvision/commit/b432bf93cad353a67edf9eb29e36736bbeef89be)) ## [4.6.4](https://github.com/aristanetworks/cloudvision/compare/v4.6.3...v4.6.4) (2021-01-19) ### Bug Fixes * **cloudvision-connector:** update type of DatasetObject ([#335](https://github.com/aristanetworks/cloudvision/issues/335)) ([32569b9](https://github.com/aristanetworks/cloudvision/commit/32569b99302829676cf1a2cb2b6aef2927226607)) ## [4.6.3](https://github.com/aristanetworks/cloudvision/compare/v4.6.2...v4.6.3) (2020-12-15) **Note:** Version bump only for package cloudvision-connector ## [4.6.2](https://github.com/aristanetworks/cloudvision/compare/v4.6.1...v4.6.2) (2020-12-01) **Note:** Version bump only for package cloudvision-connector ## [4.6.1](https://github.com/aristanetworks/cloudvision/compare/v4.6.0...v4.6.1) (2020-11-04) **Note:** Version bump only for package cloudvision-connector # [4.6.0](https://github.com/aristanetworks/cloudvision/compare/v4.5.5...v4.6.0) (2020-10-05) ### Features * **cloudvision-connector:** add support for config dataset type ([#207](https://github.com/aristanetworks/cloudvision/issues/207)) ([5e9d570](https://github.com/aristanetworks/cloudvision/commit/5e9d57093c6f05b16fa7861470602dfd3ea73fee)) ## [4.5.5](https://github.com/aristanetworks/cloudvision/compare/v4.5.4...v4.5.5) (2020-09-16) **Note:** Version bump only for package cloudvision-connector ## [4.5.4](https://github.com/aristanetworks/cloudvision/compare/v4.5.3...v4.5.4) (2020-08-10) ### Bug Fixes * **cloudvision-connector:** Remove deduping, other unused functionality ([#149](https://github.com/aristanetworks/cloudvision/issues/149)) ([b370b45](https://github.com/aristanetworks/cloudvision/commit/b370b45a7b79c8fdb7390fb5114d7edabbbb4dac)) ## [4.5.3](https://github.com/aristanetworks/cloudvision/compare/v4.5.2...v4.5.3) (2020-07-29) ### Bug Fixes * **cloudvision-connector:** export needed constants and types ([#141](https://github.com/aristanetworks/cloudvision/issues/141)) ([2875718](https://github.com/aristanetworks/cloudvision/commit/2875718b62ed97ee7879f6a0e86ae66f8286fae7)) ## [4.5.2](https://github.com/aristanetworks/cloudvision/compare/v4.5.1...v4.5.2) (2020-07-28) ### Bug Fixes * **cloudvision-connector:** add service request to Conenctor ([#139](https://github.com/aristanetworks/cloudvision/issues/139)) ([972440f](https://github.com/aristanetworks/cloudvision/commit/972440fb85fe1bf0f0a0df9f89a74e26f54be2bb)) ## [4.5.1](https://github.com/aristanetworks/cloudvision/compare/v4.5.0...v4.5.1) (2020-07-28) ### Bug Fixes * **cloudvision-connector:** add getAndSubscribe to Conenctor ([#138](https://github.com/aristanetworks/cloudvision/issues/138)) ([4b4df81](https://github.com/aristanetworks/cloudvision/commit/4b4df81efbf7ade6a54f9f774fbfc43a2e6e5651)) # [4.5.0](https://github.com/aristanetworks/cloudvision/compare/v4.4.0...v4.5.0) (2020-07-27) ### Features * **cloudvision-connector:** add server getAndSubscribe ([#134](https://github.com/aristanetworks/cloudvision/issues/134)) ([ee7b861](https://github.com/aristanetworks/cloudvision/commit/ee7b861f6015f9c90dba3fce7f83fc94795b0252)) # [4.4.0](https://github.com/aristanetworks/cloudvision/compare/v4.3.1...v4.4.0) (2020-07-14) **Note:** Version bump only for package cloudvision-connector ## [4.3.1](https://github.com/aristanetworks/cloudvision/compare/v4.3.0...v4.3.1) (2020-07-07) **Note:** Version bump only for package cloudvision-connector # [4.3.0](https://github.com/aristanetworks/cloudvision/compare/v4.2.0...v4.3.0) (2020-06-08) ### Bug Fixes * **packages:** add rimraf dev dependency ([#79](https://github.com/aristanetworks/cloudvision/issues/79)) ([15396e7](https://github.com/aristanetworks/cloudvision/commit/15396e72ca26bf7fc13009233c597cefe336d214)) ### Features * **cloudvision-connector:** add instrumentation ([#88](https://github.com/aristanetworks/cloudvision/issues/88)) ([59b99af](https://github.com/aristanetworks/cloudvision/commit/59b99afc870d95e97a3e77cd145afac27bec2424)) # [4.2.0](https://github.com/aristanetworks/cloudvision/compare/v4.1.0...v4.2.0) (2020-05-19) ### Bug Fixes * **cloudvision-connector:** Rename request args and add default ([1c40ef2](https://github.com/aristanetworks/cloudvision/commit/1c40ef2b027ca9d48d8bec90f3391585d0eb7321)) ### Features * **cloudvision-connector:** Refactor typings ([6668680](https://github.com/aristanetworks/cloudvision/commit/66686801705fca50e40226957bbca61bf42c6285)) # [4.1.0](https://github.com/aristanetworks/cloudvision/compare/v4.0.5...v4.1.0) (2020-05-11) ### Bug Fixes * **logging:** add more context to logging ([892282b](https://github.com/aristanetworks/cloudvision/commit/892282b10f85ec9de19ee6d143654bcebb0070e1)) ### Features * **callback:** add request context ([fbe23a5](https://github.com/aristanetworks/cloudvision/commit/fbe23a5113e49161669233aa3b7f954f2dc339df)) ## [4.0.5](https://github.com/aristanetworks/cloudvision/compare/v4.0.4...v4.0.5) (2020-05-06) **Note:** Version bump only for package cloudvision-connector ## [4.0.4](https://github.com/aristanetworks/cloudvision/compare/v4.0.3...v4.0.4) (2020-04-28) **Note:** Version bump only for package cloudvision-connector ## [4.0.3](https://github.com/aristanetworks/cloudvision/compare/v4.0.2...v4.0.3) (2020-04-24) **Note:** Version bump only for package cloudvision-connector ## [4.0.2](https://github.com/aristanetworks/cloudvision/compare/v4.0.1...v4.0.2) (2020-04-21) **Note:** Version bump only for package cloudvision-connector ## 4.0.1 (2020-04-15) **Note:** Version bump only for package cloudvision-connector ## [3.9.8](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.9.8) (2020-04-06) **Note:** Version bump only for package cloudvision-connector ## [3.9.7](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.9.7) (2020-03-30) **Note:** Version bump only for package cloudvision-connector ## [3.9.6](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.9.6) (2020-03-23) **Note:** Version bump only for package cloudvision-connector ## [3.9.5](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.9.5) (2020-03-20) **Note:** Version bump only for package cloudvision-connector ## [3.9.4](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.9.4) (2020-03-20) **Note:** Version bump only for package cloudvision-connector ## [3.9.3](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.9.3) (2020-03-19) **Note:** Version bump only for package cloudvision-connector ## [3.9.2](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.9.2) (2020-03-16) **Note:** Version bump only for package cloudvision-connector ## [3.9.1](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.9.1) (2020-03-09) **Note:** Version bump only for package cloudvision-connector # [3.9.0](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.9.0) (2020-03-04) ### Bug Fixes * **cloudvision-connector:** Fix default export ([887cfea](http://gerrit.corp.arista.io:29418/web-components/commits/887cfead788e85a9f611e17d1850b798f7aad789)) ### Features * **utils:** export sanitizeOptions for use with worker ([223319a](http://gerrit.corp.arista.io:29418/web-components/commits/223319a68124ee46e1ad7d4b23e2f3919476bd24)) ## [3.8.9](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.8.9) (2020-02-26) **Note:** Version bump only for package cloudvision-connector ## [3.8.8](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.8.8) (2020-02-26) ### Bug Fixes * **cloudvision-connector:** fix building of full UMD ([302b068](http://gerrit.corp.arista.io:29418/web-components/commits/302b0689c4235aa29ec6d51ec635fca2a9c61c4b)) ## [3.8.7](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.8.7) (2020-02-25) ### Bug Fixes * **cloudvision-connector:** sort notifs by seconds and nano ([36d2f12](http://gerrit.corp.arista.io:29418/web-components/commits/36d2f12f08a4f3758a6ecd350f8114b967e67116)) ## [3.8.6](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.8.6) (2020-02-24) **Note:** Version bump only for package cloudvision-connector ## [3.8.5](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.8.5) (2020-02-17) **Note:** Version bump only for package cloudvision-connector ## [3.8.4](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.8.4) (2020-02-10) **Note:** Version bump only for package cloudvision-connector ## [3.8.3](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.8.3) (2020-02-03) ### Bug Fixes * **a-msgpack,cloudvision-connector:** move to/from binary key utils ([b6be876](http://gerrit.corp.arista.io:29418/web-components/commits/b6be876b2dbe4b831ac9e1e3ae6805bccada29f0)) ## [3.8.2](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.8.2) (2020-01-27) **Note:** Version bump only for package cloudvision-connector ## [3.8.1](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.8.1) (2020-01-24) ### Bug Fixes * **cloudvision-connector:** Export types for CONNECTED/DISCONNECTED ([9310f3a](http://gerrit.corp.arista.io:29418/web-components/commits/9310f3a43b4a1612b69db318a68d901979b6fb3d)) # [3.8.0](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.8.0) (2020-01-24) ### Features * Add support for streaming services. ([16e9724](http://gerrit.corp.arista.io:29418/web-components/commits/16e9724b48702d6c9f75917f70a2c52b21154313)) ## [3.7.8](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.7.8) (2020-01-22) **Note:** Version bump only for package cloudvision-connector ## [3.7.7](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.7.7) (2020-01-22) ### Bug Fixes * **cloudvision-connector:** export types needed for mock ([3b63da2](http://gerrit.corp.arista.io:29418/web-components/commits/3b63da2eebc5eaf66b69ef99dc976130bc19b107)) ## [3.7.6](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.7.6) (2020-01-22) ### Bug Fixes * **a-msgpack,cloudvision-connector:** improve perf ([3b6992d](http://gerrit.corp.arista.io:29418/web-components/commits/3b6992d783463f8f4f000c3334ceb0693e793083)) ## [3.7.5](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.7.5) (2020-01-20) **Note:** Version bump only for package cloudvision-connector ## [3.7.4](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.7.4) (2019-12-30) **Note:** Version bump only for package cloudvision-connector ## [3.7.3](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.7.3) (2019-11-22) ### Bug Fixes * **connector:** clean up connections on close events ([37987f2](http://gerrit.corp.arista.io:29418/web-components/commits/37987f2)) ## [3.7.2](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.7.2) (2019-11-19) **Note:** Version bump only for package cloudvision-connector ## [3.7.1](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.7.1) (2019-10-30) ### Bug Fixes * **cloudvision-connector:** remove websocket-aware logic ([b620c28](http://gerrit.corp.arista.io:29418/web-components/commits/b620c28)) # [3.7.0](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.7.0) (2019-10-25) ### Bug Fixes * **cloudvision-connector:** clear streams on reconnect ([8f73ba8](http://gerrit.corp.arista.io:29418/web-components/commits/8f73ba8)) ### Features * **cloudvision-connector:** Enhance logging ([f31e0cd](http://gerrit.corp.arista.io:29418/web-components/commits/f31e0cd)) ## [3.6.7](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.6.7) (2019-10-21) **Note:** Version bump only for package cloudvision-connector ## [3.6.6](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.6.6) (2019-10-15) ### Bug Fixes * **cloudvision-connector:** update `CloudVisionDelete` type ([8670212](http://gerrit.corp.arista.io:29418/web-components/commits/8670212)) ## [3.6.5](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.6.5) (2019-10-14) **Note:** Version bump only for package cloudvision-connector ## [3.6.4](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.6.4) (2019-10-08) **Note:** Version bump only for package cloudvision-connector ## [3.6.3](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.6.3) (2019-10-07) **Note:** Version bump only for package cloudvision-connector ## [3.6.2](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.6.2) (2019-10-07) ### Bug Fixes * **cloudvision-connector:** help tsc make proper typings ([f071aab](http://gerrit.corp.arista.io:29418/web-components/commits/f071aab)) * **connector:** export hash for use in event-viewer ([8d15fd9](http://gerrit.corp.arista.io:29418/web-components/commits/8d15fd9)) ## [3.6.1](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.6.1) (2019-10-04) ### Bug Fixes * **cloudvision-connector:** fix various TypeScript types ([388125f](http://gerrit.corp.arista.io:29418/web-components/commits/388125f)) # [3.6.0](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.6.0) (2019-10-04) ### Features * **a-msgpack, cloudvision-connector:** Move to Typescript ([acf4e70](http://gerrit.corp.arista.io:29418/web-components/commits/acf4e70)) ## [3.5.11](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.5.11) (2019-10-02) **Note:** Version bump only for package cloudvision-connector ## [3.5.10](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.5.10) (2019-09-25) **Note:** Version bump only for package cloudvision-connector ## [3.5.9](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.5.9) (2019-09-23) **Note:** Version bump only for package cloudvision-connector ## [3.5.8](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.5.8) (2019-09-17) **Note:** Version bump only for package cloudvision-connector ## [3.5.7](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.5.7) (2019-09-16) **Note:** Version bump only for package cloudvision-connector ## [3.5.6](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.5.6) (2019-09-14) **Note:** Version bump only for package cloudvision-connector ## [3.5.5](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.5.5) (2019-09-10) **Note:** Version bump only for package cloudvision-connector ## [3.5.4](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.5.4) (2019-09-05) **Note:** Version bump only for package cloudvision-connector ## [3.5.3](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.5.3) (2019-08-30) **Note:** Version bump only for package cloudvision-connector ## [3.5.2](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.5.2) (2019-08-29) ### Bug Fixes * **eslint:** update replace banned global self with window ([e62698c](http://gerrit.corp.arista.io:29418/web-components/commits/e62698c)) ## [3.5.1](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.5.1) (2019-08-26) **Note:** Version bump only for package cloudvision-connector # [3.5.0](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.5.0) (2019-08-19) ### Features * **connector:** improve type checking for multithreaded use ([5d13917](http://gerrit.corp.arista.io:29418/web-components/commits/5d13917)) ## [3.4.25](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.25) (2019-08-14) **Note:** Version bump only for package cloudvision-connector ## [3.4.24](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.24) (2019-08-13) **Note:** Version bump only for package cloudvision-connector ## [3.4.23](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.23) (2019-08-12) **Note:** Version bump only for package cloudvision-connector ## [3.4.22](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.22) (2019-08-05) **Note:** Version bump only for package cloudvision-connector ## [3.4.21](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.21) (2019-07-29) **Note:** Version bump only for package cloudvision-connector ## [3.4.20](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.20) (2019-07-26) **Note:** Version bump only for package cloudvision-connector ## [3.4.19](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.19) (2019-07-26) **Note:** Version bump only for package cloudvision-connector ## [3.4.18](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.18) (2019-07-25) **Note:** Version bump only for package cloudvision-connector ## [3.4.17](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.17) (2019-07-24) ### Bug Fixes * **cloudvision-connector:** ensure that service requests get results ([0ae5340](http://gerrit.corp.arista.io:29418/web-components/commits/0ae5340)) * **cloudvision-connector:** update docs ([2809462](http://gerrit.corp.arista.io:29418/web-components/commits/2809462)) ## [3.4.16](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.16) (2019-07-16) **Note:** Version bump only for package cloudvision-connector ## [3.4.15](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.15) (2019-07-16) ### Bug Fixes * **cloudvision-connector:** Remove stream from waiting list when closing ([1a59547](http://gerrit.corp.arista.io:29418/web-components/commits/1a59547)) ## [3.4.14](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.14) (2019-07-12) ### Bug Fixes * **cloudvision-connector:** always emit the proper ws events ([41575b3](http://gerrit.corp.arista.io:29418/web-components/commits/41575b3)) ## [3.4.13](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.13) (2019-07-02) **Note:** Version bump only for package cloudvision-connector ## [3.4.12](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.12) (2019-07-01) **Note:** Version bump only for package cloudvision-connector ## [3.4.11](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.11) (2019-07-01) **Note:** Version bump only for package cloudvision-connector ## [3.4.10](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.10) (2019-06-28) **Note:** Version bump only for package cloudvision-connector ## [3.4.9](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.9) (2019-06-27) **Note:** Version bump only for package cloudvision-connector ## [3.4.8](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.8) (2019-06-11) **Note:** Version bump only for package cloudvision-connector ## [3.4.7](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.7) (2019-06-03) **Note:** Version bump only for package cloudvision-connector ## [3.4.6](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.6) (2019-05-28) **Note:** Version bump only for package cloudvision-connector ## [3.4.5](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.5) (2019-05-17) **Note:** Version bump only for package cloudvision-connector ## [3.4.4](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.4) (2019-05-14) **Note:** Version bump only for package cloudvision-connector ## [3.4.3](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.3) (2019-05-14) **Note:** Version bump only for package cloudvision-connector ## [3.4.2](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.2) (2019-05-14) **Note:** Version bump only for package cloudvision-connector ## [3.4.1](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.1) (2019-05-14) **Note:** Version bump only for package cloudvision-connector # [3.4.0](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.4.0) (2019-05-14) ### Features * **cloudvision-connector:** remove v1 codec support ([1893664](http://gerrit.corp.arista.io:29418/web-components/commits/1893664)) ## [3.3.7](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.3.7) (2019-05-13) **Note:** Version bump only for package cloudvision-connector ## [3.3.6](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.3.6) (2019-05-13) **Note:** Version bump only for package cloudvision-connector ## [3.3.5](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.3.5) (2019-05-13) **Note:** Version bump only for package cloudvision-connector ## [3.3.4](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.3.4) (2019-05-06) ### Bug Fixes * **cloudvision-connector:** for the root path don't send `path_elements` ([8bffc6d](http://gerrit.corp.arista.io:29418/web-components/commits/8bffc6d)) ## [3.3.3](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.3.3) (2019-04-29) ### Bug Fixes * **cloudvision-connector:** update decodeMap ([979541e](http://gerrit.corp.arista.io:29418/web-components/commits/979541e)) ## [3.3.2](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.3.2) (2019-04-22) ### Bug Fixes * **cloudvision-connector:** fix object key sorting ([ef4d8fc](http://gerrit.corp.arista.io:29418/web-components/commits/ef4d8fc)) * **cloudvision-connector:** support `delete_all` in publish ([bad68d0](http://gerrit.corp.arista.io:29418/web-components/commits/bad68d0)) ## [3.3.1](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.3.1) (2019-04-16) ### Bug Fixes * **cloudvision-connector:** assume 0 for nanos if not defined ([e80eaf8](http://gerrit.corp.arista.io:29418/web-components/commits/e80eaf8)) * **cloudvision-connector:** set proper defaults for primitives ([b427179](http://gerrit.corp.arista.io:29418/web-components/commits/b427179)) # [3.3.0](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.3.0) (2019-04-11) ### Bug Fixes * **cloudvision-connector:** `fromBinaryKey` should force JSBI ([08855a8](http://gerrit.corp.arista.io:29418/web-components/commits/08855a8)) * **cloudvision-connector:** expose notification Parser ([bb4d992](http://gerrit.corp.arista.io:29418/web-components/commits/bb4d992)) ### Features * **cloudvision-connector:** handle delete all in v3 ([a61da2e](http://gerrit.corp.arista.io:29418/web-components/commits/a61da2e)) * **cloudvision-connector:** support publishing for v3 ([0b805e2](http://gerrit.corp.arista.io:29418/web-components/commits/0b805e2)) # [3.2.0](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.2.0) (2019-04-10) ### Features * **cloudvision-connector:** return EOF for service requests ([f508f88](http://gerrit.corp.arista.io:29418/web-components/commits/f508f88)) ## [3.1.12](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.1.12) (2019-04-08) **Note:** Version bump only for package cloudvision-connector ## [3.1.11](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@3.1.11) (2019-04-03) ### Bug Fixes * **cloudvision-connector:** pad nanoseconds to 9 digits ([d7d2371](http://gerrit.corp.arista.io:29418/web-components/commits/d7d2371)) ## [3.1.10](http://gerrit:29418/web-components/compare/[email protected]@3.1.10) (2019-04-01) **Note:** Version bump only for package cloudvision-connector ## [3.1.9](http://gerrit:29418/web-components/compare/[email protected]@3.1.9) (2019-03-26) ### Bug Fixes * **cloudvision-connector:** path_elements notif key for root path ([2f25544](http://gerrit:29418/web-components/commits/2f25544)) ## [3.1.8](http://gerrit:29418/web-components/compare/[email protected]@3.1.8) (2019-03-25) ### Bug Fixes * **cloudvision-connector:** add query path keys for NEAT queries ([cb7d8a2](http://gerrit:29418/web-components/commits/cb7d8a2)) * **cloudvision-connector:** fix flowtype ([dbb0348](http://gerrit:29418/web-components/commits/dbb0348)) ## [3.1.7](http://gerrit:29418/web-components/compare/[email protected]@3.1.7) (2019-03-19) **Note:** Version bump only for package cloudvision-connector ## [3.1.6](http://gerrit:29418/web-components/compare/[email protected]@3.1.6) (2019-03-18) **Note:** Version bump only for package cloudvision-connector ## [3.1.5](http://gerrit:29418/web-components/compare/[email protected]@3.1.5) (2019-03-18) **Note:** Version bump only for package cloudvision-connector ## [3.1.4](http://gerrit:29418/web-components/compare/[email protected]@3.1.4) (2019-03-13) **Note:** Version bump only for package cloudvision-connector ## [3.1.3](http://gerrit:29418/web-components/compare/[email protected]@3.1.3) (2019-03-11) **Note:** Version bump only for package cloudvision-connector ## [3.1.2](http://gerrit:29418/web-components/compare/[email protected]@3.1.2) (2019-03-07) **Note:** Version bump only for package cloudvision-connector ## [3.1.1](http://gerrit:29418/web-components/compare/[email protected]@3.1.1) (2019-03-04) **Note:** Version bump only for package cloudvision-connector # [3.1.0](http://gerrit:29418/web-components/compare/[email protected]@3.1.0) (2019-02-26) ### Features * **cloudvision-connector:** Implement `Pointer` type for v2 ([42f20d3](http://gerrit:29418/web-components/commits/42f20d3)) ## [3.0.15](http://gerrit:29418/web-components/compare/[email protected]@3.0.15) (2019-02-23) **Note:** Version bump only for package cloudvision-connector ## [3.0.14](http://gerrit:29418/web-components/compare/[email protected]@3.0.14) (2019-02-22) ### Bug Fixes * **cloudvision-connector:** expose commands ([434b010](http://gerrit:29418/web-components/commits/434b010)) * **cloudvision-connector:** Fix hashObject collision ([4f95712](http://gerrit:29418/web-components/commits/4f95712)) ## [3.0.13](http://gerrit:29418/web-components/compare/[email protected]@3.0.13) (2019-02-21) ### Bug Fixes * **cloudvision-connector:** expose commands ([434b010](http://gerrit:29418/web-components/commits/434b010)) ## [3.0.12](http://gerrit:29418/web-components/compare/[email protected]@3.0.12) (2019-02-19) **Note:** Version bump only for package cloudvision-connector ## [3.0.11](http://gerrit:29418/web-components/compare/[email protected]@3.0.11) (2019-02-15) **Note:** Version bump only for package cloudvision-connector ## [3.0.10](http://gerrit:29418/web-components/compare/[email protected]@3.0.10) (2019-02-14) ### Bug Fixes * **cloudvision-connector:** add test util function for setTimeout ([2bc36c1](http://gerrit:29418/web-components/commits/2bc36c1)) * **cloudvision-connector:** expose NEAT types ([8782251](http://gerrit:29418/web-components/commits/8782251)) ## [3.0.9](http://gerrit:29418/web-components/compare/[email protected]@3.0.9) (2019-02-12) ### Bug Fixes * **cloudvision-connector:** flowtype lint ([be94ca7](http://gerrit:29418/web-components/commits/be94ca7)) ## [3.0.8](http://gerrit:29418/web-components/compare/[email protected]@3.0.8) (2019-02-11) **Note:** Version bump only for package cloudvision-connector ## [3.0.7](http://gerrit:29418/web-components/compare/[email protected]@3.0.7) (2019-02-07) **Note:** Version bump only for package cloudvision-connector ## [3.0.6](http://gerrit:29418/web-components/compare/[email protected]@3.0.6) (2019-02-04) **Note:** Version bump only for package cloudvision-connector ## [3.0.5](http://gerrit:29418/web-components/compare/[email protected]@3.0.5) (2019-02-04) **Note:** Version bump only for package cloudvision-connector ## [3.0.4](http://gerrit:29418/web-components/compare/[email protected]@3.0.4) (2019-01-29) **Note:** Version bump only for package cloudvision-connector ## [3.0.3](http://gerrit:29418/web-components/compare/[email protected]@3.0.3) (2019-01-28) ### Bug Fixes * **cloudvision-connector:** non timeseries notifications do not use NEAT ([2a5cef5](http://gerrit:29418/web-components/commits/2a5cef5)) ## [3.0.2](http://gerrit:29418/web-components/compare/[email protected]@3.0.2) (2019-01-28) **Note:** Version bump only for package cloudvision-connector ## [3.0.1](http://gerrit:29418/web-components/compare/[email protected]@3.0.1) (2019-01-28) **Note:** Version bump only for package cloudvision-connector # [3.0.0](http://gerrit:29418/web-components/compare/[email protected]@3.0.0) (2019-01-24) ### Features * **cloudvision-connector:** backwards compatibility for v1 codec ([c4dfe73](http://gerrit:29418/web-components/commits/c4dfe73)) ### BREAKING CHANGES * **cloudvision-connector:** Make connector backwards compatible. This allows switching between the v1 (BDSN) and v2 (NEAT) codec. Change-Id: Icf7b84647dcb5586d512b67ceb8d5e08d27c445d ## [2.4.2](http://gerrit:29418/web-components/compare/[email protected]@2.4.2) (2019-01-21) **Note:** Version bump only for package cloudvision-connector ## [2.4.1](http://gerrit:29418/web-components/compare/[email protected]@2.4.1) (2019-01-14) **Note:** Version bump only for package cloudvision-connector # [2.4.0](http://gerrit:29418/web-components/compare/[email protected]@2.4.0) (2019-01-14) ### Bug Fixes * **cloudvision-connector:** force JSBI ([69490e2](http://gerrit:29418/web-components/commits/69490e2)) ### Features * **cloudvision-connector:** add support for NEAT/path elements ([7d1ec1d](http://gerrit:29418/web-components/commits/7d1ec1d)) # [2.3.0](http://gerrit:29418/web-components/compare/[email protected]@2.3.0) (2019-01-11) ### Features * **cloudvision-connector:** Implement Aeris Services logic. ([1f97c8f](http://gerrit:29418/web-components/commits/1f97c8f)) ## [2.2.15](http://gerrit:29418/web-components/compare/[email protected]@2.2.15) (2019-01-08) **Note:** Version bump only for package cloudvision-connector ## [2.2.14](http://gerrit:29418/web-components/compare/[email protected]@2.2.14) (2019-01-07) **Note:** Version bump only for package cloudvision-connector ## [2.2.13](http://gerrit:29418/web-components/compare/[email protected]@2.2.13) (2019-01-02) **Note:** Version bump only for package cloudvision-connector ## [2.2.12](http://gerrit:29418/web-components/compare/[email protected]@2.2.12) (2018-12-20) **Note:** Version bump only for package cloudvision-connector ## [2.2.11](http://gerrit:29418/web-components/compare/[email protected]@2.2.11) (2018-12-19) **Note:** Version bump only for package cloudvision-connector ## [2.2.10](http://gerrit:29418/web-components/compare/[email protected]@2.2.10) (2018-12-10) **Note:** Version bump only for package cloudvision-connector ## [2.2.9](http://gerrit:29418/web-components/compare/[email protected]@2.2.9) (2018-12-05) ### Bug Fixes * **various:** upgrade to Babel 7 ([15076a5](http://gerrit:29418/web-components/commits/15076a5)) ## [2.2.8](http://gerrit:29418/web-components/compare/[email protected]@2.2.8) (2018-11-26) **Note:** Version bump only for package cloudvision-connector ## [2.2.7](http://gerrit:29418/web-components/compare/[email protected]@2.2.7) (2018-11-21) **Note:** Version bump only for package cloudvision-connector ## [2.2.6](http://gerrit:29418/web-components/compare/[email protected]@2.2.6) (2018-11-21) **Note:** Version bump only for package cloudvision-connector ## [2.2.5](http://gerrit:29418/web-components/compare/[email protected]@2.2.5) (2018-11-19) **Note:** Version bump only for package cloudvision-connector ## [2.2.4](http://gerrit:29418/web-components/compare/[email protected]@2.2.4) (2018-11-12) **Note:** Version bump only for package cloudvision-connector ## [2.2.3](http://gerrit:29418/web-components/compare/[email protected]@2.2.3) (2018-11-09) ### Bug Fixes * **eslint-config-arista:** use `no-multiple-empty-lines` ([c9425c6](http://gerrit:29418/web-components/commits/c9425c6)) ## [2.2.2](http://gerrit:29418/web-components/compare/[email protected]@2.2.2) (2018-11-07) **Note:** Version bump only for package cloudvision-connector ## [2.2.1](http://gerrit:29418/web-components/compare/[email protected]@2.2.1) (2018-11-06) ### Bug Fixes * **tagged-token:** remove tagged-token package ([69eba23](http://gerrit:29418/web-components/commits/69eba23)) # [2.2.0](http://gerrit:29418/web-components/compare/[email protected]@2.2.0) (2018-11-02) ### Features * **eslint-plugin-arista:** add Arista eslint plugin ([ea1367a](http://gerrit:29418/web-components/commits/ea1367a)) ## [2.1.8](http://gerrit:29418/web-components/compare/[email protected]@2.1.8) (2018-11-01) **Note:** Version bump only for package cloudvision-connector ## [2.1.7](http://gerrit:29418/web-components/compare/[email protected]@2.1.7) (2018-10-29) **Note:** Version bump only for package cloudvision-connector ## [2.1.6](http://gerrit:29418/web-components/compare/[email protected]@2.1.6) (2018-10-23) **Note:** Version bump only for package cloudvision-connector ## [2.1.5](http://gerrit:29418/web-components/compare/[email protected]@2.1.5) (2018-10-22) ### Bug Fixes * **various:** align package.json with .eslintrc ([f8f4126](http://gerrit:29418/web-components/commits/f8f4126)) <a name="2.1.4"></a> ## [2.1.4](http://gerrit:29418/web-components/compare/[email protected]@2.1.4) (2018-10-18) ### Bug Fixes * **various:** add/fix license files ([48e6b3f](http://gerrit:29418/web-components/commits/48e6b3f)) * **various:** change "prepublish" to "prepare" ([2d59c9c](http://gerrit:29418/web-components/commits/2d59c9c)) <a name="2.1.3"></a> ## [2.1.3](http://gerrit:29418/web-components/compare/[email protected]@2.1.3) (2018-10-17) ### Bug Fixes * **various:** upgrade eslint-plugin-babel to 5.2.1 ([ef2b7a1](http://gerrit:29418/web-components/commits/ef2b7a1)) <a name="2.1.2"></a> ## [2.1.2](http://gerrit:29418/web-components/compare/[email protected]@2.1.2) (2018-10-17) ### Bug Fixes * **various:** specify exact package versions ([9e4156a](http://gerrit:29418/web-components/commits/9e4156a)) <a name="2.1.1"></a> ## [2.1.1](http://gerrit:29418/web-components/compare/[email protected]@2.1.1) (2018-10-02) ### Bug Fixes * **cloudvision-connector:** allow pause/resume to be enabled ([ae505e7](http://gerrit:29418/web-components/commits/ae505e7)) <a name="2.1.0"></a> # [2.1.0](http://gerrit:29418/web-components/compare/[email protected]@2.1.0) (2018-09-24) ### Features * **cloudvision-connector:** add Search API ([31dbe96](http://gerrit:29418/web-components/commits/31dbe96)) * **cloudvision-connector:** add support for pause/resume of streams ([ffba69d](http://gerrit:29418/web-components/commits/ffba69d)) <a name="2.0.3"></a> ## [2.0.3](http://gerrit:29418/web-components/compare/[email protected]@2.0.3) (2018-09-13) ### Bug Fixes * **cloudvision-connector:** update docs ([71555e1](http://gerrit:29418/web-components/commits/71555e1)) <a name="2.0.2"></a> ## [2.0.2](http://gerrit:29418/web-components/compare/[email protected]@2.0.2) (2018-09-10) ### Bug Fixes * **cloudvision-connector:** fix rollup build warnings ([417fff6](http://gerrit:29418/web-components/commits/417fff6)) <a name="2.0.1"></a> ## [2.0.1](http://gerrit:29418/web-components/compare/[email protected]@2.0.1) (2018-09-10) ### Bug Fixes * **cloudvision-connector:** update eslint dependencies ([45c3ba5](http://gerrit:29418/web-components/commits/45c3ba5)) <a name="2.0.0"></a> # [2.0.0](http://gerrit:29418/web-components/compare/[email protected]@2.0.0) (2018-09-05) ### Bug Fixes * **cloudvision-connector:** use eslint-config-arista ([e87dfa3](http://gerrit:29418/web-components/commits/e87dfa3)) <file_sep>// ExtensionCodec to handle MessagePack extensions import { ExtData } from './ExtData'; export type ExtensionDecoderType = (data: Uint8Array, extensionType: number) => unknown; export type ExtensionEncoderType<T> = (input: T) => Uint8Array; export type ExtensionIdentifier = (ext: unknown) => boolean; export interface ExtensionCodecType { encode(object: unknown): ExtData; decode(data: Uint8Array, extType: number): unknown; } export class ExtensionCodec implements ExtensionCodecType { public static readonly defaultCodec: ExtensionCodecType = new ExtensionCodec(); // custom extensions private readonly encoders: ExtensionEncoderType<any>[] = []; private readonly decoders: ExtensionDecoderType[] = []; private readonly identifiers: ExtensionIdentifier[] = []; public register<EncodeType>({ type, identifier, encode, decode, }: { type: number; identifier: ExtensionIdentifier; encode: ExtensionEncoderType<EncodeType>; decode: ExtensionDecoderType; }): void { this.encoders[type] = encode; this.decoders[type] = decode; this.identifiers.push(identifier); } public encode(object: unknown): ExtData { let type = null; for (let i = 0; i < this.identifiers.length; i++) { const id = this.identifiers[i]; if (id(object)) { type = i; } } if (type === null) { throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(object)}`); } const encoder = this.encoders[type]; const data = encoder(object); return new ExtData(type, data); } public decode(data: Uint8Array, type: number): unknown { const decoder = this.decoders[type]; return decoder(data, type); } } <file_sep>export function ensureUint8Array( buffer: ArrayLike<number> | Uint8Array | ArrayBufferView | ArrayBuffer, ): Uint8Array { if (buffer instanceof Uint8Array) { return buffer; } if (ArrayBuffer.isView(buffer)) { return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); } if (buffer instanceof ArrayBuffer) { return new Uint8Array(buffer); } return Uint8Array.from(buffer); } export function createDataView( buffer: ArrayLike<number> | ArrayBufferView | ArrayBuffer, ): DataView { if (buffer instanceof ArrayBuffer) { return new DataView(buffer); } const bufferView = ensureUint8Array(buffer); return new DataView(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength); } <file_sep># CloudVision Connector The CloudVision Connector is a simple JavaScript module using WebSockets that enables you to transmit data over an open connection with the CloudVision API server. The CloudVision Connector supports subscribing to data, which lets clients receive streaming updates as data changes in real-time. ## Installation with yarn: ```bash yarn add cloudvision-connector ``` or npm: ```bash npm install --save cloudvision-connector ``` ## Usage ### Getting Started Quick introduction into to how to connect to the API server #### Getting Datasets ```js const parseDatasets = (err, datasets) => {...}; // Add a callback connector.getDatasets(parseDatasets); // datasets returned in `parseDatasets` is a list of dataset ids datasets = [ 'JPE15076475', 'JPE12111270', 'app-turbine', 'HSH14525062', 'CloudTracer', ]; ``` You can also get datasets use `getWithOptions` (see details below). This is done by calling `getWithOptions` with `Connector.DEVICES_DATASET_ID` as the first parameter. ```js const parseDevices = (err, datasets) => {...}; const query = Connector.DEVICES_DATASET_ID; connector.getWithOptions(query, handleResponse); ``` #### Getting Data The CloudVision Connector allows you to query notifications for multiple paths on a dataset, as well as multiple paths within multiple datasets. ##### getWithOptions(query, callback, options) Returns all notifications that match the given query and options. - `query`: an object in the shape of a query (see "Query") - `callback`: a function that is called when notifications are received (see "Notifications Callback") - `options`: an object in the shape of query options (see "Options") - **Returns**: the token (unique identifier) of the request. ##### Example ```js const query = [{ dataset: { type: 'app', name: 'analytics' }, paths: [{ path_elements: ['events','activeEvents'], }], }, { dataset: { type: 'app', name: 'analytics' }, paths: [{ path_elements: ['tags','stats'], }, { path_elements: ['BugAlerts','bugs'], }], }]; const handleResponse = (err, res, status) => {...}; const options = { start: 1504113817725, end: 1504113917725, }; // open the stream const token = connector.getWithOptions(query, handleResponse), options; ``` #### Subscribing to Data In addition to getting data, you can use the same query to subscribe to any updates to the data as it changes. ##### getAndSubscribe(query, callback, options) Returns all notifications that match the given query and options, in addition to subscribing to updates. This will return notifications as new updates to the data requested come in. - `query`: an object in the shape of a query (see "Query") - `callback`: a function that is called when notifications are received (see "Notifications Callback") - `options`: an object in the shape of query options (see "Options") - **Returns**: a the subscription identifier. This is an object constaining the token and the callback ##### Example ```js const query = [{ dataset: { type: 'app', name: 'analytics' }, paths: [{ path_elements: ['events','activeEvents'], }], }, { dataset: { type: 'app', name: 'analytics' }, paths: [{ path_elements: ['tags','stats'], }, { path_elements: ['BugAlerts','bugs'], }], }]; const handleResponse = (err, res, status) => {...}; // open the stream const subscribptionsIdentifier = connector.subscribe(query, handleResponse); ``` #### Notifications Callback This is the callback, which is called when notifications are received. ```js const handler = (err, res, status, token) => {...} ``` Arguments: - `err`: either a string or `null`. If `null` then there is no error. If it is a string, then an error occurred. - `res`: an object with the properties `dataset` and `notifications`. e.g. ```js res = { dataset: "someDevice", notifications: { "['path', 'to', 'some', 'data']": [...], "['path', 'to', 'another', 'data']": [...], ... } } ``` Each `[...]` above is an array of notifications which each have a `timestamp`, `path`, collection of `updates`, and `deletes` (see "Data Model" section for more information). - status: An object with the status code and a message. See the "Notification Statuses" section for more details. - `token`: The token id that was created for the request. #### Notification Statuses A status object has an optional `message` key containing a string describing the status, in addition to a `code` key with the code number. Possible status codes: |Code|JS Constant|Description| |1001|EOF_CODE|Signals that this is the last notification for the request| |3001|ACTIVE_CODE|Signals that the stream (subscription), has been established| #### Options There are a number of options you can supply to the query which limit it's scope. Options are passed as an object, where the **key** is the name of the option and the **value** is the value for that option. The options are `start`, `end` and `versions`. There are different combinations of options that are valid, each of them is listed below. Range query (returns one or more data points): - `start`: the epoch timestamp in (milliseconds) of the first data point. - `end`: the epoch timestamp in (milliseconds) of the last data point. Point in time query (returns exactly one data point): - `end`: the epoch timestamp in (milliseconds) of the data point. Limit query (returns `versions` + 1 number of data points): - `end`: the epoch timestamp in (milliseconds) of the last data point. - `versions`: the number of versions of data (in the past) to request in addition to the data point for `end`. #### Query A query is an array of objects with a **dataset** key and **paths** key. The value of each **dataset** is an object with a **type** (the type of the dataset, which can be **device** or **app**) and **name** (the identifier for the dataset e.g. 'JPE13262133') key. The value of the **paths** key is an array of objects with a **path_elements** (an array of the component parts of a path) key and an optional **keys** key. The value of **keys** is an object that defines the shape of how you want the data to be returned. Think of it like a map that points to certain fields in CloudVision api. ```js query = [{ dataset: { type: <dataset type>, name: <dataset>, }, paths: [{ path_elements: <path 1>, }, { path_elements: <path 2>, keys: { [any_custom_key]: { key: <key 1>, } } }], }]; ``` ##### Example ```js const handleResponse = (err, res) => {...}; const query = [{ dataset: { type: 'app'. name: 'analytics', }, paths: [{ path_elements: ['events', 'activeEvents'], }, { path_elements: ['Logs', 'var', 'log', 'messages'], keys: { logMessage: { key: 'text', } } }], }]; const options = { start: 1504113817725, end: 1504113917725, }; connector.getWithOptions(query, null, options, handleResponse); ``` ### Getting Data More in depth information on how to query different data. #### Connecting to the Server You can connect to the CloudVision API server with any kind of WebSocket. This connector uses the regular browser WebSocket, but it also allows you to pass in your own custom implementation of a standard WebSocket. You can also connect via secure WebSockets (`wss`), which uses the same SSL certificate as `https` does. If you are using wss, you will need to get the authentication cookie from the CVP auth service. ```js const authUrl = 'https://example.cloudvision.api-server/cvpservice/login/authenticate.do'; const userId = 'user'; const password = '<PASSWORD>'; function loggedIn() { console.log('You are logged in'); } function authFailure(message) { console.log('Auth Failure:', message); } window .fetch(authUrl, { method: 'POST', credentials: 'include', body: JSON.stringify({ userId, password }), }) .then((response) => { // Handle JSON response return response.json(); }) .then((jsonResp) => { if (jsonResp.sessionId) { // We got a session id, so we are now logged in loggedIn(); } else if (jsonResp.errorMessage) { // Handle authentication failure authFailure(jsonResp.errorMessage); } }) .catch // Error handling for failed request (); ``` Once you have completed this request successfully, you will have the authentication cookie which will be sent along with the request to open the WebSocket. ```js // Import module import Connector from 'cloudvision-connector'; // Create the connection const connector = new Connector(); // Start the connection connector.run('ws://example.cloudvision.api-server/api/v3/wrpc/'); // Start the connection with a custom WebSocket class CustomWS extends WebSocket { ... }; const connectorWithCustomWS = new Connector(CustomWS); connectorWithCustomWS.runWithWs('ws://example.cloudvision.api-server/api/v3/wrpc/'); // Start a secure authenticated connection. NOTE: the `wss` vs `ws` connector.run('wss://example.cloudvision.api-server/api/v3/wrpc/'); ``` #### Listening to the Connection Status The `Connector.connection` function adds a status-accepting callback to a `Connector` and returns an unbinding function that may be used to remove the callback. The status passed to the callback is either `Connector.CONNECTED`, or `Connector.DISCONNECTED`. Additionally, the WebSocket event (see WebSocket documentation) is passed as the second argument. - `Connector.CONNECTED` is emitted once the WebSocket connection has been established and the client is authenticated. At this point requests can be sent and the server will start sending responses. - `Connector.DISCONNECTED` is emitted when the WebSocket is hung up. ##### Example ```js function statusCallback(status, wsEvent) { switch (status) { case Connector.CONNECTED: // react to connected event break; case Connector.DISCONNECTED: // react to disconnected event break; } } // Add callback const unbindStatus = connector.connection(statusCallback); ... // Remove callback when done unbindStatus(); ``` Multiple callbacks may be added to a given `Connector` via `Connector.connection`: ```js // This is es6 arrow function notation (shortcut for function() {} ) const callback1 = (status) => {...} const callback2 = (status) => {...} const unbind1 = connector.connection(callback1) const unbind2 = connector.connection(callback2) ``` Callbacks will be called in the order in which they were added. ## Data Endcoding Data returned from the CloudVision APi is both JSON and NEAT (more strict MessagePack) encoded. Additionally NEAT encoded values are base64 encoded for transport. The notification body is JSON encoded, while `key` and `value` attributes of the notification are NEAT encoded. The parser inside the cloudvision-connector library takes care of decoding and encoding notifications for you. Note that when notifications are decoded they are decoded into an object keyed key the notification key. Since keys can be non strings, the key is the base64 NEAT encoded value. The value of this object contains both the decoded `key` and `value`. ## What is NEAT? NEAT is MessagePack with some alterations listed below: - All strings are binary encoded - Maps and Object keys are encoded in order of binary value of the key. This means `{ a: 'b', c: 'd' }` and `{ c: 'd', a: 'b' }` are encoded as the same NEAT value. - Support for pointer values via the `Pointer` extention type - Support for wildcard values via the `Wildcard` extention type ## Try it out To try out the CloudVision Connector in your browser, simply run ```shell npm install ``` at the root and then ```shell npm run build:try ``` in the **packages/cloudvision-connector** directory Then open **index.html** in your browser. In the developer console CloudVision Connector will be available as **window.CloudVisionConnector**. ### Examples Create the connector: `conn = new window.CloudVisionConnector()` Connect to an API server: `conn.run('ws://example.cloudvision.api-server/api/v3/wrpc/')` Run a query: `conn.getWithOptions(window.CloudVisionConnector.DEVICES_DATASET_ID , (err, res) => console.log(err, res))` ## Contributing Contributing pull requests are welcomed for this repository. Please note that all contributions require 100% code test cases and 100% code coverage, otherwise the pull request will be rejected. ## License The CloudVision Connector is [MIT licensed](LICENSE). <file_sep>import { ObservableInput, OperatorFunction, pipe, takeUntil, toArray } from 'rxjs'; /** Similar to `buffer`, except completes after the notifier emits. */ export function bufferOnce<T>(notifier: ObservableInput<unknown>): OperatorFunction<T, T[]> { return pipe(takeUntil(notifier), toArray()); } <file_sep>/* eslint-disable no-console */ import { encode, decode, Pointer, Codec } from '../src'; const pointer = new Pointer([ 'The', 'Dodgers', 'are', 'the', 'best', 'baseball', 'team', 'and', 'the', 'Astros', 'are', 'cheater', ]); const encoded = encode(pointer, { extensionCodec: Codec }); console.log('encoded size:', encoded.byteLength); console.time('decode pointer'); for (let i = 0; i < 1000; i++) { decode(encoded, { extensionCodec: Codec }); } console.timeEnd('decode pointer'); console.time('encode pointer'); for (let i = 0; i < 1000; i++) { encode(pointer, { extensionCodec: Codec }); } console.timeEnd('encode pointer'); <file_sep>import alias from '@rollup/plugin-alias'; import commonjs from '@rollup/plugin-commonjs'; import { nodeResolve } from '@rollup/plugin-node-resolve'; import replace from '@rollup/plugin-replace'; import typescript from '@rollup/plugin-typescript'; import path from 'path'; import { terser } from 'rollup-plugin-terser'; import packageJson from './package.json'; const env = process.env.NODE_ENV; const projectRootDir = path.resolve(__dirname); const config = { input: 'src/index.ts', onwarn: (warning) => { if ( warning.code === 'CIRCULAR_DEPENDENCY' && warning.importer === 'node_modules/protobufjs/src/util/minimal.js' ) { return; } if ( warning.code === 'EVAL' && (warning.id || '').includes('node_modules/@protobufjs/inquire/index.js') ) { return; } if (warning.loc) { throw new Error( `${warning.message} (${warning.loc.file}):${warning.loc.line}:${warning.loc.column}`, ); } throw new Error(warning.message); }, plugins: [ alias({ entries: [ { find: '@generated', replacement: path.resolve(projectRootDir, 'generated') }, { find: '@types', replacement: path.resolve(projectRootDir, 'types') }, ], }), typescript({ sourceMap: false }), ], }; const external = Object.keys(packageJson.dependencies); const globals = { '@arista/grpc-web': 'grpc-web', 'google-protobuf': 'google-protobuf', 'rxjs': 'rxjs', }; // Build preserving environment variables if (env === 'es' || env === 'cjs') { config.external = external; config.output = { exports: 'named', format: env, // globals, indent: false, }; config.plugins.push(nodeResolve(), commonjs()); } // Replace NODE_ENV variable if (env === 'development' || env === 'production') { if (!process.env.INCLUDE_EXTERNAL) { config.external = external; config.plugins.push(nodeResolve()); } else { config.plugins.push(nodeResolve({ browser: true })); } config.output = { exports: 'named', format: 'umd', globals, indent: false, name: 'CloudvisionGrpcWeb', }; config.plugins.push( replace({ preventAssignment: true, values: { 'process.env.NODE_ENV': JSON.stringify(env), 'process.env.TEXT_ENCODING': JSON.stringify('always'), 'process.env.TEXT_DECODER': JSON.stringify('always'), }, }), commonjs(), ); } if (env === 'production') { config.plugins.push(nodeResolve(), terser()); } export default config; <file_sep>import { ERROR, INFO, WARN } from '../src/constants'; export type LogLevel = typeof ERROR | typeof INFO | typeof WARN; /** @deprecated: Use `LogLevel`. */ export type LogLevels = LogLevel; <file_sep>/* eslint-disable @typescript-eslint/ban-ts-comment */ // @ts-nocheck /* eslint-disable */ import Long from 'long'; import _m0 from '@arista/protobufjs/minimal'; import { SourceContext } from '../../google/protobuf/source_context'; import { Any } from '../../google/protobuf/any'; export const protobufPackage = 'google.protobuf'; /** The syntax in which a protocol buffer element is defined. */ export enum Syntax { /** SYNTAX_PROTO2 - Syntax `proto2`. */ SYNTAX_PROTO2 = 0, /** SYNTAX_PROTO3 - Syntax `proto3`. */ SYNTAX_PROTO3 = 1, UNRECOGNIZED = -1, } export function syntaxFromJSON(object: any): Syntax { switch (object) { case 0: case 'SYNTAX_PROTO2': return Syntax.SYNTAX_PROTO2; case 1: case 'SYNTAX_PROTO3': return Syntax.SYNTAX_PROTO3; case -1: case 'UNRECOGNIZED': default: return Syntax.UNRECOGNIZED; } } export function syntaxToJSON(object: Syntax): string { switch (object) { case Syntax.SYNTAX_PROTO2: return 'SYNTAX_PROTO2'; case Syntax.SYNTAX_PROTO3: return 'SYNTAX_PROTO3'; default: return 'UNKNOWN'; } } /** A protocol buffer message type. */ export interface Type { /** The fully qualified message name. */ name: string; /** The list of fields. */ fields: Field[]; /** The list of types appearing in `oneof` definitions in this type. */ oneofs: string[]; /** The protocol buffer options. */ options: Option[]; /** The source context. */ sourceContext: SourceContext | undefined; /** The source syntax. */ syntax: Syntax; } /** A single field of a message type. */ export interface Field { /** The field type. */ kind: Field_Kind; /** The field cardinality. */ cardinality: Field_Cardinality; /** The field number. */ number: number; /** The field name. */ name: string; /** * The field type URL, without the scheme, for message or enumeration * types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`. */ typeUrl: string; /** * The index of the field type in `Type.oneofs`, for message or enumeration * types. The first type has index 1; zero means the type is not in the list. */ oneofIndex: number; /** Whether to use alternative packed wire representation. */ packed: boolean; /** The protocol buffer options. */ options: Option[]; /** The field JSON name. */ jsonName: string; /** The string value of the default value of this field. Proto2 syntax only. */ defaultValue: string; } /** Basic field types. */ export enum Field_Kind { /** TYPE_UNKNOWN - Field type unknown. */ TYPE_UNKNOWN = 0, /** TYPE_DOUBLE - Field type double. */ TYPE_DOUBLE = 1, /** TYPE_FLOAT - Field type float. */ TYPE_FLOAT = 2, /** TYPE_INT64 - Field type int64. */ TYPE_INT64 = 3, /** TYPE_UINT64 - Field type uint64. */ TYPE_UINT64 = 4, /** TYPE_INT32 - Field type int32. */ TYPE_INT32 = 5, /** TYPE_FIXED64 - Field type fixed64. */ TYPE_FIXED64 = 6, /** TYPE_FIXED32 - Field type fixed32. */ TYPE_FIXED32 = 7, /** TYPE_BOOL - Field type bool. */ TYPE_BOOL = 8, /** TYPE_STRING - Field type string. */ TYPE_STRING = 9, /** TYPE_GROUP - Field type group. Proto2 syntax only, and deprecated. */ TYPE_GROUP = 10, /** TYPE_MESSAGE - Field type message. */ TYPE_MESSAGE = 11, /** TYPE_BYTES - Field type bytes. */ TYPE_BYTES = 12, /** TYPE_UINT32 - Field type uint32. */ TYPE_UINT32 = 13, /** TYPE_ENUM - Field type enum. */ TYPE_ENUM = 14, /** TYPE_SFIXED32 - Field type sfixed32. */ TYPE_SFIXED32 = 15, /** TYPE_SFIXED64 - Field type sfixed64. */ TYPE_SFIXED64 = 16, /** TYPE_SINT32 - Field type sint32. */ TYPE_SINT32 = 17, /** TYPE_SINT64 - Field type sint64. */ TYPE_SINT64 = 18, UNRECOGNIZED = -1, } export function field_KindFromJSON(object: any): Field_Kind { switch (object) { case 0: case 'TYPE_UNKNOWN': return Field_Kind.TYPE_UNKNOWN; case 1: case 'TYPE_DOUBLE': return Field_Kind.TYPE_DOUBLE; case 2: case 'TYPE_FLOAT': return Field_Kind.TYPE_FLOAT; case 3: case 'TYPE_INT64': return Field_Kind.TYPE_INT64; case 4: case 'TYPE_UINT64': return Field_Kind.TYPE_UINT64; case 5: case 'TYPE_INT32': return Field_Kind.TYPE_INT32; case 6: case 'TYPE_FIXED64': return Field_Kind.TYPE_FIXED64; case 7: case 'TYPE_FIXED32': return Field_Kind.TYPE_FIXED32; case 8: case 'TYPE_BOOL': return Field_Kind.TYPE_BOOL; case 9: case 'TYPE_STRING': return Field_Kind.TYPE_STRING; case 10: case 'TYPE_GROUP': return Field_Kind.TYPE_GROUP; case 11: case 'TYPE_MESSAGE': return Field_Kind.TYPE_MESSAGE; case 12: case 'TYPE_BYTES': return Field_Kind.TYPE_BYTES; case 13: case 'TYPE_UINT32': return Field_Kind.TYPE_UINT32; case 14: case 'TYPE_ENUM': return Field_Kind.TYPE_ENUM; case 15: case 'TYPE_SFIXED32': return Field_Kind.TYPE_SFIXED32; case 16: case 'TYPE_SFIXED64': return Field_Kind.TYPE_SFIXED64; case 17: case 'TYPE_SINT32': return Field_Kind.TYPE_SINT32; case 18: case 'TYPE_SINT64': return Field_Kind.TYPE_SINT64; case -1: case 'UNRECOGNIZED': default: return Field_Kind.UNRECOGNIZED; } } export function field_KindToJSON(object: Field_Kind): string { switch (object) { case Field_Kind.TYPE_UNKNOWN: return 'TYPE_UNKNOWN'; case Field_Kind.TYPE_DOUBLE: return 'TYPE_DOUBLE'; case Field_Kind.TYPE_FLOAT: return 'TYPE_FLOAT'; case Field_Kind.TYPE_INT64: return 'TYPE_INT64'; case Field_Kind.TYPE_UINT64: return 'TYPE_UINT64'; case Field_Kind.TYPE_INT32: return 'TYPE_INT32'; case Field_Kind.TYPE_FIXED64: return 'TYPE_FIXED64'; case Field_Kind.TYPE_FIXED32: return 'TYPE_FIXED32'; case Field_Kind.TYPE_BOOL: return 'TYPE_BOOL'; case Field_Kind.TYPE_STRING: return 'TYPE_STRING'; case Field_Kind.TYPE_GROUP: return 'TYPE_GROUP'; case Field_Kind.TYPE_MESSAGE: return 'TYPE_MESSAGE'; case Field_Kind.TYPE_BYTES: return 'TYPE_BYTES'; case Field_Kind.TYPE_UINT32: return 'TYPE_UINT32'; case Field_Kind.TYPE_ENUM: return 'TYPE_ENUM'; case Field_Kind.TYPE_SFIXED32: return 'TYPE_SFIXED32'; case Field_Kind.TYPE_SFIXED64: return 'TYPE_SFIXED64'; case Field_Kind.TYPE_SINT32: return 'TYPE_SINT32'; case Field_Kind.TYPE_SINT64: return 'TYPE_SINT64'; default: return 'UNKNOWN'; } } /** Whether a field is optional, required, or repeated. */ export enum Field_Cardinality { /** CARDINALITY_UNKNOWN - For fields with unknown cardinality. */ CARDINALITY_UNKNOWN = 0, /** CARDINALITY_OPTIONAL - For optional fields. */ CARDINALITY_OPTIONAL = 1, /** CARDINALITY_REQUIRED - For required fields. Proto2 syntax only. */ CARDINALITY_REQUIRED = 2, /** CARDINALITY_REPEATED - For repeated fields. */ CARDINALITY_REPEATED = 3, UNRECOGNIZED = -1, } export function field_CardinalityFromJSON(object: any): Field_Cardinality { switch (object) { case 0: case 'CARDINALITY_UNKNOWN': return Field_Cardinality.CARDINALITY_UNKNOWN; case 1: case 'CARDINALITY_OPTIONAL': return Field_Cardinality.CARDINALITY_OPTIONAL; case 2: case 'CARDINALITY_REQUIRED': return Field_Cardinality.CARDINALITY_REQUIRED; case 3: case 'CARDINALITY_REPEATED': return Field_Cardinality.CARDINALITY_REPEATED; case -1: case 'UNRECOGNIZED': default: return Field_Cardinality.UNRECOGNIZED; } } export function field_CardinalityToJSON(object: Field_Cardinality): string { switch (object) { case Field_Cardinality.CARDINALITY_UNKNOWN: return 'CARDINALITY_UNKNOWN'; case Field_Cardinality.CARDINALITY_OPTIONAL: return 'CARDINALITY_OPTIONAL'; case Field_Cardinality.CARDINALITY_REQUIRED: return 'CARDINALITY_REQUIRED'; case Field_Cardinality.CARDINALITY_REPEATED: return 'CARDINALITY_REPEATED'; default: return 'UNKNOWN'; } } /** Enum type definition. */ export interface Enum { /** Enum type name. */ name: string; /** Enum value definitions. */ enumvalue: EnumValue[]; /** Protocol buffer options. */ options: Option[]; /** The source context. */ sourceContext: SourceContext | undefined; /** The source syntax. */ syntax: Syntax; } /** Enum value definition. */ export interface EnumValue { /** Enum value name. */ name: string; /** Enum value number. */ number: number; /** Protocol buffer options. */ options: Option[]; } /** * A protocol buffer option, which can be attached to a message, field, * enumeration, etc. */ export interface Option { /** * The option's name. For protobuf built-in options (options defined in * descriptor.proto), this is the short name. For example, `"map_entry"`. * For custom options, it should be the fully-qualified name. For example, * `"google.api.http"`. */ name: string; /** * The option's value packed in an Any message. If the value is a primitive, * the corresponding wrapper type defined in google/protobuf/wrappers.proto * should be used. If the value is an enum, it should be stored as an int32 * value using the google.protobuf.Int32Value type. */ value: Any | undefined; } const baseType: object = { name: '', oneofs: '', syntax: 0 }; export const Type = { encode(message: Type, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { if (message.name !== '') { writer.uint32(10).string(message.name); } for (const v of message.fields) { Field.encode(v!, writer.uint32(18).fork()).ldelim(); } for (const v of message.oneofs) { writer.uint32(26).string(v!); } for (const v of message.options) { Option.encode(v!, writer.uint32(34).fork()).ldelim(); } if (message.sourceContext !== undefined) { SourceContext.encode(message.sourceContext, writer.uint32(42).fork()).ldelim(); } if (message.syntax !== 0) { writer.uint32(48).int32(message.syntax); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Type { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseType } as Type; message.fields = []; message.oneofs = []; message.options = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.name = reader.string(); break; case 2: message.fields.push(Field.decode(reader, reader.uint32())); break; case 3: message.oneofs.push(reader.string()); break; case 4: message.options.push(Option.decode(reader, reader.uint32())); break; case 5: message.sourceContext = SourceContext.decode(reader, reader.uint32()); break; case 6: message.syntax = reader.int32() as any; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Type { const message = { ...baseType } as Type; message.fields = []; message.oneofs = []; message.options = []; if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } else { message.name = ''; } if (object.fields !== undefined && object.fields !== null) { for (const e of object.fields) { message.fields.push(Field.fromJSON(e)); } } if (object.oneofs !== undefined && object.oneofs !== null) { for (const e of object.oneofs) { message.oneofs.push(String(e)); } } if (object.options !== undefined && object.options !== null) { for (const e of object.options) { message.options.push(Option.fromJSON(e)); } } if (object.sourceContext !== undefined && object.sourceContext !== null) { message.sourceContext = SourceContext.fromJSON(object.sourceContext); } else { message.sourceContext = undefined; } if (object.syntax !== undefined && object.syntax !== null) { message.syntax = syntaxFromJSON(object.syntax); } else { message.syntax = 0; } return message; }, toJSON(message: Type): unknown { const obj: any = {}; message.name !== undefined && (obj.name = message.name); if (message.fields) { obj.fields = message.fields.map((e) => (e ? Field.toJSON(e) : undefined)); } else { obj.fields = []; } if (message.oneofs) { obj.oneofs = message.oneofs.map((e) => e); } else { obj.oneofs = []; } if (message.options) { obj.options = message.options.map((e) => (e ? Option.toJSON(e) : undefined)); } else { obj.options = []; } message.sourceContext !== undefined && (obj.sourceContext = message.sourceContext ? SourceContext.toJSON(message.sourceContext) : undefined); message.syntax !== undefined && (obj.syntax = syntaxToJSON(message.syntax)); return obj; }, fromPartial(object: DeepPartial<Type>): Type { const message = { ...baseType } as Type; message.fields = []; message.oneofs = []; message.options = []; if (object.name !== undefined && object.name !== null) { message.name = object.name; } else { message.name = ''; } if (object.fields !== undefined && object.fields !== null) { for (const e of object.fields) { message.fields.push(Field.fromPartial(e)); } } if (object.oneofs !== undefined && object.oneofs !== null) { for (const e of object.oneofs) { message.oneofs.push(e); } } if (object.options !== undefined && object.options !== null) { for (const e of object.options) { message.options.push(Option.fromPartial(e)); } } if (object.sourceContext !== undefined && object.sourceContext !== null) { message.sourceContext = SourceContext.fromPartial(object.sourceContext); } else { message.sourceContext = undefined; } if (object.syntax !== undefined && object.syntax !== null) { message.syntax = object.syntax; } else { message.syntax = 0; } return message; }, }; const baseField: object = { kind: 0, cardinality: 0, number: 0, name: '', typeUrl: '', oneofIndex: 0, packed: false, jsonName: '', defaultValue: '', }; export const Field = { encode(message: Field, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { if (message.kind !== 0) { writer.uint32(8).int32(message.kind); } if (message.cardinality !== 0) { writer.uint32(16).int32(message.cardinality); } if (message.number !== 0) { writer.uint32(24).int32(message.number); } if (message.name !== '') { writer.uint32(34).string(message.name); } if (message.typeUrl !== '') { writer.uint32(50).string(message.typeUrl); } if (message.oneofIndex !== 0) { writer.uint32(56).int32(message.oneofIndex); } if (message.packed === true) { writer.uint32(64).bool(message.packed); } for (const v of message.options) { Option.encode(v!, writer.uint32(74).fork()).ldelim(); } if (message.jsonName !== '') { writer.uint32(82).string(message.jsonName); } if (message.defaultValue !== '') { writer.uint32(90).string(message.defaultValue); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Field { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseField } as Field; message.options = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.kind = reader.int32() as any; break; case 2: message.cardinality = reader.int32() as any; break; case 3: message.number = reader.int32(); break; case 4: message.name = reader.string(); break; case 6: message.typeUrl = reader.string(); break; case 7: message.oneofIndex = reader.int32(); break; case 8: message.packed = reader.bool(); break; case 9: message.options.push(Option.decode(reader, reader.uint32())); break; case 10: message.jsonName = reader.string(); break; case 11: message.defaultValue = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Field { const message = { ...baseField } as Field; message.options = []; if (object.kind !== undefined && object.kind !== null) { message.kind = field_KindFromJSON(object.kind); } else { message.kind = 0; } if (object.cardinality !== undefined && object.cardinality !== null) { message.cardinality = field_CardinalityFromJSON(object.cardinality); } else { message.cardinality = 0; } if (object.number !== undefined && object.number !== null) { message.number = Number(object.number); } else { message.number = 0; } if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } else { message.name = ''; } if (object.typeUrl !== undefined && object.typeUrl !== null) { message.typeUrl = String(object.typeUrl); } else { message.typeUrl = ''; } if (object.oneofIndex !== undefined && object.oneofIndex !== null) { message.oneofIndex = Number(object.oneofIndex); } else { message.oneofIndex = 0; } if (object.packed !== undefined && object.packed !== null) { message.packed = Boolean(object.packed); } else { message.packed = false; } if (object.options !== undefined && object.options !== null) { for (const e of object.options) { message.options.push(Option.fromJSON(e)); } } if (object.jsonName !== undefined && object.jsonName !== null) { message.jsonName = String(object.jsonName); } else { message.jsonName = ''; } if (object.defaultValue !== undefined && object.defaultValue !== null) { message.defaultValue = String(object.defaultValue); } else { message.defaultValue = ''; } return message; }, toJSON(message: Field): unknown { const obj: any = {}; message.kind !== undefined && (obj.kind = field_KindToJSON(message.kind)); message.cardinality !== undefined && (obj.cardinality = field_CardinalityToJSON(message.cardinality)); message.number !== undefined && (obj.number = message.number); message.name !== undefined && (obj.name = message.name); message.typeUrl !== undefined && (obj.typeUrl = message.typeUrl); message.oneofIndex !== undefined && (obj.oneofIndex = message.oneofIndex); message.packed !== undefined && (obj.packed = message.packed); if (message.options) { obj.options = message.options.map((e) => (e ? Option.toJSON(e) : undefined)); } else { obj.options = []; } message.jsonName !== undefined && (obj.jsonName = message.jsonName); message.defaultValue !== undefined && (obj.defaultValue = message.defaultValue); return obj; }, fromPartial(object: DeepPartial<Field>): Field { const message = { ...baseField } as Field; message.options = []; if (object.kind !== undefined && object.kind !== null) { message.kind = object.kind; } else { message.kind = 0; } if (object.cardinality !== undefined && object.cardinality !== null) { message.cardinality = object.cardinality; } else { message.cardinality = 0; } if (object.number !== undefined && object.number !== null) { message.number = object.number; } else { message.number = 0; } if (object.name !== undefined && object.name !== null) { message.name = object.name; } else { message.name = ''; } if (object.typeUrl !== undefined && object.typeUrl !== null) { message.typeUrl = object.typeUrl; } else { message.typeUrl = ''; } if (object.oneofIndex !== undefined && object.oneofIndex !== null) { message.oneofIndex = object.oneofIndex; } else { message.oneofIndex = 0; } if (object.packed !== undefined && object.packed !== null) { message.packed = object.packed; } else { message.packed = false; } if (object.options !== undefined && object.options !== null) { for (const e of object.options) { message.options.push(Option.fromPartial(e)); } } if (object.jsonName !== undefined && object.jsonName !== null) { message.jsonName = object.jsonName; } else { message.jsonName = ''; } if (object.defaultValue !== undefined && object.defaultValue !== null) { message.defaultValue = object.defaultValue; } else { message.defaultValue = ''; } return message; }, }; const baseEnum: object = { name: '', syntax: 0 }; export const Enum = { encode(message: Enum, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { if (message.name !== '') { writer.uint32(10).string(message.name); } for (const v of message.enumvalue) { EnumValue.encode(v!, writer.uint32(18).fork()).ldelim(); } for (const v of message.options) { Option.encode(v!, writer.uint32(26).fork()).ldelim(); } if (message.sourceContext !== undefined) { SourceContext.encode(message.sourceContext, writer.uint32(34).fork()).ldelim(); } if (message.syntax !== 0) { writer.uint32(40).int32(message.syntax); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Enum { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseEnum } as Enum; message.enumvalue = []; message.options = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.name = reader.string(); break; case 2: message.enumvalue.push(EnumValue.decode(reader, reader.uint32())); break; case 3: message.options.push(Option.decode(reader, reader.uint32())); break; case 4: message.sourceContext = SourceContext.decode(reader, reader.uint32()); break; case 5: message.syntax = reader.int32() as any; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Enum { const message = { ...baseEnum } as Enum; message.enumvalue = []; message.options = []; if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } else { message.name = ''; } if (object.enumvalue !== undefined && object.enumvalue !== null) { for (const e of object.enumvalue) { message.enumvalue.push(EnumValue.fromJSON(e)); } } if (object.options !== undefined && object.options !== null) { for (const e of object.options) { message.options.push(Option.fromJSON(e)); } } if (object.sourceContext !== undefined && object.sourceContext !== null) { message.sourceContext = SourceContext.fromJSON(object.sourceContext); } else { message.sourceContext = undefined; } if (object.syntax !== undefined && object.syntax !== null) { message.syntax = syntaxFromJSON(object.syntax); } else { message.syntax = 0; } return message; }, toJSON(message: Enum): unknown { const obj: any = {}; message.name !== undefined && (obj.name = message.name); if (message.enumvalue) { obj.enumvalue = message.enumvalue.map((e) => (e ? EnumValue.toJSON(e) : undefined)); } else { obj.enumvalue = []; } if (message.options) { obj.options = message.options.map((e) => (e ? Option.toJSON(e) : undefined)); } else { obj.options = []; } message.sourceContext !== undefined && (obj.sourceContext = message.sourceContext ? SourceContext.toJSON(message.sourceContext) : undefined); message.syntax !== undefined && (obj.syntax = syntaxToJSON(message.syntax)); return obj; }, fromPartial(object: DeepPartial<Enum>): Enum { const message = { ...baseEnum } as Enum; message.enumvalue = []; message.options = []; if (object.name !== undefined && object.name !== null) { message.name = object.name; } else { message.name = ''; } if (object.enumvalue !== undefined && object.enumvalue !== null) { for (const e of object.enumvalue) { message.enumvalue.push(EnumValue.fromPartial(e)); } } if (object.options !== undefined && object.options !== null) { for (const e of object.options) { message.options.push(Option.fromPartial(e)); } } if (object.sourceContext !== undefined && object.sourceContext !== null) { message.sourceContext = SourceContext.fromPartial(object.sourceContext); } else { message.sourceContext = undefined; } if (object.syntax !== undefined && object.syntax !== null) { message.syntax = object.syntax; } else { message.syntax = 0; } return message; }, }; const baseEnumValue: object = { name: '', number: 0 }; export const EnumValue = { encode(message: EnumValue, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { if (message.name !== '') { writer.uint32(10).string(message.name); } if (message.number !== 0) { writer.uint32(16).int32(message.number); } for (const v of message.options) { Option.encode(v!, writer.uint32(26).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): EnumValue { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseEnumValue } as EnumValue; message.options = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.name = reader.string(); break; case 2: message.number = reader.int32(); break; case 3: message.options.push(Option.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): EnumValue { const message = { ...baseEnumValue } as EnumValue; message.options = []; if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } else { message.name = ''; } if (object.number !== undefined && object.number !== null) { message.number = Number(object.number); } else { message.number = 0; } if (object.options !== undefined && object.options !== null) { for (const e of object.options) { message.options.push(Option.fromJSON(e)); } } return message; }, toJSON(message: EnumValue): unknown { const obj: any = {}; message.name !== undefined && (obj.name = message.name); message.number !== undefined && (obj.number = message.number); if (message.options) { obj.options = message.options.map((e) => (e ? Option.toJSON(e) : undefined)); } else { obj.options = []; } return obj; }, fromPartial(object: DeepPartial<EnumValue>): EnumValue { const message = { ...baseEnumValue } as EnumValue; message.options = []; if (object.name !== undefined && object.name !== null) { message.name = object.name; } else { message.name = ''; } if (object.number !== undefined && object.number !== null) { message.number = object.number; } else { message.number = 0; } if (object.options !== undefined && object.options !== null) { for (const e of object.options) { message.options.push(Option.fromPartial(e)); } } return message; }, }; const baseOption: object = { name: '' }; export const Option = { encode(message: Option, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { if (message.name !== '') { writer.uint32(10).string(message.name); } if (message.value !== undefined) { Any.encode(message.value, writer.uint32(18).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Option { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseOption } as Option; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.name = reader.string(); break; case 2: message.value = Any.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Option { const message = { ...baseOption } as Option; if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } else { message.name = ''; } if (object.value !== undefined && object.value !== null) { message.value = Any.fromJSON(object.value); } else { message.value = undefined; } return message; }, toJSON(message: Option): unknown { const obj: any = {}; message.name !== undefined && (obj.name = message.name); message.value !== undefined && (obj.value = message.value ? Any.toJSON(message.value) : undefined); return obj; }, fromPartial(object: DeepPartial<Option>): Option { const message = { ...baseOption } as Option; if (object.name !== undefined && object.name !== null) { message.name = object.name; } else { message.name = ''; } if (object.value !== undefined && object.value !== null) { message.value = Any.fromPartial(object.value); } else { message.value = undefined; } return message; }, }; type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined; export type DeepPartial<T> = T extends Builtin ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> } : Partial<T>; if (_m0.util.Long !== Long) { _m0.util.Long = Long as any; _m0.configure(); } <file_sep>/* eslint-disable no-console, global-require, @typescript-eslint/no-non-null-assertion, @typescript-eslint/no-var-requires, import/no-dynamic-require */ import Benchmark from 'benchmark'; interface Implementation { encode: (d: unknown) => Uint8Array | string; decode: (d: Uint8Array | string) => unknown; toDecode?: Uint8Array | string; } const implementations: { [name: string]: Implementation; } = { 'a-msgpack': { encode: require('../src').encode, decode: require('../src').decode, }, '@msgpack/msgpack': { encode: require('@msgpack/msgpack').encode, decode: require('@msgpack/msgpack').decode, }, 'msgpack-lite': { encode: require('msgpack-lite').encode, decode: require('msgpack-lite').decode, }, 'msgpack-js-v5': { encode: require('msgpack-js-v5').encode, decode: require('msgpack-js-v5').decode, }, 'msgpack-js': { encode: require('msgpack-js').encode, decode: require('msgpack-js').decode, }, 'notepack.io': { encode: require('notepack.io/browser/encode'), decode: require('notepack.io/browser/decode'), }, JSON: { encode: (obj: unknown): string => JSON.stringify(obj), decode: (str: string | Uint8Array): unknown => JSON.parse(str as string), }, }; const sampleFiles = ['./sample-large.json']; for (const sampleFile of sampleFiles) { const data = require(sampleFile); const encodeSuite = new Benchmark.Suite(); const decodeSuite = new Benchmark.Suite(); console.log(''); console.log('**' + sampleFile + ':** (' + JSON.stringify(data).length + ' bytes in JSON)'); console.log(''); for (const name of Object.keys(implementations)) { implementations[name].toDecode = implementations[name].encode(data); encodeSuite.add('(encode) ' + name, () => { implementations[name].encode(data); }); decodeSuite.add('(decode) ' + name, () => { implementations[name].decode(implementations[name].toDecode!); }); } encodeSuite.on('cycle', (event: Event) => { console.log(String(event.target)); }); console.log('```'); encodeSuite.run(); console.log('```'); console.log(''); decodeSuite.on('cycle', (event: Event) => { console.log(String(event.target)); }); console.log('```'); decodeSuite.run(); console.log('```'); } <file_sep>/* eslint-disable @typescript-eslint/ban-ts-comment */ // @ts-nocheck /* eslint-disable */ import Long from 'long'; import _m0 from '@arista/protobufjs/minimal'; export const protobufPackage = 'google.protobuf'; /** * `SourceContext` represents information about the source of a * protobuf element, like the file in which it is defined. */ export interface SourceContext { /** * The path-qualified name of the .proto file that contained the associated * protobuf element. For example: `"google/protobuf/source_context.proto"`. */ fileName: string; } const baseSourceContext: object = { fileName: '' }; export const SourceContext = { encode(message: SourceContext, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { if (message.fileName !== '') { writer.uint32(10).string(message.fileName); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): SourceContext { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseSourceContext } as SourceContext; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.fileName = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): SourceContext { const message = { ...baseSourceContext } as SourceContext; if (object.fileName !== undefined && object.fileName !== null) { message.fileName = String(object.fileName); } else { message.fileName = ''; } return message; }, toJSON(message: SourceContext): unknown { const obj: any = {}; message.fileName !== undefined && (obj.fileName = message.fileName); return obj; }, fromPartial(object: DeepPartial<SourceContext>): SourceContext { const message = { ...baseSourceContext } as SourceContext; if (object.fileName !== undefined && object.fileName !== null) { message.fileName = object.fileName; } else { message.fileName = ''; } return message; }, }; type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined; export type DeepPartial<T> = T extends Builtin ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> } : Partial<T>; if (_m0.util.Long !== Long) { _m0.util.Long = Long as any; _m0.configure(); } <file_sep># Change Log All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. ## [5.0.2](https://github.com/aristanetworks/cloudvision/compare/v5.0.1...v5.0.2) (2023-01-18) ### Bug Fixes * **a-msgpack:** write uint32 when appropriate ([#938](https://github.com/aristanetworks/cloudvision/issues/938)) ([aed30eb](https://github.com/aristanetworks/cloudvision/commit/aed30eb459caef97acbd0d57231587e608cb6af3)) ## [5.0.1](https://github.com/aristanetworks/cloudvision/compare/v5.0.0...v5.0.1) (2022-07-18) **Note:** Version bump only for package a-msgpack # [5.0.0](https://github.com/aristanetworks/cloudvision/compare/v4.14.0...v5.0.0) (2022-07-11) * chore(deps)!: update dependency jsbi to v4 (#598) ([c0672d9](https://github.com/aristanetworks/cloudvision/commit/c0672d92c0391a75e081246a4cbb25ff2fc3cfca)), closes [#598](https://github.com/aristanetworks/cloudvision/issues/598) ### BREAKING CHANGES * Upgrade to JSBI v4 # [4.14.0](https://github.com/aristanetworks/cloudvision/compare/v4.13.1...v4.14.0) (2022-05-30) **Note:** Version bump only for package a-msgpack ## [4.13.1](https://github.com/aristanetworks/cloudvision/compare/v4.13.0...v4.13.1) (2022-05-05) **Note:** Version bump only for package a-msgpack # [4.13.0](https://github.com/aristanetworks/cloudvision/compare/v4.12.2...v4.13.0) (2022-04-26) **Note:** Version bump only for package a-msgpack ## [4.12.2](https://github.com/aristanetworks/cloudvision/compare/v4.12.1...v4.12.2) (2022-04-04) **Note:** Version bump only for package a-msgpack ## [4.12.1](https://github.com/aristanetworks/cloudvision/compare/v4.12.0...v4.12.1) (2022-03-21) **Note:** Version bump only for package a-msgpack # [4.12.0](https://github.com/aristanetworks/cloudvision/compare/v4.11.0...v4.12.0) (2021-10-05) **Note:** Version bump only for package a-msgpack # [4.11.0](https://github.com/aristanetworks/cloudvision/compare/v4.10.1...v4.11.0) (2021-10-04) ### Bug Fixes * **msgpack:** encode stripped neat objects ([#568](https://github.com/aristanetworks/cloudvision/issues/568)) ([5498236](https://github.com/aristanetworks/cloudvision/commit/5498236baa65756c5f29aad801963877e7905246)) ## [4.10.1](https://github.com/aristanetworks/cloudvision/compare/v4.10.0...v4.10.1) (2021-09-17) **Note:** Version bump only for package a-msgpack # [4.10.0](https://github.com/aristanetworks/cloudvision/compare/v4.9.2...v4.10.0) (2021-09-08) **Note:** Version bump only for package a-msgpack ## [4.9.2](https://github.com/aristanetworks/cloudvision/compare/v4.9.1...v4.9.2) (2021-08-06) **Note:** Version bump only for package a-msgpack ## [4.9.1](https://github.com/aristanetworks/cloudvision/compare/v4.9.0...v4.9.1) (2021-07-22) ### Bug Fixes * update packages ([#470](https://github.com/aristanetworks/cloudvision/issues/470)) ([264d1e0](https://github.com/aristanetworks/cloudvision/commit/264d1e04045ec9ae2efeaf1ff87cf4b9339626c5)) # [4.9.0](https://github.com/aristanetworks/cloudvision/compare/v4.8.0...v4.9.0) (2021-06-17) **Note:** Version bump only for package a-msgpack # [4.8.0](https://github.com/aristanetworks/cloudvision/compare/v4.7.0...v4.8.0) (2021-05-18) **Note:** Version bump only for package a-msgpack # [4.7.0](https://github.com/aristanetworks/cloudvision/compare/v4.6.5...v4.7.0) (2021-03-08) **Note:** Version bump only for package a-msgpack ## [4.6.5](https://github.com/aristanetworks/cloudvision/compare/v4.6.4...v4.6.5) (2021-01-20) **Note:** Version bump only for package a-msgpack ## [4.6.4](https://github.com/aristanetworks/cloudvision/compare/v4.6.3...v4.6.4) (2021-01-19) **Note:** Version bump only for package a-msgpack ## [4.6.3](https://github.com/aristanetworks/cloudvision/compare/v4.6.2...v4.6.3) (2020-12-15) **Note:** Version bump only for package a-msgpack ## [4.6.2](https://github.com/aristanetworks/cloudvision/compare/v4.6.1...v4.6.2) (2020-12-01) ### Bug Fixes * **a-msgpack:** properly key nested complex values ([#287](https://github.com/aristanetworks/cloudvision/issues/287)) ([0de0421](https://github.com/aristanetworks/cloudvision/commit/0de0421dfd868d29dcd4902a0c899ccd958a941f)) ## [4.6.1](https://github.com/aristanetworks/cloudvision/compare/v4.6.0...v4.6.1) (2020-11-04) ### Bug Fixes * **a-msgpack:** Always convert int64 to BigInt ([#224](https://github.com/aristanetworks/cloudvision/issues/224)) ([85c4c4e](https://github.com/aristanetworks/cloudvision/commit/85c4c4ed5642d89e44f5a5a705e4891d854c22fc)) # [4.6.0](https://github.com/aristanetworks/cloudvision/compare/v4.5.5...v4.6.0) (2020-10-05) **Note:** Version bump only for package a-msgpack ## [4.5.5](https://github.com/aristanetworks/cloudvision/compare/v4.5.4...v4.5.5) (2020-09-16) **Note:** Version bump only for package a-msgpack ## [4.5.4](https://github.com/aristanetworks/cloudvision/compare/v4.5.3...v4.5.4) (2020-08-10) **Note:** Version bump only for package a-msgpack ## [4.5.3](https://github.com/aristanetworks/cloudvision/compare/v4.5.2...v4.5.3) (2020-07-29) **Note:** Version bump only for package a-msgpack ## [4.5.1](https://github.com/aristanetworks/cloudvision/compare/v4.5.0...v4.5.1) (2020-07-28) **Note:** Version bump only for package a-msgpack # [4.5.0](https://github.com/aristanetworks/cloudvision/compare/v4.4.0...v4.5.0) (2020-07-27) **Note:** Version bump only for package a-msgpack # [4.4.0](https://github.com/aristanetworks/cloudvision/compare/v4.3.1...v4.4.0) (2020-07-14) ### Features * **a-msgpack:** add Wildcard support ([#124](https://github.com/aristanetworks/cloudvision/issues/124)) ([09d75d7](https://github.com/aristanetworks/cloudvision/commit/09d75d7d80faab8fe70f707e82529f8d5c213d42)) ## [4.3.1](https://github.com/aristanetworks/cloudvision/compare/v4.3.0...v4.3.1) (2020-07-07) **Note:** Version bump only for package a-msgpack # [4.3.0](https://github.com/aristanetworks/cloudvision/compare/v4.2.0...v4.3.0) (2020-06-08) ### Bug Fixes * **packages:** add rimraf dev dependency ([#79](https://github.com/aristanetworks/cloudvision/issues/79)) ([15396e7](https://github.com/aristanetworks/cloudvision/commit/15396e72ca26bf7fc13009233c597cefe336d214)) # [4.2.0](https://github.com/aristanetworks/cloudvision/compare/v4.1.0...v4.2.0) (2020-05-19) **Note:** Version bump only for package a-msgpack # [4.1.0](https://github.com/aristanetworks/cloudvision/compare/v4.0.5...v4.1.0) (2020-05-11) **Note:** Version bump only for package a-msgpack ## [4.0.5](https://github.com/aristanetworks/cloudvision/compare/v4.0.4...v4.0.5) (2020-05-06) **Note:** Version bump only for package a-msgpack ## [4.0.4](https://github.com/aristanetworks/cloudvision/compare/v4.0.3...v4.0.4) (2020-04-28) **Note:** Version bump only for package a-msgpack ## [4.0.3](https://github.com/aristanetworks/cloudvision/compare/v4.0.2...v4.0.3) (2020-04-24) **Note:** Version bump only for package a-msgpack ## [4.0.2](https://github.com/aristanetworks/cloudvision/compare/v4.0.1...v4.0.2) (2020-04-21) **Note:** Version bump only for package a-msgpack ## 4.0.1 (2020-04-15) **Note:** Version bump only for package a-msgpack ## [0.3.24](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.24) (2020-04-06) **Note:** Version bump only for package a-msgpack ## [0.3.23](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.23) (2020-03-30) **Note:** Version bump only for package a-msgpack ## [0.3.22](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.22) (2020-03-23) **Note:** Version bump only for package a-msgpack ## [0.3.21](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.21) (2020-03-20) **Note:** Version bump only for package a-msgpack ## [0.3.20](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.20) (2020-03-20) **Note:** Version bump only for package a-msgpack ## [0.3.19](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.19) (2020-03-19) **Note:** Version bump only for package a-msgpack ## [0.3.18](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.18) (2020-03-16) **Note:** Version bump only for package a-msgpack ## [0.3.17](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.17) (2020-03-09) **Note:** Version bump only for package a-msgpack ## [0.3.16](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.16) (2020-03-04) **Note:** Version bump only for package a-msgpack ## [0.3.15](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.15) (2020-02-26) **Note:** Version bump only for package a-msgpack ## [0.3.14](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.14) (2020-02-25) ### Bug Fixes * **a-msgpack:** account for int64 less than MAX_SAFE ([5e1df74](http://gerrit.corp.arista.io:29418/web-components/commits/5e1df741acc598804bcf9609aa5de645d99ce94e)) ## [0.3.13](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.13) (2020-02-24) **Note:** Version bump only for package a-msgpack ## [0.3.12](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.12) (2020-02-17) **Note:** Version bump only for package a-msgpack ## [0.3.11](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.11) (2020-02-10) **Note:** Version bump only for package a-msgpack ## [0.3.10](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.10) (2020-02-03) ### Bug Fixes * **a-msgpack:** add base64-js back to config files ([2a435f8](http://gerrit.corp.arista.io:29418/web-components/commits/2a435f898035e1ee6728103e89deb090f6d6bb6c)) * **a-msgpack,cloudvision-connector:** move to/from binary key utils ([b6be876](http://gerrit.corp.arista.io:29418/web-components/commits/b6be876b2dbe4b831ac9e1e3ae6805bccada29f0)) ## [0.3.9](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.9) (2020-01-27) **Note:** Version bump only for package a-msgpack ## [0.3.8](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.8) (2020-01-22) ### Bug Fixes * **a-msgpack:** allow BigInt configuration of fromBinaryKey ([08c63a2](http://gerrit.corp.arista.io:29418/web-components/commits/08c63a285a362b839cb8ba547add95a4d0c8161e)) ## [0.3.7](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.7) (2020-01-22) ### Bug Fixes * **a-msgpack,cloudvision-connector:** improve perf ([3b6992d](http://gerrit.corp.arista.io:29418/web-components/commits/3b6992d783463f8f4f000c3334ceb0693e793083)) ## [0.3.6](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.6) (2020-01-20) **Note:** Version bump only for package a-msgpack ## [0.3.5](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.5) (2019-12-30) **Note:** Version bump only for package a-msgpack ## [0.3.4](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.4) (2019-11-19) **Note:** Version bump only for package a-msgpack ## [0.3.3](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.3) (2019-10-21) **Note:** Version bump only for package a-msgpack ## [0.3.2](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.2) (2019-10-14) **Note:** Version bump only for package a-msgpack ## [0.3.1](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.1) (2019-10-07) ### Bug Fixes * **a-msgpack:** package proper files ([e68ab76](http://gerrit.corp.arista.io:29418/web-components/commits/e68ab76)) # [0.3.0](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.3.0) (2019-10-04) ### Features * **a-msgpack, cloudvision-connector:** Move to Typescript ([acf4e70](http://gerrit.corp.arista.io:29418/web-components/commits/acf4e70)) ## [0.2.8](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.2.8) (2019-09-23) **Note:** Version bump only for package a-msgpack ## [0.2.7](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.2.7) (2019-09-17) **Note:** Version bump only for package a-msgpack ## [0.2.6](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.2.6) (2019-09-16) **Note:** Version bump only for package a-msgpack ## [0.2.5](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.2.5) (2019-09-14) **Note:** Version bump only for package a-msgpack ## [0.2.4](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.2.4) (2019-09-10) **Note:** Version bump only for package a-msgpack ## [0.2.3](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.2.3) (2019-08-30) **Note:** Version bump only for package a-msgpack ## [0.2.2](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.2.2) (2019-08-29) **Note:** Version bump only for package a-msgpack ## [0.2.1](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.2.1) (2019-08-26) **Note:** Version bump only for package a-msgpack # [0.2.0](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.2.0) (2019-08-19) ### Features * **connector:** improve type checking for multithreaded use ([5d13917](http://gerrit.corp.arista.io:29418/web-components/commits/5d13917)) ## [0.1.49](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.49) (2019-08-14) **Note:** Version bump only for package a-msgpack ## [0.1.48](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.48) (2019-08-13) **Note:** Version bump only for package a-msgpack ## [0.1.47](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.47) (2019-08-12) **Note:** Version bump only for package a-msgpack ## [0.1.46](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.46) (2019-07-26) **Note:** Version bump only for package a-msgpack ## [0.1.45](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.45) (2019-07-26) **Note:** Version bump only for package a-msgpack ## [0.1.44](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.44) (2019-07-25) **Note:** Version bump only for package a-msgpack ## [0.1.43](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.43) (2019-07-16) **Note:** Version bump only for package a-msgpack ## [0.1.42](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.42) (2019-07-16) **Note:** Version bump only for package a-msgpack ## [0.1.41](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.41) (2019-07-12) **Note:** Version bump only for package a-msgpack ## [0.1.40](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.40) (2019-07-02) **Note:** Version bump only for package a-msgpack ## [0.1.39](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.39) (2019-07-01) **Note:** Version bump only for package a-msgpack ## [0.1.38](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.38) (2019-07-01) **Note:** Version bump only for package a-msgpack ## [0.1.37](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.37) (2019-06-28) **Note:** Version bump only for package a-msgpack ## [0.1.36](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.36) (2019-06-27) **Note:** Version bump only for package a-msgpack ## [0.1.35](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.35) (2019-06-11) **Note:** Version bump only for package a-msgpack ## [0.1.34](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.34) (2019-06-03) **Note:** Version bump only for package a-msgpack ## [0.1.33](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.33) (2019-05-28) **Note:** Version bump only for package a-msgpack ## [0.1.32](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.32) (2019-05-17) **Note:** Version bump only for package a-msgpack ## [0.1.31](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.31) (2019-05-14) **Note:** Version bump only for package a-msgpack ## [0.1.30](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.30) (2019-05-14) **Note:** Version bump only for package a-msgpack ## [0.1.29](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.29) (2019-05-13) **Note:** Version bump only for package a-msgpack ## [0.1.28](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.28) (2019-05-13) **Note:** Version bump only for package a-msgpack ## [0.1.27](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.27) (2019-05-06) **Note:** Version bump only for package a-msgpack ## [0.1.26](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.26) (2019-04-29) **Note:** Version bump only for package a-msgpack ## [0.1.25](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.25) (2019-04-22) **Note:** Version bump only for package a-msgpack ## [0.1.24](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.24) (2019-04-16) **Note:** Version bump only for package a-msgpack ## [0.1.23](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.23) (2019-04-11) ### Bug Fixes * **a-msgpack:** advance the buffer offset when decoding int64 ([027afa6](http://gerrit.corp.arista.io:29418/web-components/commits/027afa6)) ## [0.1.22](http://gerrit.corp.arista.io:29418/web-components/compare/[email protected]@0.1.22) (2019-04-08) **Note:** Version bump only for package a-msgpack ## [0.1.21](http://gerrit:29418/web-components/compare/[email protected]@0.1.21) (2019-04-01) **Note:** Version bump only for package a-msgpack ## [0.1.20](http://gerrit:29418/web-components/compare/[email protected]@0.1.20) (2019-03-25) **Note:** Version bump only for package a-msgpack ## [0.1.19](http://gerrit:29418/web-components/compare/[email protected]@0.1.19) (2019-03-19) **Note:** Version bump only for package a-msgpack ## [0.1.18](http://gerrit:29418/web-components/compare/[email protected]@0.1.18) (2019-03-18) **Note:** Version bump only for package a-msgpack ## [0.1.17](http://gerrit:29418/web-components/compare/[email protected]@0.1.17) (2019-03-18) **Note:** Version bump only for package a-msgpack ## [0.1.16](http://gerrit:29418/web-components/compare/[email protected]@0.1.16) (2019-03-13) **Note:** Version bump only for package a-msgpack ## [0.1.15](http://gerrit:29418/web-components/compare/[email protected]@0.1.15) (2019-03-07) **Note:** Version bump only for package a-msgpack ## [0.1.14](http://gerrit:29418/web-components/compare/[email protected]@0.1.14) (2019-03-04) **Note:** Version bump only for package a-msgpack ## [0.1.13](http://gerrit:29418/web-components/compare/[email protected]@0.1.13) (2019-02-23) **Note:** Version bump only for package a-msgpack ## [0.1.12](http://gerrit:29418/web-components/compare/[email protected]@0.1.12) (2019-02-19) **Note:** Version bump only for package a-msgpack ## [0.1.11](http://gerrit:29418/web-components/compare/[email protected]@0.1.11) (2019-02-15) **Note:** Version bump only for package a-msgpack ## [0.1.10](http://gerrit:29418/web-components/compare/[email protected]@0.1.10) (2019-02-12) **Note:** Version bump only for package a-msgpack ## [0.1.9](http://gerrit:29418/web-components/compare/[email protected]@0.1.9) (2019-02-11) **Note:** Version bump only for package a-msgpack ## [0.1.8](http://gerrit:29418/web-components/compare/[email protected]@0.1.8) (2019-02-07) **Note:** Version bump only for package a-msgpack ## [0.1.7](http://gerrit:29418/web-components/compare/[email protected]@0.1.7) (2019-02-04) **Note:** Version bump only for package a-msgpack ## [0.1.6](http://gerrit:29418/web-components/compare/[email protected]@0.1.6) (2019-02-04) **Note:** Version bump only for package a-msgpack ## [0.1.5](http://gerrit:29418/web-components/compare/[email protected]@0.1.5) (2019-01-29) **Note:** Version bump only for package a-msgpack ## [0.1.4](http://gerrit:29418/web-components/compare/[email protected]@0.1.4) (2019-01-28) ### Bug Fixes * **eslint-config-arista:** use `quote-props` ([2259c7e](http://gerrit:29418/web-components/commits/2259c7e)) ## [0.1.3](http://gerrit:29418/web-components/compare/[email protected]@0.1.3) (2019-01-28) **Note:** Version bump only for package a-msgpack ## [0.1.2](http://gerrit:29418/web-components/compare/[email protected]@0.1.2) (2019-01-21) **Note:** Version bump only for package a-msgpack ## [0.1.1](http://gerrit:29418/web-components/compare/[email protected]@0.1.1) (2019-01-14) **Note:** Version bump only for package a-msgpack # 0.1.0 (2019-01-14) ### Features * **a-msgpack:** Add MessagePack libaray for JS ([25b844a](http://gerrit:29418/web-components/commits/25b844a)) <file_sep>// Copyright (c) 2018, Arista Networks, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import { toBinaryKey } from '../src'; import { DEFAULT_CONTEXT, GET } from '../src/constants'; import Emitter from '../src/emitter'; import { EventCallback, RequestContext } from '../types'; describe('Emitter', () => { const requestContext: RequestContext = { command: GET, token: '<PASSWORD>', encodedParams: toBinaryKey('Dodgers'), }; test('should remove itself from callback during emit', () => { const emitter = new Emitter(); const event = 'test'; const data = 'lol'; const fakeCallback1 = jest.fn(); const fakeCallback2 = jest.fn(); const fakeCallbackInner = jest.fn(); const callbackWithUnbind: EventCallback = (_rq, d) => { emitter.unbind(event, callbackWithUnbind); fakeCallbackInner(d); }; emitter.bind(event, requestContext, fakeCallback1); emitter.bind(event, requestContext, callbackWithUnbind); emitter.bind(event, requestContext, fakeCallback2); expect(emitter.getEventsMap().get(event)).toHaveLength(3); emitter.emit(event, data); expect(fakeCallback1).toHaveBeenCalledWith(requestContext, data); expect(fakeCallbackInner).toHaveBeenCalledWith(data); expect(fakeCallback2).toHaveBeenCalledWith(requestContext, data); expect(emitter.getEventsMap().get(event)).toHaveLength(2); expect(emitter.getEventsMap().get(event)).toContain(fakeCallback1); expect(emitter.getEventsMap().get(event)).toContain(fakeCallback2); expect(emitter.getEventsMap().get(event)).not.toContain(callbackWithUnbind); }); test('should delete the event and request entry, if there is only one', () => { const emitter = new Emitter(); const event = 'test'; const data = 'lol'; const fakeCallbackInner = jest.fn(); const callbackWithUnbind: EventCallback = (_rq, d) => { emitter.unbind(event, callbackWithUnbind); fakeCallbackInner(d); }; emitter.bind(event, requestContext, callbackWithUnbind); expect(emitter.getEventsMap().get(event)).toHaveLength(1); expect(emitter.getRequestContextMap().get(event)).toEqual(requestContext); emitter.emit(event, data); expect(fakeCallbackInner).toHaveBeenCalledWith(data); expect(emitter.getEventsMap().get(event)).toBe(undefined); expect(emitter.getRequestContextMap().get(event)).toBe(undefined); }); test('should not unbind if callack or remove request data is not present', () => { const emitter = new Emitter(); const event = 'test'; const fakeCallback = jest.fn(); const fakeCallback2 = jest.fn(); emitter.bind(event, requestContext, fakeCallback); emitter.unbind(event, fakeCallback2); expect(emitter.getEventsMap().get(event)).toHaveLength(1); expect(emitter.getRequestContextMap().get(event)).toEqual(requestContext); }); test('should not unbind if event type or remove request data is not present', () => { const emitter = new Emitter(); const event = 'test'; const fakeCallback = jest.fn(); emitter.bind(event, requestContext, fakeCallback); emitter.unbind('test2', fakeCallback); expect(emitter.getEventsMap().get(event)).toHaveLength(1); expect(emitter.getRequestContextMap().get(event)).toEqual(requestContext); }); test('should unbind if callack is present and remove request data', () => { const emitter = new Emitter(); const event = 'test'; const fakeCallback = jest.fn(); emitter.bind(event, requestContext, fakeCallback); emitter.unbind(event, fakeCallback); expect(emitter.getEventsMap().get(event)).toBe(undefined); expect(emitter.getRequestContextMap().get(event)).toBe(undefined); }); test('should unbind if callack is present and but not remove shared request data', () => { const emitter = new Emitter(); const event = 'test'; const fakeCallback = jest.fn(); const fakeCallback2 = jest.fn(); emitter.bind(event, requestContext, fakeCallback); emitter.bind(event, requestContext, fakeCallback2); expect(emitter.getEventsMap().get(event)).toHaveLength(2); emitter.unbind(event, fakeCallback); expect(emitter.getEventsMap().get(event)).toHaveLength(1); expect(emitter.getRequestContextMap().get(event)).toEqual(requestContext); }); test('`getRequestContextMap` should return request context', () => { const emitter = new Emitter(); const event = 'test'; const event2 = 'test2'; const fakeCallbackInner = jest.fn(); const fakeCallback1 = jest.fn(); const callbackWithUnbind: EventCallback = (_rq, d) => { emitter.unbind(event, callbackWithUnbind); fakeCallbackInner(d); }; emitter.bind(event, requestContext, callbackWithUnbind); emitter.bind(event2, requestContext, fakeCallback1); // @ts-expect-error Accessing private attribute for easier testing expect(emitter.events.size).toBe(2); expect(emitter.getRequestContextMap().size).toBe(2); }); test('`getEventsMap` should return events', () => { const emitter = new Emitter(); const event = 'test'; const event2 = 'test2'; const fakeCallbackInner = jest.fn(); const fakeCallback1 = jest.fn(); const callbackWithUnbind: EventCallback = (_rq, d) => { emitter.unbind(event, callbackWithUnbind); fakeCallbackInner(d); }; emitter.bind(event, requestContext, callbackWithUnbind); emitter.bind(event2, requestContext, fakeCallback1); // @ts-expect-error Accessing private attribute for easier testing expect(emitter.events.size).toBe(2); expect(emitter.getEventsMap().size).toBe(2); }); test('should clear all events and request data for eventType on `unbindAll`', () => { const emitter = new Emitter(); const event = 'test'; const event2 = 'test2'; const fakeCallbackInner = jest.fn(); const fakeCallback1 = jest.fn(); const fakeCallback2 = jest.fn(); const callbackWithUnbind: EventCallback = (_rq, d) => { emitter.unbind(event, callbackWithUnbind); fakeCallbackInner(d); }; emitter.bind(event, requestContext, callbackWithUnbind); emitter.bind(event, requestContext, fakeCallback2); emitter.bind(event2, requestContext, fakeCallback1); expect(emitter.getEventsMap().get(event)).toHaveLength(2); expect(emitter.getEventsMap().size).toBe(2); expect(emitter.getRequestContextMap().get(event)).toEqual(requestContext); emitter.unbindAll(event); expect(emitter.getEventsMap().get(event)).toBe(undefined); expect(emitter.getEventsMap().size).toBe(1); expect(emitter.getRequestContextMap().get(event)).toBe(undefined); }); test('should not emit eventType if no callbacks present', () => { const emitter = new Emitter(); const event = 'test'; const fakeCallback1 = jest.fn(); emitter.bind(event, requestContext, fakeCallback1); emitter.emit('test1'); expect(fakeCallback1).not.toHaveBeenCalled(); }); test('should include request context in emit', () => { const emitter = new Emitter(); const event = 'test'; const otherArg = 'something'; const fakeCallback = jest.fn(); const fakeCallback1 = jest.fn(); emitter.bind(event, requestContext, fakeCallback); emitter.bind(event, requestContext, fakeCallback1); emitter.emit(event, otherArg); expect(fakeCallback).toHaveBeenCalledWith(requestContext, otherArg); emitter.emit(event); expect(fakeCallback).toHaveBeenCalledWith(requestContext); }); test('should include default request context in emit, if none is found', () => { const emitter = new Emitter(); const event = 'test'; const otherArg = 'something'; const fakeCallback = jest.fn(); const fakeCallback1 = jest.fn(); // @ts-expect-error setup for callback that is missing request context emitter.bind(event, undefined, fakeCallback); // @ts-expect-error setup for callback that is missing request context emitter.bind(event, undefined, fakeCallback1); emitter.emit(event, otherArg); expect(fakeCallback).toHaveBeenCalledWith(DEFAULT_CONTEXT, otherArg); emitter.emit(event); expect(fakeCallback).toHaveBeenCalledWith(DEFAULT_CONTEXT); }); test('should clear events `Map` on close', () => { const emitter = new Emitter(); const event = 'test'; const fakeCallback1 = jest.fn(); emitter.bind(event, requestContext, fakeCallback1); emitter.close(); expect(emitter.getEventsMap().get(event)).toBe(undefined); expect(emitter.getEventsMap().size).toBe(0); }); test('should clear requestContext `Map` on close', () => { const emitter = new Emitter(); const event = 'test'; const fakeCallback1 = jest.fn(); emitter.bind(event, requestContext, fakeCallback1); emitter.close(); expect(emitter.getRequestContextMap().get(event)).toBe(undefined); }); test('should return true if `has` is called with a callback present in the emitter', () => { const emitter = new Emitter(); const event = 'test'; const fakeCallback1 = jest.fn(); emitter.bind(event, requestContext, fakeCallback1); expect(emitter.has(event)).toBe(true); }); test('should return false if `has` is called without a callback present in the emitter', () => { const emitter = new Emitter(); const event = 'test'; expect(emitter.has(event)).toBe(false); const fakeCallback1 = jest.fn(); emitter.bind(event, requestContext, fakeCallback1); emitter.close(); expect(emitter.has(event)).toBe(false); }); }); <file_sep>/* eslint-disable no-labels, no-extra-label */ import { fromByteArray } from 'base64-js'; import JSBI from 'jsbi'; import { CachedKeyDecoder } from './CachedKeyDecoder'; import { ExtensionCodec, ExtensionCodecType } from './ExtensionCodec'; import { getInt64, getUint64 } from './utils/int'; import { prettyByte } from './utils/prettyByte'; import { createDataView, ensureUint8Array } from './utils/typedArrays'; import { utf8DecodeJs, TEXT_ENCODING_AVAILABLE, TEXT_DECODER_THRESHOLD, utf8DecodeTD, } from './utils/utf8'; const enum State { ARRAY, MAP_KEY, MAP_VALUE, } type MapKeyType = unknown; const isValidMapKeyType = (key: unknown): key is MapKeyType => { const keyType = typeof key; return keyType === 'string'; }; type StackMapState = { type: State.MAP_KEY | State.MAP_VALUE; size: number; key: MapKeyType | null; keyStart: number; keyEnd: number; serializedKey: string | null; readCount: number; map: Record<string, unknown>; }; type StackArrayState = { type: State.ARRAY; size: number; keyStart: number; array: unknown[]; position: number; }; type StackState = StackArrayState | StackMapState; const EMPTY_VIEW = new DataView(new ArrayBuffer(0)); const EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer); const DEFAULT_MAX_LENGTH = 0xffff_ffff; // uint32_max const sharedCachedKeyDecoder = new CachedKeyDecoder(); export class Decoder { totalPos = 0; pos = 0; view = EMPTY_VIEW; bytes = EMPTY_BYTES; readonly stack: StackState[] = []; readonly maxStrLength: number; readonly maxBinLength: number; readonly maxArrayLength: number; readonly maxMapLength: number; readonly maxExtLength: number; readonly extensionCodec: ExtensionCodecType; readonly cachedKeyDecoder: CachedKeyDecoder | null; readonly useJSBI: boolean; constructor( extensionCodec = ExtensionCodec.defaultCodec, useJSBI = false, maxStrLength = DEFAULT_MAX_LENGTH, maxBinLength = DEFAULT_MAX_LENGTH, maxArrayLength = DEFAULT_MAX_LENGTH, maxMapLength = DEFAULT_MAX_LENGTH, maxExtLength = DEFAULT_MAX_LENGTH, cachedKeyDecoder: CachedKeyDecoder | null = sharedCachedKeyDecoder, ) { this.extensionCodec = extensionCodec; this.cachedKeyDecoder = cachedKeyDecoder; this.useJSBI = useJSBI; this.maxStrLength = maxStrLength; this.maxBinLength = maxBinLength; this.maxArrayLength = maxArrayLength; this.maxMapLength = maxMapLength; this.maxExtLength = maxExtLength; } setBuffer(buffer: ArrayLike<number> | ArrayBuffer): void { this.bytes = ensureUint8Array(buffer); this.view = createDataView(this.bytes); this.pos = 0; } hasRemaining(size = 1): boolean { return this.view.byteLength - this.pos >= size; } createNoExtraBytesError(posToShow: number): Error { const { view, pos } = this; return new RangeError(`Extra ${view.byteLength - pos} byte(s) found at buffer[${posToShow}]`); } decodeSingleSync(): unknown { const object = this.decodeSync(); if (this.hasRemaining()) { throw this.createNoExtraBytesError(this.pos); } return object; } decodeSync(): unknown { // eslint-disable-next-line no-constant-condition DECODE: while (true) { const headByte = this.readU8(); let object: unknown; if (headByte >= 0xe0) { // negative fixint (111x xxxx) 0xe0 - 0xff object = headByte - 0x100; } else if (headByte < 0xc0) { if (headByte < 0x80) { // positive fixint (0xxx xxxx) 0x00 - 0x7f object = headByte; } else if (headByte < 0x90) { // fixmap (1000 xxxx) 0x80 - 0x8f const size = headByte - 0x80; if (size !== 0) { this.pushMapState(size); continue DECODE; } else { object = {}; } } else { // fixarray (1001 xxxx) 0x90 - 0x9f const size = headByte - 0x90; if (size !== 0) { this.pushArrayState(size); continue DECODE; } else { object = []; } } } else if (headByte === 0xc0) { // nil object = null; } else if (headByte === 0xc2) { // false object = false; } else if (headByte === 0xc3) { // true object = true; } else if (headByte === 0xca) { // float 32 object = this.readF32(); } else if (headByte === 0xcb) { // float 64 object = this.readF64(); } else if (headByte === 0xcc) { // uint 8 object = this.readU8(); } else if (headByte === 0xcd) { // uint 16 object = this.readU16(); } else if (headByte === 0xce) { // uint 32 object = this.readU32(); } else if (headByte === 0xcf) { // uint 64 object = this.readU64(); } else if (headByte === 0xd0) { // int 8 object = this.readI8(); } else if (headByte === 0xd1) { // int 16 object = this.readI16(); } else if (headByte === 0xd2) { // int 32 object = this.readI32(); } else if (headByte === 0xd3) { // int 64 object = this.readI64(); } else if (headByte === 0xdc) { // array 16 const size = this.readU16(); this.pushArrayState(size); continue DECODE; } else if (headByte === 0xdd) { // array 32 const size = this.readU32(); this.pushArrayState(size); continue DECODE; } else if (headByte === 0xde) { // map 16 const size = this.readU16(); this.pushMapState(size); continue DECODE; } else if (headByte === 0xdf) { // map 32 const size = this.readU32(); this.pushMapState(size); continue DECODE; } else if (headByte === 0xc4) { // bin 8 const size = this.lookU8(); object = this.decodeUtf8String(size, 1); } else if (headByte === 0xc5) { // bin 16 const size = this.lookU16(); object = this.decodeUtf8String(size, 2); } else if (headByte === 0xc6) { // bin 32 const size = this.lookU32(); object = this.decodeUtf8String(size, 4); } else if (headByte === 0xd4) { // fixext 1 object = this.decodeExtension(1, 0); } else if (headByte === 0xd5) { // fixext 2 object = this.decodeExtension(2, 0); } else if (headByte === 0xd6) { // fixext 4 object = this.decodeExtension(4, 0); } else if (headByte === 0xd7) { // fixext 8 object = this.decodeExtension(8, 0); } else if (headByte === 0xd8) { // fixext 16 object = this.decodeExtension(16, 0); } else if (headByte === 0xc7) { // ext 8 const size = this.lookU8(); object = this.decodeExtension(size, 1); } else if (headByte === 0xc8) { // ext 16 const size = this.lookU16(); object = this.decodeExtension(size, 2); } else if (headByte === 0xc9) { // ext 32 const size = this.lookU32(); object = this.decodeExtension(size, 4); } else { throw new Error(`Unrecognized type byte: ${prettyByte(headByte)}`); } const stack = this.stack; while (stack.length > 0) { // arrays and maps const state = stack[stack.length - 1]; if (state.type === State.ARRAY) { state.array[state.position] = object; state.position++; if (state.position === state.size) { stack.pop(); object = state.array; } else { continue DECODE; } } else if (state.type === State.MAP_KEY) { // Map key state.keyEnd = this.pos; state.key = object; state.type = State.MAP_VALUE; continue DECODE; } else { // Map value if (!isValidMapKeyType(state.key)) { const serializedKey = fromByteArray(this.bytes.slice(state.keyStart, state.keyEnd)); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion state.map[serializedKey!] = { _key: state.key, _value: object }; } else { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion state.map[state.key! as string] = object; } state.readCount++; if (state.readCount === state.size) { // This is the last value, end of map stack.pop(); object = state.map; } else { state.key = null; state.type = State.MAP_KEY; stack[stack.length - 1].keyStart = this.pos; continue DECODE; } } } return object; } } pushMapState(size: number): void { if (size > this.maxMapLength) { throw new Error( `Max length exceeded: map length (${size}) > maxMapLengthLength (${this.maxMapLength})`, ); } this.stack.push({ type: State.MAP_KEY, size, keyStart: this.pos, keyEnd: this.pos, key: null, serializedKey: null, readCount: 0, map: {}, }); } pushArrayState(size: number): void { if (size > this.maxArrayLength) { throw new Error( `Max length exceeded: array length (${size}) > maxArrayLength (${this.maxArrayLength})`, ); } this.stack.push({ type: State.ARRAY, size, keyStart: 1, array: new Array<unknown>(size), position: 0, }); } decodeUtf8String(byteLength: number, headerOffset: number): string { if (byteLength > this.maxStrLength) { throw new Error( 'Max length exceeded: ' + `UTF-8 byte length (${byteLength}) > maxStrLength (${this.maxStrLength})`, ); } if (this.bytes.byteLength < this.pos + headerOffset + byteLength) { throw new RangeError('Insufficient data'); } const offset = this.pos + headerOffset; let object: string; if (this.stateIsMapKey() && this.cachedKeyDecoder?.canBeCached(byteLength)) { object = this.cachedKeyDecoder.decode(this.bytes, offset, byteLength); } else if (TEXT_ENCODING_AVAILABLE && byteLength > TEXT_DECODER_THRESHOLD) { object = utf8DecodeTD(this.bytes, offset, byteLength); } else { object = utf8DecodeJs(this.bytes, offset, byteLength); } this.pos += headerOffset + byteLength; return object; } stateIsMapKey(): boolean { if (this.stack.length > 0) { const state = this.stack[this.stack.length - 1]; return state.type === State.MAP_KEY; } return false; } decodeBinary(byteLength: number, headOffset: number): Uint8Array { if (byteLength > this.maxBinLength) { throw new Error( `Max length exceeded: bin length (${byteLength}) > maxBinLength (${this.maxBinLength})`, ); } if (!this.hasRemaining(byteLength + headOffset)) { throw new RangeError('Insufficient data'); } const offset = this.pos + headOffset; const object = this.bytes.subarray(offset, offset + byteLength); this.pos += headOffset + byteLength; return object; } decodeExtension(size: number, headOffset: number): unknown { if (size > this.maxExtLength) { throw new Error( `Max length exceeded: ext length (${size}) > maxExtLength (${this.maxExtLength})`, ); } const extType = this.view.getInt8(this.pos + headOffset); const data = this.decodeBinary(size, headOffset + 1 /* extType */); return this.extensionCodec.decode(data, extType); } lookU8(): number { return this.view.getUint8(this.pos); } lookU16(): number { return this.view.getUint16(this.pos); } lookU32(): number { return this.view.getUint32(this.pos); } readU8(): number { const value = this.view.getUint8(this.pos); this.pos++; return value; } readI8(): number { const value = this.view.getInt8(this.pos); this.pos++; return value; } readU16(): number { const value = this.view.getUint16(this.pos); this.pos += 2; return value; } readI16(): number { const value = this.view.getInt16(this.pos); this.pos += 2; return value; } readU32(): number { const value = this.view.getUint32(this.pos); this.pos += 4; return value; } readI32(): number { const value = this.view.getInt32(this.pos); this.pos += 4; return value; } readU64(): bigint | JSBI { const value = getUint64(this.view, this.pos, this.useJSBI); this.pos += 8; return value; } readI64(): bigint | JSBI { const value = getInt64(this.view, this.pos, this.useJSBI); this.pos += 8; return value; } readF32(): number { const value = this.view.getFloat32(this.pos); this.pos += 4; return value; } readF64(): number { const value = this.view.getFloat64(this.pos); this.pos += 8; return value; } } <file_sep>import JSBI from 'jsbi'; import { BasicNeatType } from '../types/neat'; import { ExtData } from './ExtData'; import { ExtensionCodec, ExtensionCodecType } from './ExtensionCodec'; import { isBasicNeatType, isBool, isFloat32, isFloat64, isInt, isStr, sortMapByKey, } from './neat/utils'; import { isJsbi, isPlainObject } from './utils/data'; import { setInt64, setUint64 } from './utils/int'; import { ensureUint8Array } from './utils/typedArrays'; import { utf8EncodeJs, utf8Count, TEXT_ENCODING_AVAILABLE, TEXT_ENCODER_THRESHOLD, utf8EncodeTE, } from './utils/utf8'; export const DEFAULT_MAX_DEPTH = 100; export const DEFAULT_INITIAL_BUFFER_SIZE = 2048; export class Encoder { private pos = 0; private view: DataView; private bytes: Uint8Array; readonly extensionCodec: ExtensionCodecType; readonly maxDepth: number; readonly initialBufferSize: number; constructor( extensionCodec = ExtensionCodec.defaultCodec, maxDepth = DEFAULT_MAX_DEPTH, initialBufferSize = DEFAULT_INITIAL_BUFFER_SIZE, ) { this.extensionCodec = extensionCodec; this.maxDepth = maxDepth; this.initialBufferSize = initialBufferSize; this.view = new DataView(new ArrayBuffer(this.initialBufferSize)); this.bytes = new Uint8Array(this.view.buffer); } keyEncoder(value: unknown, depth: number): Uint8Array { const encoder = new Encoder(this.extensionCodec, this.maxDepth, this.initialBufferSize); encoder.encode(value, depth); return encoder.getUint8Array(); } encode(object: unknown, depth: number): void { if (depth > this.maxDepth) { throw new Error(`Too deep objects in depth ${depth}`); } if (object == null) { this.encodeNil(); } else if (typeof object === 'boolean') { this.encodeBoolean(object); } else if (typeof object === 'number') { this.encodeNumber(object); } else if (typeof object === 'string') { this.encodeString(object); } else { this.encodeObject(object, depth); } } getUint8Array(): Uint8Array { return this.bytes.subarray(0, this.pos); } ensureBufferSizeToWrite(sizeToWrite: number): void { const requiredSize = this.pos + sizeToWrite; if (this.view.byteLength < requiredSize) { this.resizeBuffer(requiredSize * 2); } } resizeBuffer(newSize: number): void { const newBuffer = new ArrayBuffer(newSize); const newBytes = new Uint8Array(newBuffer); const newView = new DataView(newBuffer); newBytes.set(this.bytes); this.view = newView; this.bytes = newBytes; } encodeNil(): void { this.writeU8(0xc0); } encodeBoolean(object: boolean): void { if (object === false) { this.writeU8(0xc2); } else { this.writeU8(0xc3); } } encodeNumber(object: number): void { if (Number.isSafeInteger(object)) { if (object >= 0) { if (object < 0x80) { // positive fixint this.writeU8(object); } else if (object < 0x100) { // uint 8 this.writeU8(0xcc); this.writeU8(object); } else if (object < 0x10000) { // uint 16 this.writeU8(0xcd); this.writeU16(object); } else if (object < 0x100000000) { // uint 32 this.writeU8(0xce); this.writeU32(object); } else { // uint 64 this.writeU8(0xcf); this.writeU64(object); } } else if (object >= -0x20) { // negative fixint this.writeU8(0xe0 | (object + 0x20)); } else if (object >= -0x80) { // int 8 this.writeU8(0xd0); this.writeI8(object); } else if (object >= -0x8000) { // int 16 this.writeU8(0xd1); this.writeI16(object); } else if (object >= -0x80000000) { // int 32 this.writeU8(0xd2); this.writeI32(object); } else { // int 64 this.writeU8(0xd3); this.writeI64(object); } } else { // non-integer numbers // float 64 this.writeU8(0xcb); this.writeF64(object); } } writeStringHeader(size: number): void { if (size < 0x100) { // bin 8 this.writeU8(0xc4); this.writeU8(size); } else if (size < 0x10000) { // bin 16 this.writeU8(0xc5); this.writeU16(size); } else { // bin 32 this.writeU8(0xc6); this.writeU32(size); } } encodeString(object: string): void { const maxHeaderSize = 1 + 4; const strLength = object.length; if (TEXT_ENCODING_AVAILABLE && strLength > TEXT_ENCODER_THRESHOLD) { const byteLength = utf8Count(object); this.ensureBufferSizeToWrite(maxHeaderSize + byteLength); this.writeStringHeader(byteLength); utf8EncodeTE(object, this.bytes, this.pos); this.pos += byteLength; } else { const byteLength = utf8Count(object); this.ensureBufferSizeToWrite(maxHeaderSize + byteLength); this.writeStringHeader(byteLength); utf8EncodeJs(object, this.bytes, this.pos); this.pos += byteLength; } } encodeObject(object: unknown, depth: number): void { if (Array.isArray(object)) { if (isJsbi(object)) { this.encodeJSBI(object as JSBI); } else { this.encodeArray(object, depth); } } else if (ArrayBuffer.isView(object)) { this.encodeBinary(object); } else if (typeof object === 'bigint') { this.encodeBigInt(object as bigint); } else if (object instanceof Map) { this.encodeMap(object, depth); } else if (typeof object === 'object') { if (isBasicNeatType(object)) { this.encodeNeatClass(object); } else if (isPlainObject(object as object)) { // Find out if it is a plain object this.encodePlainObject(object as Record<string, unknown>, depth); } else { // Otherwise try to encode objects with custom codec of non-primitives this.encodeExtension(this.extensionCodec.encode(object)); } } else if (typeof object === 'function') { this.encodeNil(); } else { // symbol, function and other special object come here unless extensionCodec handles them. throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(object)}`); } } encodeNeatClass(value: BasicNeatType): void { if (isFloat32(value)) { // float 32 -- 0xca this.writeU8(0xca); this.writeF32(value.value); } else if (isFloat64(value)) { // float 64 -- 0xcb this.writeU8(0xcb); this.writeF64(value.value); } else if (isInt(value)) { // int if (typeof value.value === 'bigint') { this.encodeBigInt(value.value); } else if (isJsbi(value.value)) { this.encodeJSBI(value.value as JSBI); } else { this.encodeNumber(value.value as number); } } else if (isStr(value)) { // string this.encodeString(value.value); } else if (isBool(value)) { // bool this.encodeBoolean(value.value); } else { // nil this.encodeNil(); } } encodeBigInt(value: bigint): void { // uint 64 -- 0xcf // int 64 -- 0xd3 if ( value === BigInt(0) || BigInt.asIntN(32, value) > 0 || (value < 0 && BigInt.asUintN(32, value) === value * BigInt(-1)) ) { this.encodeNumber(Number(value)); } else if (value < 0) { this.writeU8(0xd3); this.writeI64(value); } else if (value < 0x100000000) { this.writeU8(0xce); this.writeU32(Number(value)) } else { this.writeU8(0xcf); this.writeU64(value); } } encodeJSBI(value: JSBI): void { const strValue = value.toString(); if ( strValue === '0' || (JSBI.LE(value, 0x7fffffff) && JSBI.GE(value, -0xffffffff)) || (strValue < '0' && JSBI.GE(value, -0xffffffff)) ) { this.encodeNumber(JSBI.toNumber(value)); } else if (strValue < '0') { this.writeU8(0xd3); this.writeI64(strValue); } else if (JSBI.LE(value, 0xffffffff)) { this.writeU8(0xce); this.writeU32(JSBI.toNumber(value)); } else { this.writeU8(0xcf); this.writeU64(strValue); } } encodeBinary(object: ArrayBufferView): void { const size = object.byteLength; if (size < 0x100) { // bin 8 this.writeU8(0xc4); this.writeU8(size); } else if (size < 0x10000) { // bin 16 this.writeU8(0xc5); this.writeU16(size); } else { // bin 32 this.writeU8(0xc6); this.writeU32(size); } const bytes = ensureUint8Array(object); this.writeU8a(bytes); } encodeArray(object: unknown[], depth: number): void { const size = object.length; if (size < 16) { // fixarray this.writeU8(0x90 + size); } else if (size < 0x10000) { // array 16 this.writeU8(0xdc); this.writeU16(size); } else { // array 32 this.writeU8(0xdd); this.writeU32(size); } for (const item of object) { this.encode(item, depth + 1); } } encodeMap(object: Map<unknown, unknown>, depth: number): void { const size = object.size; const sortedMap: [Uint8Array, unknown][] = []; if (size < 16) { // fixmap this.writeU8(0x80 + size); } else if (size < 0x10000) { // map 16 this.writeU8(0xde); this.writeU16(size); } else { // map 32 this.writeU8(0xdf); this.writeU32(size); } object.forEach((value, key): void => { const encodedKey: Uint8Array = this.keyEncoder(key, depth + 1); sortedMap.push([encodedKey, value]); }); sortedMap.sort(sortMapByKey); sortedMap.forEach((keyVal): void => { this.writeU8a(keyVal[0]); this.encode(keyVal[1], depth + 1); }); } encodePlainObject(object: Record<string, unknown>, depth: number): void { this.encodeMap(new Map(Object.entries(object)), depth); } encodeExtension(ext: ExtData): void { const size = ext.data.length; if (size === 1) { // fixext 1 this.writeU8(0xd4); } else if (size === 2) { // fixext 2 this.writeU8(0xd5); } else if (size === 4) { // fixext 4 this.writeU8(0xd6); } else if (size === 8) { // fixext 8 this.writeU8(0xd7); } else if (size === 16) { // fixext 16 this.writeU8(0xd8); } else if (size < 0x100) { // ext 8 this.writeU8(0xc7); this.writeU8(size); } else if (size < 0x10000) { // ext 16 this.writeU8(0xc8); this.writeU16(size); } else { // ext 32 this.writeU8(0xc9); this.writeU32(size); } this.writeI8(ext.type); this.writeU8a(ext.data); } writeU8(value: number): void { this.ensureBufferSizeToWrite(1); this.view.setUint8(this.pos, value); this.pos++; } writeU8a(values: ArrayLike<number>): void { const size = values.length; this.ensureBufferSizeToWrite(size); this.bytes.set(values, this.pos); this.pos += size; } writeI8(value: number): void { this.ensureBufferSizeToWrite(1); this.view.setInt8(this.pos, value); this.pos++; } writeU16(value: number): void { this.ensureBufferSizeToWrite(2); this.view.setUint16(this.pos, value); this.pos += 2; } writeI16(value: number): void { this.ensureBufferSizeToWrite(2); this.view.setInt16(this.pos, value); this.pos += 2; } writeU32(value: number): void { this.ensureBufferSizeToWrite(4); this.view.setUint32(this.pos, value); this.pos += 4; } writeI32(value: number): void { this.ensureBufferSizeToWrite(4); this.view.setInt32(this.pos, value); this.pos += 4; } writeF32(value: number): void { this.ensureBufferSizeToWrite(4); this.view.setFloat32(this.pos, value); this.pos += 4; } writeF64(value: number): void { this.ensureBufferSizeToWrite(8); this.view.setFloat64(this.pos, value); this.pos += 8; } writeU64(value: bigint | string | number): void { this.ensureBufferSizeToWrite(8); setUint64(this.view, this.pos, value); this.pos += 8; } writeI64(value: bigint | string | number): void { this.ensureBufferSizeToWrite(8); setInt64(this.view, this.pos, value); this.pos += 8; } } <file_sep>import type { Operation } from '@generated/arista/subscriptions/subscriptions'; import type { grpc } from '@arista/grpc-web'; import type { RpcOptions } from './grpc'; /** * A GRPC response the represents a response from a streaming resource. */ export interface StreamingResourceResponse extends grpc.ProtobufMessage { type: Operation; } /** * Includes all [grpc invoke options](https://github.com/improbable-eng/grpc-web/blob/master/client/grpc-web/docs/invoke.md#invokerpcoptions) * except for `onMessage`, `onEnd` and `onHeaders` for a resource request. */ export type ResourceRpcOptions< Req extends grpc.ProtobufMessage, Res extends grpc.ProtobufMessage, > = RpcOptions<Req, Res>; <file_sep># Change Log All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. ## [5.0.2](https://github.com/aristanetworks/cloudvision/compare/v5.0.1...v5.0.2) (2023-01-18) ### Bug Fixes * **a-msgpack:** write uint32 when appropriate ([#938](https://github.com/aristanetworks/cloudvision/issues/938)) ([aed30eb](https://github.com/aristanetworks/cloudvision/commit/aed30eb459caef97acbd0d57231587e608cb6af3)) ## [5.0.1](https://github.com/aristanetworks/cloudvision/compare/v5.0.0...v5.0.1) (2022-07-18) **Note:** Version bump only for package root # [5.0.0](https://github.com/aristanetworks/cloudvision/compare/v4.14.0...v5.0.0) (2022-07-11) * chore(deps)!: update dependency jsbi to v4 (#598) ([c0672d9](https://github.com/aristanetworks/cloudvision/commit/c0672d92c0391a75e081246a4cbb25ff2fc3cfca)), closes [#598](https://github.com/aristanetworks/cloudvision/issues/598) ### BREAKING CHANGES * Upgrade to JSBI v4 # [4.14.0](https://github.com/aristanetworks/cloudvision/compare/v4.13.1...v4.14.0) (2022-05-30) ### Features * **grpc-web:** Refactor fromGrpcInvoke ([#786](https://github.com/aristanetworks/cloudvision/issues/786)) ([e8794e2](https://github.com/aristanetworks/cloudvision/commit/e8794e2f2d17d0884aeb695c7c8c1217323ab4a3)) ## [4.13.1](https://github.com/aristanetworks/cloudvision/compare/v4.13.0...v4.13.1) (2022-05-05) ### Bug Fixes * **cloudvision-grpc-web:** Defer requests until an observer is listening ([#785](https://github.com/aristanetworks/cloudvision/issues/785)) ([43e4281](https://github.com/aristanetworks/cloudvision/commit/43e4281b4e21ae74076eac6c8d4e7c9d0f760b24)) # [4.13.0](https://github.com/aristanetworks/cloudvision/compare/v4.12.2...v4.13.0) (2022-04-26) ### Bug Fixes * **cloudvision-grpc-web:** Add a try/catch around request close ([#773](https://github.com/aristanetworks/cloudvision/issues/773)) ([1350e56](https://github.com/aristanetworks/cloudvision/commit/1350e564d384f07440052d86e8d70d3b27137daa)) ### Features * **cloudvision-grpc-web:** Add support to close requests on unsubscribe ([#770](https://github.com/aristanetworks/cloudvision/issues/770)) ([4656263](https://github.com/aristanetworks/cloudvision/commit/46562635baedec15d2fb03c233992ec8e663d2a6)) ## [4.12.2](https://github.com/aristanetworks/cloudvision/compare/v4.12.1...v4.12.2) (2022-04-04) ### Bug Fixes * **timestamps:** Add nanosecond support to timestamps ([#762](https://github.com/aristanetworks/cloudvision/issues/762)) ([93ae5cc](https://github.com/aristanetworks/cloudvision/commit/93ae5ccd3c395bcacf504cfa44181245cba16795)) ## [4.12.1](https://github.com/aristanetworks/cloudvision/compare/v4.12.0...v4.12.1) (2022-03-21) ### Bug Fixes * **timestamps:** Add nanosecond support to timestamps ([#672](https://github.com/aristanetworks/cloudvision/issues/672)) ([9f97468](https://github.com/aristanetworks/cloudvision/commit/9f97468c6cfd7a3156d4ff64d081e4d1b8213537)), closes [#673](https://github.com/aristanetworks/cloudvision/issues/673) [#677](https://github.com/aristanetworks/cloudvision/issues/677) [#675](https://github.com/aristanetworks/cloudvision/issues/675) [#674](https://github.com/aristanetworks/cloudvision/issues/674) [#679](https://github.com/aristanetworks/cloudvision/issues/679) [#678](https://github.com/aristanetworks/cloudvision/issues/678) [#680](https://github.com/aristanetworks/cloudvision/issues/680) [#682](https://github.com/aristanetworks/cloudvision/issues/682) [#681](https://github.com/aristanetworks/cloudvision/issues/681) [#683](https://github.com/aristanetworks/cloudvision/issues/683) [#685](https://github.com/aristanetworks/cloudvision/issues/685) [#684](https://github.com/aristanetworks/cloudvision/issues/684) [#686](https://github.com/aristanetworks/cloudvision/issues/686) [#687](https://github.com/aristanetworks/cloudvision/issues/687) [#688](https://github.com/aristanetworks/cloudvision/issues/688) [#689](https://github.com/aristanetworks/cloudvision/issues/689) [#690](https://github.com/aristanetworks/cloudvision/issues/690) [#692](https://github.com/aristanetworks/cloudvision/issues/692) [#694](https://github.com/aristanetworks/cloudvision/issues/694) [#693](https://github.com/aristanetworks/cloudvision/issues/693) [#691](https://github.com/aristanetworks/cloudvision/issues/691) [#695](https://github.com/aristanetworks/cloudvision/issues/695) [#697](https://github.com/aristanetworks/cloudvision/issues/697) [#696](https://github.com/aristanetworks/cloudvision/issues/696) [#698](https://github.com/aristanetworks/cloudvision/issues/698) [#700](https://github.com/aristanetworks/cloudvision/issues/700) [#701](https://github.com/aristanetworks/cloudvision/issues/701) [#699](https://github.com/aristanetworks/cloudvision/issues/699) [#702](https://github.com/aristanetworks/cloudvision/issues/702) [#703](https://github.com/aristanetworks/cloudvision/issues/703) [#704](https://github.com/aristanetworks/cloudvision/issues/704) [#705](https://github.com/aristanetworks/cloudvision/issues/705) [#706](https://github.com/aristanetworks/cloudvision/issues/706) [#707](https://github.com/aristanetworks/cloudvision/issues/707) [#709](https://github.com/aristanetworks/cloudvision/issues/709) [#710](https://github.com/aristanetworks/cloudvision/issues/710) [#711](https://github.com/aristanetworks/cloudvision/issues/711) [#713](https://github.com/aristanetworks/cloudvision/issues/713) [#712](https://github.com/aristanetworks/cloudvision/issues/712) [#714](https://github.com/aristanetworks/cloudvision/issues/714) [#708](https://github.com/aristanetworks/cloudvision/issues/708) [#715](https://github.com/aristanetworks/cloudvision/issues/715) [#716](https://github.com/aristanetworks/cloudvision/issues/716) [#718](https://github.com/aristanetworks/cloudvision/issues/718) [#719](https://github.com/aristanetworks/cloudvision/issues/719) [#722](https://github.com/aristanetworks/cloudvision/issues/722) [#720](https://github.com/aristanetworks/cloudvision/issues/720) [#723](https://github.com/aristanetworks/cloudvision/issues/723) [#724](https://github.com/aristanetworks/cloudvision/issues/724) [#725](https://github.com/aristanetworks/cloudvision/issues/725) [#726](https://github.com/aristanetworks/cloudvision/issues/726) [#727](https://github.com/aristanetworks/cloudvision/issues/727) [#728](https://github.com/aristanetworks/cloudvision/issues/728) [#730](https://github.com/aristanetworks/cloudvision/issues/730) [#731](https://github.com/aristanetworks/cloudvision/issues/731) [#729](https://github.com/aristanetworks/cloudvision/issues/729) [#732](https://github.com/aristanetworks/cloudvision/issues/732) [#733](https://github.com/aristanetworks/cloudvision/issues/733) [#734](https://github.com/aristanetworks/cloudvision/issues/734) [#735](https://github.com/aristanetworks/cloudvision/issues/735) [#736](https://github.com/aristanetworks/cloudvision/issues/736) [#737](https://github.com/aristanetworks/cloudvision/issues/737) [#738](https://github.com/aristanetworks/cloudvision/issues/738) [#740](https://github.com/aristanetworks/cloudvision/issues/740) [#739](https://github.com/aristanetworks/cloudvision/issues/739) [#741](https://github.com/aristanetworks/cloudvision/issues/741) [#744](https://github.com/aristanetworks/cloudvision/issues/744) [#745](https://github.com/aristanetworks/cloudvision/issues/745) [#746](https://github.com/aristanetworks/cloudvision/issues/746) [#747](https://github.com/aristanetworks/cloudvision/issues/747) [#748](https://github.com/aristanetworks/cloudvision/issues/748) [#749](https://github.com/aristanetworks/cloudvision/issues/749) [#750](https://github.com/aristanetworks/cloudvision/issues/750) [#751](https://github.com/aristanetworks/cloudvision/issues/751) [#752](https://github.com/aristanetworks/cloudvision/issues/752) [#753](https://github.com/aristanetworks/cloudvision/issues/753) [#754](https://github.com/aristanetworks/cloudvision/issues/754) # [4.12.0](https://github.com/aristanetworks/cloudvision/compare/v4.11.0...v4.12.0) (2021-10-05) ### Features * **grpc-web:** Export operators ([#578](https://github.com/aristanetworks/cloudvision/issues/578)) ([218a5de](https://github.com/aristanetworks/cloudvision/commit/218a5deac53a6de73eb01c4649710c7d836fbdc4)) # [4.11.0](https://github.com/aristanetworks/cloudvision/compare/v4.10.1...v4.11.0) (2021-10-04) ### Bug Fixes * **cloudvision-grpc-web:** hanging test in CI ([#563](https://github.com/aristanetworks/cloudvision/issues/563)) ([58a7e66](https://github.com/aristanetworks/cloudvision/commit/58a7e66af159defbec473dfe7ec7b88e262cb308)) * **msgpack:** encode stripped neat objects ([#568](https://github.com/aristanetworks/cloudvision/issues/568)) ([5498236](https://github.com/aristanetworks/cloudvision/commit/5498236baa65756c5f29aad801963877e7905246)) ### Features * **grpc-web:** Refactor package ([#558](https://github.com/aristanetworks/cloudvision/issues/558)) ([eac7fc3](https://github.com/aristanetworks/cloudvision/commit/eac7fc31b8bd6a926090e30e92e555289a377a41)) ## [4.10.1](https://github.com/aristanetworks/cloudvision/compare/v4.10.0...v4.10.1) (2021-09-17) **Note:** Version bump only for package root # [4.10.0](https://github.com/aristanetworks/cloudvision/compare/v4.9.2...v4.10.0) (2021-09-08) ### Features * **cloudvision-grpc-web:** Use Arista fork of protobuf.js ([#541](https://github.com/aristanetworks/cloudvision/issues/541)) ([33d61d4](https://github.com/aristanetworks/cloudvision/commit/33d61d47fb5f7d9a85b829f027391e5b73fb2776)) ## [4.9.2](https://github.com/aristanetworks/cloudvision/compare/v4.9.1...v4.9.2) (2021-08-06) **Note:** Version bump only for package root ## [4.9.1](https://github.com/aristanetworks/cloudvision/compare/v4.9.0...v4.9.1) (2021-07-22) ### Bug Fixes * update packages ([#470](https://github.com/aristanetworks/cloudvision/issues/470)) ([264d1e0](https://github.com/aristanetworks/cloudvision/commit/264d1e04045ec9ae2efeaf1ff87cf4b9339626c5)) # [4.9.0](https://github.com/aristanetworks/cloudvision/compare/v4.8.0...v4.9.0) (2021-06-17) ### Features * **cloudvision-grpc-web:** Use RxJS Observables instead of Wonka + Use ts-proto + Fix alias resolutions ([#457](https://github.com/aristanetworks/cloudvision/issues/457)) ([6f84cf2](https://github.com/aristanetworks/cloudvision/commit/6f84cf2cfe9ef9da6df677bed9ef121feac6fd4f)) # [4.8.0](https://github.com/aristanetworks/cloudvision/compare/v4.7.0...v4.8.0) (2021-05-18) ### Features * **cloudvision-grpc-web:** add grpc-web client ([#407](https://github.com/aristanetworks/cloudvision/issues/407)) ([cc0ee18](https://github.com/aristanetworks/cloudvision/commit/cc0ee180b6d2371e807622fcd85dd81ee4440313)) # [4.7.0](https://github.com/aristanetworks/cloudvision/compare/v4.6.5...v4.7.0) (2021-03-08) ### Features * **connector:** add GET_REGIONS_AND_CLUSTERS method ([#366](https://github.com/aristanetworks/cloudvision/issues/366)) ([c26369c](https://github.com/aristanetworks/cloudvision/commit/c26369c536d5910ecc772e1f2f7a7db1132cf227)) ## [4.6.5](https://github.com/aristanetworks/cloudvision/compare/v4.6.4...v4.6.5) (2021-01-20) ### Bug Fixes * **cloudvision-connector:** fix DatasetObject type ([#337](https://github.com/aristanetworks/cloudvision/issues/337)) ([b432bf9](https://github.com/aristanetworks/cloudvision/commit/b432bf93cad353a67edf9eb29e36736bbeef89be)) ## [4.6.4](https://github.com/aristanetworks/cloudvision/compare/v4.6.3...v4.6.4) (2021-01-19) ### Bug Fixes * **cloudvision-connector:** update type of DatasetObject ([#335](https://github.com/aristanetworks/cloudvision/issues/335)) ([32569b9](https://github.com/aristanetworks/cloudvision/commit/32569b99302829676cf1a2cb2b6aef2927226607)) ## [4.6.3](https://github.com/aristanetworks/cloudvision/compare/v4.6.2...v4.6.3) (2020-12-15) ### Bug Fixes * **docs:** install packages before running gh-pages ([#301](https://github.com/aristanetworks/cloudvision/issues/301)) ([bfe7057](https://github.com/aristanetworks/cloudvision/commit/bfe70573d1299cdb7d74b1a68efe8b6f02519fa2)) ### Features * **docs:** publish docs to gh-pages branch ([#300](https://github.com/aristanetworks/cloudvision/issues/300)) ([2c2cef3](https://github.com/aristanetworks/cloudvision/commit/2c2cef31c9f15ad7ae9ccc482720822514d6bea8)) ## [4.6.2](https://github.com/aristanetworks/cloudvision/compare/v4.6.1...v4.6.2) (2020-12-01) ### Bug Fixes * **a-msgpack:** properly key nested complex values ([#287](https://github.com/aristanetworks/cloudvision/issues/287)) ([0de0421](https://github.com/aristanetworks/cloudvision/commit/0de0421dfd868d29dcd4902a0c899ccd958a941f)) ## [4.6.1](https://github.com/aristanetworks/cloudvision/compare/v4.6.0...v4.6.1) (2020-11-04) ### Bug Fixes * **a-msgpack:** Always convert int64 to BigInt ([#224](https://github.com/aristanetworks/cloudvision/issues/224)) ([85c4c4e](https://github.com/aristanetworks/cloudvision/commit/85c4c4ed5642d89e44f5a5a705e4891d854c22fc)) # [4.6.0](https://github.com/aristanetworks/cloudvision/compare/v4.5.5...v4.6.0) (2020-10-05) ### Features * **cloudvision-connector:** add support for config dataset type ([#207](https://github.com/aristanetworks/cloudvision/issues/207)) ([5e9d570](https://github.com/aristanetworks/cloudvision/commit/5e9d57093c6f05b16fa7861470602dfd3ea73fee)) ## [4.5.5](https://github.com/aristanetworks/cloudvision/compare/v4.5.4...v4.5.5) (2020-09-16) **Note:** Version bump only for package root ## [4.5.4](https://github.com/aristanetworks/cloudvision/compare/v4.5.3...v4.5.4) (2020-08-10) ### Bug Fixes * **cloudvision-connector:** Remove deduping, other unused functionality ([#149](https://github.com/aristanetworks/cloudvision/issues/149)) ([b370b45](https://github.com/aristanetworks/cloudvision/commit/b370b45a7b79c8fdb7390fb5114d7edabbbb4dac)) ## [4.5.3](https://github.com/aristanetworks/cloudvision/compare/v4.5.2...v4.5.3) (2020-07-29) ### Bug Fixes * **cloudvision-connector:** export needed constants and types ([#141](https://github.com/aristanetworks/cloudvision/issues/141)) ([2875718](https://github.com/aristanetworks/cloudvision/commit/2875718b62ed97ee7879f6a0e86ae66f8286fae7)) ## [4.5.2](https://github.com/aristanetworks/cloudvision/compare/v4.5.1...v4.5.2) (2020-07-28) ### Bug Fixes * **cloudvision-connector:** add service request to Conenctor ([#139](https://github.com/aristanetworks/cloudvision/issues/139)) ([972440f](https://github.com/aristanetworks/cloudvision/commit/972440fb85fe1bf0f0a0df9f89a74e26f54be2bb)) ## [4.5.1](https://github.com/aristanetworks/cloudvision/compare/v4.5.0...v4.5.1) (2020-07-28) ### Bug Fixes * **cloudvision-connector:** add getAndSubscribe to Conenctor ([#138](https://github.com/aristanetworks/cloudvision/issues/138)) ([4b4df81](https://github.com/aristanetworks/cloudvision/commit/4b4df81efbf7ade6a54f9f774fbfc43a2e6e5651)) # [4.5.0](https://github.com/aristanetworks/cloudvision/compare/v4.4.0...v4.5.0) (2020-07-27) ### Features * **cloudvision-connector:** add server getAndSubscribe ([#134](https://github.com/aristanetworks/cloudvision/issues/134)) ([ee7b861](https://github.com/aristanetworks/cloudvision/commit/ee7b861f6015f9c90dba3fce7f83fc94795b0252)) # [4.4.0](https://github.com/aristanetworks/cloudvision/compare/v4.3.1...v4.4.0) (2020-07-14) ### Features * **a-msgpack:** add Wildcard support ([#124](https://github.com/aristanetworks/cloudvision/issues/124)) ([09d75d7](https://github.com/aristanetworks/cloudvision/commit/09d75d7d80faab8fe70f707e82529f8d5c213d42)) ## [4.3.1](https://github.com/aristanetworks/cloudvision/compare/v4.3.0...v4.3.1) (2020-07-07) **Note:** Version bump only for package root # [4.3.0](https://github.com/aristanetworks/cloudvision/compare/v4.2.0...v4.3.0) (2020-06-08) ### Bug Fixes * **packages:** add rimraf dev dependency ([#79](https://github.com/aristanetworks/cloudvision/issues/79)) ([15396e7](https://github.com/aristanetworks/cloudvision/commit/15396e72ca26bf7fc13009233c597cefe336d214)) ### Features * **cloudvision-connector:** add instrumentation ([#88](https://github.com/aristanetworks/cloudvision/issues/88)) ([59b99af](https://github.com/aristanetworks/cloudvision/commit/59b99afc870d95e97a3e77cd145afac27bec2424)) # [4.2.0](https://github.com/aristanetworks/cloudvision/compare/v4.1.0...v4.2.0) (2020-05-19) ### Bug Fixes * **cloudvision-connector:** Rename request args and add default ([1c40ef2](https://github.com/aristanetworks/cloudvision/commit/1c40ef2b027ca9d48d8bec90f3391585d0eb7321)) ### Features * **cloudvision-connector:** Refactor typings ([6668680](https://github.com/aristanetworks/cloudvision/commit/66686801705fca50e40226957bbca61bf42c6285)) # [4.1.0](https://github.com/aristanetworks/cloudvision/compare/v4.0.5...v4.1.0) (2020-05-11) ### Bug Fixes * **logging:** add more context to logging ([892282b](https://github.com/aristanetworks/cloudvision/commit/892282b10f85ec9de19ee6d143654bcebb0070e1)) ### Features * **callback:** add request context ([fbe23a5](https://github.com/aristanetworks/cloudvision/commit/fbe23a5113e49161669233aa3b7f954f2dc339df)) ## [4.0.5](https://github.com/aristanetworks/cloudvision/compare/v4.0.4...v4.0.5) (2020-05-06) **Note:** Version bump only for package root ## [4.0.4](https://github.com/aristanetworks/cloudvision/compare/v4.0.3...v4.0.4) (2020-04-28) **Note:** Version bump only for package root ## [4.0.3](https://github.com/aristanetworks/cloudvision/compare/v4.0.2...v4.0.3) (2020-04-24) **Note:** Version bump only for package root ## [4.0.2](https://github.com/aristanetworks/cloudvision/compare/v4.0.1...v4.0.2) (2020-04-21) **Note:** Version bump only for package root ## 4.0.1 (2020-04-15) ### Bug Fixes * **build:** update lerna publish message ([6336606](https://github.com/aristanetworks/cloudvision/commit/6336606e5d3a078bbd3e34f69a9c1defcec830f2)) * **package.json:** make root package private ([3ac4f40](https://github.com/aristanetworks/cloudvision/commit/3ac4f40ff43d6392cf1af17d5810ab5b5b81fcc8)) * **various:** upgrade to Babel 7 ([dc552b3](https://github.com/aristanetworks/cloudvision/commit/dc552b3bfc91102d5d53c725e2f7a6327f14dcf5)) * **yarn.lock:** update lockfile ([6eed646](https://github.com/aristanetworks/cloudvision/commit/6eed6462c0826b8e697062b114a8f0f5cf7372b3)) ### Features * **cloudvision-connector:** Implement Aeris Services logic. ([6336dbb](https://github.com/aristanetworks/cloudvision/commit/6336dbbc07f7987b97b2fca1f3de414f3b113ec6)) <file_sep>export { encode } from './encode'; export { decode } from './decode'; export { ExtensionCodec } from './ExtensionCodec'; export { ExtData } from './ExtData'; export { isJsbi } from './utils/data'; export { Bool, Float32, Float64, Int, Nil, Pointer, Str } from './neat/NeatTypes'; export { createBaseType } from './neat/typeCreators'; export { NeatTypes, Codec } from './neat'; export { isNeatType, NeatTypeSerializer } from './neat/utils'; <file_sep>// Copyright (c) 2018, Arista Networks, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. export { createBaseType, isJsbi, isNeatType, Bool, Float32, Float64, Int, NeatTypes, NeatTypeSerializer, Nil, Pointer, Str, } from 'a-msgpack'; export { default } from './Connector'; export { default as Parser } from './Parser'; export { ACTIVE_CODE, ALL_DATASET_TYPES, APP_DATASET_TYPE, CLOSE, CONFIG_DATASET_TYPE, CONNECTED, DEVICE_DATASET_TYPE, DISCONNECTED, EOF, EOF_CODE, GET, GET_AND_SUBSCRIBE, GET_DATASETS, GET_REQUEST_COMPLETED, PUBLISH, SEARCH, SEARCH_SUBSCRIBE, SERVICE_REQUEST, SUBSCRIBE, } from './constants'; export { fromBinaryKey, toBinaryKey, sanitizeOptions } from './utils';
7f51cecb91c62c111855a22afe64d714a37560fe
[ "Markdown", "JavaScript", "JSON with Comments", "TypeScript", "Shell" ]
84
TypeScript
aristanetworks/cloudvision
ae2f03d0092f343d449ddc5eda4166e1acfc492f
c7404a0378cae190d6d5c972184496c71821a695
refs/heads/master
<repo_name>agutsal/Vyper-Contract-GUI<file_sep>/app/actions/contractForm.js // @flow import { CONTRACT_DEPLOY, CONTRACT_SELECT_ADDRESS, CONTRACT_LOAD_BALANCES, CONTRACT_CALL_FUNCTION, CONTRACT_SEND_ETHER, } from '../constants/actions' const deployContract = (payload: Object) => ({ type: CONTRACT_DEPLOY, payload, }) const selectAddress = (file: Object, address: String) => ({ type: CONTRACT_SELECT_ADDRESS, payload: { file, address, } }) const loadContractBalances = (file: Object) => ({ type: CONTRACT_LOAD_BALANCES, file, }) const callFunction = (payload: Object) => ({ type: CONTRACT_CALL_FUNCTION, payload, }) const sendEther = (payload: Object) => ({ type: CONTRACT_SEND_ETHER, payload, }) export { deployContract, selectAddress, loadContractBalances, callFunction, sendEther, } <file_sep>/app/containers/contract-form/SendEther.js // @flow import { connect } from 'react-redux' import { sendEther } from '../../actions/contractForm' import SendEther from '../../components/contract-form/SendEther' function mapStateToProps(state) { return { file: state.selectedFile, web3: state.web3, } } const mapDispatchToProps = dispatch => ({ sendEther: (ether) => dispatch(sendEther(ether)), }) export default connect( mapStateToProps, mapDispatchToProps, )(SendEther) <file_sep>/app/containers/contract-form/Constructor.js // @flow import { connect } from 'react-redux' import Constructor from '../../components/contract-form/Constructor' import { deployContract } from '../../actions/contractForm' function mapStateToProps(state) { return { file: state.selectedFile, web3: state.web3, } } const mapDispatchToProps = dispatch => ({ deployContract: (contract) => dispatch(deployContract(contract)), }) export default connect( mapStateToProps, mapDispatchToProps, )(Constructor) <file_sep>/app/components/contract-form/Functions.js // @flow import React, { Component } from 'react' import { Form, Input, Button, Typography, } from 'antd' // TODO: // type Props = {} export default class Functions extends Component<Props> { renderInputs = (inputs) => { if (inputs) { return inputs.map((input, key) => { return ( <React.Fragment key={`f-f-input-${key}`}> {input.name} <Input key={`f-input-${key}`} //onChange={handleChange} style={{ width: '100%' }} name={input.name} placeholder={input.type} /> </React.Fragment> ) }) } } renderEthInput = (abiPart) => { if (abiPart.type === 'function' && abiPart.payable) { return ( <React.Fragment key={`f-f-input-${abiPart.name}`}> {'[transaktion value]'} <Input key={`f-input-${abiPart.name}`} style={{ width: '100%' }} name='transactionValue_CxH4' placeholder='ETH' /> </React.Fragment> ) } } createLabel = (a) => { let label = '' if (a.constant) { label += '@constant' } label = `${a.name}()` if (a.outputs && a.outputs[0]) { label += ` -> ${a.outputs[0].type}` } return label } /* handleChange = (formValue) => { this.setState({ formValue }) console.log('handleChange:') console.log(formValue) } validateBoolean = (formValue: String) => { if (formValue == 'True' ||formValue == 'False') { return { validateStatus: 'success', errorMsg: null, } } return { validateStatus: 'error', errorMsg: 'Not a valid type of True or False.', } } validateInt128 = (formValue: String) => { // TODO: if (true) { return { validateStatus: 'success', errorMsg: null, } } return { validateStatus: 'error', errorMsg: 'Not a valid int128 value.', } } validateUint256 = (formValue: String) => { // TODO: if (!isNaN(formValue)) { return { validateStatus: 'success', errorMsg: null, } } return { validateStatus: 'error', errorMsg: 'Not a valid uint256 value.', } } validateDecimal = (formValue: String) => { // TODO: if (true) { return { validateStatus: 'success', errorMsg: null, } } return { validateStatus: 'error', errorMsg: 'Not a valid decimal value.', } } validateAddress = (content: String) => { // TODO: if (true) { return { validateStatus: 'success', errorMsg: null, } } return { validateStatus: 'error', errorMsg: 'Not a valid address.', } } validateTime = (content: String) => { // TODO: if (true) { return { validateStatus: 'success', errorMsg: null, } } return { validateStatus: 'error', errorMsg: 'Not a valid time view.', } } validateWei = (content: String) => { // TODO: if (true) { return { validateStatus: 'success', errorMsg: null, } } return { validateStatus: 'error', errorMsg: 'Not a valid wei value.', } } validateString = (formValue: String) => { if (typeof formValue == 'string') { return { validateStatus: 'success', errorMsg: null, } } return { validateStatus: 'error', errorMsg: 'Not a valid string value.', } } validateBytes32 = (content: String) => { // TODO: if (true) { return { validateStatus: 'success', errorMsg: null, } } return { validateStatus: 'error', errorMsg: 'Not a valid bytes32 value.', } } validateBytes = (content: String) => { // TODO: if (true) { return { validateStatus: 'success', errorMsg: null, } } return { validateStatus: 'error', errorMsg: 'Not a valid bytes value.', } } */ handleSubmit = (abiFunc) => (event) => { event.preventDefault() const { file, web3, resetFunctionCallResults, callFunction } = this.props const formInputFields = $(event.target).find('input') let inputValues = {} let transactionValue = '0' formInputFields.each((index, item) => { if (item.name === 'transactionValue_CxH4') { transactionValue = item.value } else { inputValues[item.name] = item.value } }) // console.log('submit with values:') // console.log(inputValues) resetFunctionCallResults(abiFunc.name) callFunction({ file, functionDetails: abiFunc, inputs: inputValues, transactionValue, account: web3.selectedAccount, }) } // TODO: functionCallResult = (abiFunc) => { } render() { const { Text } = Typography const { file: { abi } } = this.props const { renderInputs, renderEthInput, createLabel, handleSubmit } = this const { functionCallResults } = this.props return ( <React.Fragment> <Text strong>functions</Text> { abi.map((abiPart, key) => { if (abiPart.type === 'function') { return ( <Form key={`form-${key}`} onSubmit={handleSubmit(abiPart)} name={abiPart.name} style={{ marginBottom:'10px', padding:'10px', backgroundColor:'rgb(240, 242, 245)' }} > <Text>{createLabel(abiPart)}</Text> <br /> {renderInputs(abiPart.inputs)} {renderEthInput(abiPart)} <Button block htmlType='submit'>call</Button> <Text style={{color:'#52c41a'}}>{functionCallResults[abiPart.name]}</Text> </Form> ) } }) } </React.Fragment> ) } } <file_sep>/app/actions/files.js // @flow import { FILES_FETCH_ALL, FILES_SHOW_ALL, FILES_UPLOAD, //FILES_COMPILE, FILES_RECOMPILE, FILES_SAVE, FILES_UPDATE, FILES_REMOVE, } from '../constants/actions' const filesFetchAll = () => ({ type: FILES_FETCH_ALL, }) const filesShowAll = (files: Array<Object>) => ({ type: FILES_SHOW_ALL, files, }) const fileUpload = (file: Object) => ({ type: FILES_UPLOAD, file, }) const fileReCompile = (file: Object) => ({ type: FILES_RECOMPILE, file, }) const fileSave = (file: Object) => ({ type: FILES_SAVE, file, }) const fileUpdate = (file: Object) => ({ type: FILES_UPDATE, }) const fileRemove = (file: Object) => ({ type: FILES_REMOVE, file, }) export { filesFetchAll, filesShowAll, fileUpload, fileReCompile, fileSave, fileUpdate, fileRemove, } <file_sep>/app/sagas/index.js // https://redux-saga.js.org/docs/advanced/RootSaga.html import { spawn } from 'redux-saga/effects' import { web3Saga } from './web3' import { settingsSaga } from './settings' import { filesSaga } from './files' import { addFileSaga } from './fileUpload' import { contractSaga } from './contract' export default function* rootSaga() { yield spawn(web3Saga) yield spawn(settingsSaga) yield spawn(filesSaga) yield spawn(addFileSaga) yield spawn(contractSaga) } /* export default function* rootSaga () { console.log('creating rootSaga') const sagas = [ addFileSaga, sidebarSaga //saga2, //saga3, ] console.log(sagas) yield sagas.map(saga => spawn(function* () { console.log('in spawn') while (true) { try { console.log('calling saga') console.log(saga) yield call(saga) break } catch (e) { console.log(e) } } }) ) } */ <file_sep>/app/containers/contract-form/Functions.js // @flow import { connect } from 'react-redux' import Functions from '../../components/contract-form/Functions' import { callFunction } from '../../actions/contractForm' import { resetFunctionCallResults } from '../../actions/functionCallResults' function mapStateToProps(state) { return { file: state.selectedFile, functionCallResults: state.functionCallResults, web3: state.web3, } } const mapDispatchToProps = dispatch => ({ callFunction: (contract) => dispatch(callFunction(contract)), resetFunctionCallResults: (functionDetails) => dispatch(resetFunctionCallResults(functionDetails)), }) export default connect( mapStateToProps, mapDispatchToProps, )(Functions) <file_sep>/app/sagas/fileUpload.js import { call, put, takeEvery } from 'redux-saga/effects' import { message } from 'antd' import { FILES_UPLOAD, FILES_COMPILE, FILES_RECOMPILE, FILES_SAVE, FILES_FETCH_ALL, SELECTED_FILE_SET, } from '../constants/actions' import { Files } from '../datastore' import { promiseDbInsert, promiseDbFind, promiseDbUpdate, uploadVyperFile, compileVyperFile, } from '../utils' export function* uploadFile(action) { try { const results = yield call(promiseDbFind, Files, { path: action.file.path }) if (results.length === 0) { const file = yield call(uploadVyperFile, action.file) yield put({ type: FILES_COMPILE, file }) } else { message.error('file already added') } } catch (e) { console.log(e) message.error(e.message) } } export function* compileFile(action) { try { const compiledFile = yield call(compileVyperFile, action.file) yield put({ type: FILES_SAVE, file: compiledFile }) } catch (e) { console.log(e) message.error(e.message) } } export function* reCompileFile(action) { try { const file = yield call(uploadVyperFile, action.file) const compiledFile = yield call(compileVyperFile, file) const query_find = { _id: compiledFile._id } const query_change = { $set: { ...compiledFile } } yield call(promiseDbUpdate, Files, query_find, query_change) yield put({ type: SELECTED_FILE_SET, file: compiledFile }) yield put({ type: FILES_FETCH_ALL }) message.success('file compiled') } catch (e) { console.log(e) message.error(e.message) } } export function* saveFile(action) { try { const newFile = yield call(promiseDbInsert, Files, action.file) yield put({ type: SELECTED_FILE_SET, file: newFile }) message.success('file saved') } catch (e) { console.log(e) message.error(e.message) } } export function* addFileSaga() { yield takeEvery(FILES_UPLOAD, uploadFile) yield takeEvery(FILES_COMPILE, compileFile) yield takeEvery(FILES_RECOMPILE, reCompileFile) yield takeEvery(FILES_SAVE, saveFile) } <file_sep>/app/sagas/settings.js import { call, put, takeEvery } from 'redux-saga/effects' import { message } from 'antd' import { SETTINGS_INIT, SETTINGS_UPDATE, SETTINGS_IMPORT_ACCOUNT, SETTINGS_REMOVE_ACCOUNT, SETTINGS_GENERATE_RANDOM_ACCOUNT, SETTINGS_RESET, WEB3_INIT, } from '../constants/actions' import { Settings } from '../datastore' import { promiseDbInsert, promiseDbFind, promiseDbUpdate, getWeb3, } from '../utils' export function* initializeSettings(action) { try { const currentSettings = yield call(promiseDbFind, Settings, { _id: 'connections' }) if (!currentSettings[0]) { const initial_settings = { _id: 'connections', rpcServer: 'http://127.0.0.1:7545', compilerUrl: 'http://127.0.0.1:8000/compile', } message.success('settings initialized') message.info(`rpc: ${initial_settings.rpcServer}`) message.info(`compiler: ${initial_settings.compilerUrl}`) yield put({ type: SETTINGS_UPDATE, settings: initial_settings }) } else { yield put({ type: SETTINGS_UPDATE, settings: currentSettings[0] }) } } catch (e) { console.log(e) } } export function* updateSettings(action) { try { const newSettings = action.settings const currentSettings = yield call(promiseDbFind, Settings, { _id: 'connections' }) if (currentSettings[0]) { // update const file = yield call(promiseDbUpdate, Settings, { _id: 'connections' }, newSettings) } else { // insert newSettings._id = 'connections' const file = yield call(promiseDbInsert, Settings, newSettings) } message.success('settings set') } catch (e) { console.log(e) message.error(e.message) } } export function* importAccountFromPrivateKey(action) { try { const web3 = yield call(getWeb3) const generateAccountFromPKPromise = (privateKey) => { return new Promise((resolve, reject) => { resolve(web3.eth.accounts.privateKeyToAccount(privateKey)) }) } const account = yield call(generateAccountFromPKPromise, action.privateKey) const query_find = { _id: 'accounts' } const query_update = { $push: { accounts: account } } yield call(promiseDbUpdate, Settings, query_find, query_update) yield put({ type: WEB3_INIT }) message.success('key imported') } catch (e) { console.log(e) message.error(e.message) } } export function* generateRandomAccount(action) { try { const web3 = yield call(getWeb3) const generateRandomAccountPromise = () => { return new Promise((resolve, reject) => { // TODO: create 'real' entropy const entropy = '+++' resolve(web3.eth.accounts.create(entropy)) }) } const account = yield call(generateRandomAccountPromise) const query_find = { _id: 'accounts' } const query_update = { $push: {accounts: account} } yield call(promiseDbUpdate, Settings, query_find, query_update) yield put({ type: WEB3_INIT }) message.success('account created') } catch (e) { console.log(e) message.error(e.message) } } export function* removeAccount(action) { try { const query_find = { _id: 'accounts' } const query_update = { $pull: { accounts: { address: action.account.address } } } yield call(promiseDbUpdate, Settings, query_find, query_update) yield put({ type: WEB3_INIT }) } catch (e) { console.log(e) message.error(e.message) } } // TODO: /* export function* resetSettings(action) { console.log(action) try { } catch (e) { console.log(e) message.error(e.message) } } */ export function* settingsSaga() { yield takeEvery(SETTINGS_INIT, initializeSettings) yield takeEvery(SETTINGS_UPDATE, updateSettings) yield takeEvery(SETTINGS_IMPORT_ACCOUNT, importAccountFromPrivateKey) yield takeEvery(SETTINGS_GENERATE_RANDOM_ACCOUNT, generateRandomAccount) yield takeEvery(SETTINGS_REMOVE_ACCOUNT, removeAccount) //yield takeEvery(SETTINGS_RESET, resetSettings) } <file_sep>/app/components/File.js // @flow import React, { Component } from 'react' import { Layout, Row, Col } from 'antd' import ContractForm from '../containers/contract-form' import CompilationFormats from '../containers/CompilationFormats' /* // TODO: type Props = { selectedFile: { _id: String, name: String, path: String, lastModified: Number, lastModifiedDate: String, // TODO: -> Date? size: Number, uid: String, addedOn: String, deployedAt: { addresses: Array, selected: String, }, content: String, abi: Array, method_identifiers: Object, interface: String, external_interface: String, bytecode: String, bytecode_runtime: String, ir: String, asm: String, source_map: { breakpoints: Array, pc_pos_map: Object, }, } } */ export default class File extends Component<Props> { render() { const { Content } = Layout // TODO: dynamically calculate marginTop return ( <Content style={{ margin:'64px 0px 0px' }}> <div style={{ padding:'24px', background:'#fff' }}> <Row> <Col span={12}> <ContractForm /> </Col> <Col span={12}> <CompilationFormats /> </Col> </Row> </div> </Content> ) } } <file_sep>/app/components/contract-form/Constructor.js // @flow import React, { Component } from 'react' import { Form, Input, Button, Typography, } from 'antd' // TODO: // type Props = {} export default class Constructor extends Component<Props> { handleSubmit = (e) => { e.preventDefault() const { web3, file, deployContract } = this.props const inputFields = $(e.target).find('input') let inputs = {} inputFields.each((index, item) => { inputs[item.name] = item.value }) deployContract({file, inputs, account: web3.selectedAccount}) } renderInputs = (inputs) => { if (inputs) { return inputs.map((input, key) => { return ( <React.Fragment key={`constr-f-input-${key}`}> {input.name} <Input key={`constr-input-${key}`} style={{ width:'100%' }} name={input.name} placeholder={input.type} /> </React.Fragment> ) }) } } render() { const { Text } = Typography const { file: { abi } } = this.props const { handleSubmit, renderInputs } = this return ( <React.Fragment> <Text strong>constructor</Text> <div style={{ marginBottom:'10px', padding:'10px', backgroundColor:'rgb(240, 242, 245)' }}> { abi.map((a, key) => { if (a.type === 'constructor') { return ( <Form key={`form-${key}`} onSubmit={handleSubmit}> <Form.Item key={`form-item-${key}`} label={a.name} style={{ marginBottom:0 }} /> {renderInputs(a.inputs)} <Button block htmlType='submit'>deploy</Button> </Form> ) } }) } </div> </React.Fragment> ) } } <file_sep>/app/reducers/selectedFile.js // @flow import type { Action } from './types' import { SELECTED_FILE_SET, CONTRACT_DEPLOY, CONTRACT_SELECT_ADDRESS, CONTRACT_CALL_FUNCTION, } from '../constants/actions' const initialState = {} export default function selectedFile(state: Object = initialState, action: Action) { switch (action.type) { case SELECTED_FILE_SET: return { ...state, ...action.file, } case CONTRACT_DEPLOY: return { ...state, } case CONTRACT_SELECT_ADDRESS: return { ...state, } case CONTRACT_CALL_FUNCTION: return { ...state, } default: return { ...state, } } } <file_sep>/app/containers/File.js // @flow import { connect } from 'react-redux' import File from '../components/File' function mapStateToProps(state) { return { ...state.selectedFile, } } const mapDispatchToProps = dispatch => ({ }) export default connect( mapStateToProps, mapDispatchToProps, )(File)
8e85bbda04e252600b1ddeb4fb86eee342abe6ec
[ "JavaScript" ]
13
JavaScript
agutsal/Vyper-Contract-GUI
4d97be36bf73490005752ec73c62079de19eb202
30a056bdfb91d77f069231e1a2c599175771104b
refs/heads/master
<repo_name>THORinHOOD/s3server<file_sep>/src/main/java/com/thorinhood/data/list/raw/ListBucketResultRawAbstract.java package com.thorinhood.data.list.raw; import com.thorinhood.data.S3FileObjectPath; import java.util.List; import java.util.Set; public abstract class ListBucketResultRawAbstract { protected List<S3FileObjectPath> s3FileObjectsPaths; protected boolean isTruncated; protected Set<String> commonPrefixes; public List<S3FileObjectPath> getS3FileObjectsPaths() { return s3FileObjectsPaths; } public boolean isTruncated() { return isTruncated; } public Set<String> getCommonPrefixes() { return commonPrefixes; } public static abstract class Builder<T extends Builder> { private ListBucketResultRawAbstract listBucketResultRawAbstract; private T childBuilder; protected void init(ListBucketResultRawAbstract listBucketResultRawAbstract, T childBuilder) { this.listBucketResultRawAbstract = listBucketResultRawAbstract; this.childBuilder = childBuilder; } public T setS3FileObjectsPaths(List<S3FileObjectPath> s3FileObjectsPaths) { listBucketResultRawAbstract.s3FileObjectsPaths = s3FileObjectsPaths; return childBuilder; } public T setIsTruncated(boolean isTruncated) { listBucketResultRawAbstract.isTruncated = isTruncated; return childBuilder; } public T setCommonPrefixes(Set<String> commonPrefixes) { listBucketResultRawAbstract.commonPrefixes = commonPrefixes; return childBuilder; } } } <file_sep>/src/main/java/com/thorinhood/utils/ParsedRequest.java package com.thorinhood.utils; import com.thorinhood.data.S3FileBucketPath; import com.thorinhood.data.S3FileObjectPath; import com.thorinhood.data.requests.S3ResponseErrorCodes; import com.thorinhood.data.S3User; import com.thorinhood.exceptions.S3Exception; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpResponseStatus; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; public class ParsedRequest { private byte[] bytes; private S3FileObjectPath s3FileObjectPath; private String signature; private Credential credential; private Integer decodedContentLength; private PayloadSignType payloadSignType; private HttpHeaders headers; private Map<String, List<String>> queryParams; private HttpMethod method; private Map<String, String> metadata; private S3User s3User; private String uri; private Set<String> signedHeaders; public static Builder builder() { return new Builder(); } private ParsedRequest() { } public boolean hasPathToObjectOrBucket() { return s3FileObjectPath != null; } public boolean isPathToObject() { return s3FileObjectPath != null && !s3FileObjectPath.isBucket(); } public byte[] getBytes() { return bytes; } public S3FileBucketPath getS3BucketPath() throws S3Exception { if (s3FileObjectPath == null) { throw S3Exception.builder("Not found bucket name") .setStatus(HttpResponseStatus.BAD_REQUEST) .setCode(S3ResponseErrorCodes.INVALID_REQUEST) .setMessage("Not found bucket name") .build(); } return s3FileObjectPath; } public S3FileObjectPath getS3ObjectPath() { if (s3FileObjectPath == null || s3FileObjectPath.isBucket()) { throw S3Exception.builder("Incorrect path to object : " + s3FileObjectPath) .setStatus(HttpResponseStatus.BAD_REQUEST) .setCode(S3ResponseErrorCodes.INVALID_REQUEST) .setMessage("Incorrect path to object : " + s3FileObjectPath) .build(); } return s3FileObjectPath; } public S3FileObjectPath getS3ObjectPathUnsafe() { return s3FileObjectPath; } public String getSignature() { return signature; } public Credential getCredential() { return credential; } public Integer getDecodedContentLength() { return decodedContentLength; } public PayloadSignType getPayloadSignType() { return payloadSignType; } public void setBytes(byte[] bytes) { this.bytes = bytes; } public boolean containsHeader(String header) { return headers.contains(header); } public String getHeader(String header) { return headers.get(header); } public HttpHeaders getHeaders() { return headers; } public HttpMethod getMethod() { return method; } public Map<String, String> getMetadata() { return metadata; } public Map<String, List<String>> getQueryParams() { return queryParams; } public S3User getS3User() { return s3User; } public String getRawUri() { return uri; } public Set<String> getSignedHeaders() { return signedHeaders; } public <T> T getQueryParam(String key, T defaultValue, Function<String, T> converter) throws S3Exception { if (!queryParams.containsKey(key)) { return defaultValue; } List<String> values = queryParams.get(key); if (values.size() != 1) { return defaultValue; } try { return converter.apply(values.get(0)); } catch (Exception exception) { throw S3Exception.builder("Can't parse query parameter") .setStatus(HttpResponseStatus.BAD_REQUEST) .setCode(S3ResponseErrorCodes.INVALID_ARGUMENT) .setMessage("Can't parse query parameter : " + key) .build(); } } public static class Builder { private final ParsedRequest parsedRequest; public Builder() { parsedRequest = new ParsedRequest(); } public Builder setBytes(byte[] bytes) { parsedRequest.bytes = bytes; return this; } public Builder setS3ObjectPath(S3FileObjectPath s3FileObjectPath) { parsedRequest.s3FileObjectPath = s3FileObjectPath; return this; } public Builder setSignature(String signature) { parsedRequest.signature = signature; return this; } public Builder setCredential(Credential credential) { parsedRequest.credential = credential; return this; } public Builder setDecodedContentLength(Integer decodedContentLength) { parsedRequest.decodedContentLength = decodedContentLength; return this; } public Builder setPayloadSignType(PayloadSignType payloadSignType) { parsedRequest.payloadSignType = payloadSignType; return this; } public Builder setHeaders(HttpHeaders headers) { parsedRequest.headers = headers; return this; } public Builder setQueryParams(Map<String, List<String>> queryParams) { parsedRequest.queryParams = queryParams; return this; } public Builder setMethod(HttpMethod method) { parsedRequest.method = method; return this; } public Builder setMetadata(Map<String, String> metadata) { parsedRequest.metadata = metadata; return this; } public Builder setS3User(S3User s3User) { parsedRequest.s3User = s3User; return this; } public Builder setRawUri(String uri) { parsedRequest.uri = uri; return this; } public Builder setSignedHeaders(Set<String> signedHeaders) { parsedRequest.signedHeaders = signedHeaders; return this; } public ParsedRequest build() { return parsedRequest; } } } <file_sep>/src/test/java/com/thorinhood/actions/GetObjectTest.java package com.thorinhood.actions; import com.thorinhood.BaseTest; import com.thorinhood.data.requests.S3ResponseErrorCodes; import io.netty.handler.codec.http.HttpResponseStatus; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.sync.ResponseTransformer; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; public class GetObjectTest extends BaseTest { public GetObjectTest() { super("testS3Java", 9999); } @Test public void getObjectSimple() { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); String content = "hello, s3!!!"; Map<String, String> metadata = Map.of( "key", "value", "key1", "value1"); createBucketRaw(s3, "bucket"); putObjectRaw(s3, "bucket", "file.txt", content, metadata); getObject(s3, "bucket", "file.txt", content, metadata); } @Test public void getObjectCompositeKey() { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); String content = "hello, s3!!!"; Map<String, String> metadata = Map.of("key", "value"); createBucketRaw(s3, "bucket"); putObjectRaw(s3, "bucket", "folder1/folder2/file.txt", content, metadata); putObjectRaw(s3, "bucket", "folder1/file.txt", content, metadata); getObject(s3, "bucket", "folder1/file.txt", content, metadata); getObject(s3, "bucket", "folder1/folder2/file.txt", content, metadata); } @Test public void getObjectUnregisterUser() { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); String content = "hello, s3!!!"; Map<String, String> metadata = Map.of("key", "value"); createBucketRaw(s3, "bucket"); putObjectRaw(s3, "bucket", "folder1/file.txt", content, metadata); S3Client s3ClientNotAuth = getS3Client(false, NOT_AUTH_ROOT_USER.getAccessKey(), NOT_AUTH_ROOT_USER.getSecretKey()); assertException(HttpResponseStatus.FORBIDDEN.code(), S3ResponseErrorCodes.ACCESS_DENIED, () -> { getObject(s3ClientNotAuth, "bucket", "folder1/file.txt", content, metadata); }); } @Test public void getObjectAnotherUser() { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); String content = "hello, s3!!!"; Map<String, String> metadata = Map.of("key", "value"); createBucketRaw(s3, "bucket"); putObjectRaw(s3, "bucket", "folder1/file.txt", content, metadata); S3Client s3Client2 = getS3Client(false, ROOT_USER_2.getAccessKey(), ROOT_USER_2.getSecretKey()); assertException(HttpResponseStatus.FORBIDDEN.code(), S3ResponseErrorCodes.ACCESS_DENIED, () -> { getObject(s3Client2, "bucket", "folder1/file.txt", content, metadata); }); } @Test public void getObjectWithHeaders() { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); String content = "hello, s3!!!"; Map<String, String> metadata = Map.of("key", "value"); createBucketRaw(s3, "bucket"); putObjectRaw(s3, "bucket", "folder1/file.txt", content, metadata); getObject(s3, "bucket", "folder1/file.txt", content, metadata, calcETag(content), null); getObject(s3, "bucket", "folder1/file.txt", content, metadata, null, "aaa"); assertException(HttpResponseStatus.PRECONDITION_FAILED.code(), S3ResponseErrorCodes.PRECONDITION_FAILED, () -> { getObject(s3, "bucket", "folder1/file.txt", content, metadata, "aaa", null); }); assertException(HttpResponseStatus.PRECONDITION_FAILED.code(), S3ResponseErrorCodes.PRECONDITION_FAILED, () -> { getObject(s3, "bucket", "folder1/file.txt", content, metadata, null, calcETag(content)); }); } @Test public void getObjectSeveralRequests() throws Exception { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); S3AsyncClient s3Async = getS3AsyncClient(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); String content = createContent(5242880); Map<String, String> metadata = Map.of( "key", "value", "key3", "value3", "key12", "value12" ); createBucketRaw(s3, "bucket"); putObjectRaw(s3, "bucket", "folder1/folder2/file.txt", content, metadata); List<CompletableFuture<ResponseBytes<GetObjectResponse>>> futureList = getObjectAsync(s3Async, "bucket", "folder1/folder2/file.txt", null, null, 200); for (CompletableFuture<ResponseBytes<GetObjectResponse>> responseBytesCompletableFuture : futureList) { checkGetObject(content, metadata, responseBytesCompletableFuture.get()); } } } <file_sep>/src/main/java/com/thorinhood/ServerInitializer.java package com.thorinhood; import com.thorinhood.drivers.main.S3Driver; import com.thorinhood.drivers.user.UserDriver; import com.thorinhood.handlers.ServerHandler; import com.thorinhood.utils.RequestUtil; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; public class ServerInitializer extends ChannelInitializer<SocketChannel> { private final ServerHandler serverHandler; public ServerInitializer(S3Driver s3Driver, RequestUtil requestUtil) { serverHandler = new ServerHandler(s3Driver, requestUtil); } @Override protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); pipeline.addLast(new HttpRequestDecoder()); pipeline.addLast(new HttpResponseEncoder()); pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE)); pipeline.addLast(serverHandler); } } <file_sep>/src/main/java/com/thorinhood/data/requests/S3ResponseErrorCodes.java package com.thorinhood.data.requests; public class S3ResponseErrorCodes { public static final String INTERNAL_ERROR = "InternalError"; public static final String BUCKET_ALREADY_OWNED_BY_YOU = "BucketAlreadyOwnedByYou"; public static final String BUCKET_ALREADY_EXISTS = "BucketAlreadyExists"; public static final String NO_SUCH_BUCKET = "NoSuchBucket"; public static final String NO_SUCH_KEY = "NoSuchKey"; public static final String INVALID_REQUEST = "InvalidRequest"; public static final String INVALID_ARGUMENT = "InvalidArgument"; public static final String SIGNATURE_DOES_NOT_MATCH = "SignatureDoesNotMatch"; public static final String PRECONDITION_FAILED = "PreconditionFailed"; public static final String ACCESS_DENIED = "AccessDenied"; public static final String NO_SUCH_UPLOAD = "NoSuchUpload"; public static final String INVALID_PART = "InvalidPart"; public static final String ENTITY_TOO_SMALL = "EntityTooSmall"; } <file_sep>/src/main/java/com/thorinhood/processors/actions/CopyObjectProcessor.java package com.thorinhood.processors.actions; import com.thorinhood.data.S3FileObjectPath; import com.thorinhood.data.results.CopyObjectResult; import com.thorinhood.drivers.main.S3Driver; import com.thorinhood.processors.Processor; import com.thorinhood.utils.DateTimeUtil; import com.thorinhood.utils.ParsedRequest; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpResponseStatus; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class CopyObjectProcessor extends Processor { private static final Logger log = LogManager.getLogger(CopyObjectProcessor.class); public CopyObjectProcessor(S3Driver s3Driver) { super(s3Driver); } @Override protected void processInner(ChannelHandlerContext context, FullHttpRequest request, ParsedRequest parsedRequest, Object... arguments) throws Exception { S3FileObjectPath sourcePath = S3_DRIVER.buildPathToObject(parsedRequest.getHeader("x-amz-copy-source")); checkRequestPermissions(sourcePath, parsedRequest.getS3User(), "s3:GetObject", false); checkRequestPermissions(parsedRequest, "s3:PutObject", true); CopyObjectResult copyObjectResult = S3_DRIVER.copyObject( sourcePath, parsedRequest.getS3ObjectPath(), parsedRequest.getHeaders(), parsedRequest.getS3User()); String xml = copyObjectResult.buildXmlText(); sendResponse(context, request, HttpResponseStatus.OK, response -> { response.headers().set("Date", DateTimeUtil.currentDateTime()); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/xml"); }, xml); } @Override protected Logger getLogger() { return log; } } <file_sep>/src/test/java/com/thorinhood/actions/CreateBucketTest.java package com.thorinhood.actions; import com.thorinhood.BaseTest; import com.thorinhood.data.requests.S3ResponseErrorCodes; import io.netty.handler.codec.http.HttpResponseStatus; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.CreateBucketRequest; import software.amazon.awssdk.services.s3.model.CreateBucketResponse; import java.io.File; import java.util.stream.Collectors; import java.util.stream.IntStream; public class CreateBucketTest extends BaseTest { public CreateBucketTest() { super("testS3Java", 9999); } @Test void createBucket() { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); CreateBucketRequest request = CreateBucketRequest.builder() .bucket("bucket") .build(); CreateBucketResponse response = s3.createBucket(request); File bucket = new File(BASE_PATH + File.separatorChar + "bucket"); Assertions.assertTrue(bucket.exists() && bucket.isDirectory()); File metaBucketFolder = new File(BASE_PATH + File.separatorChar + ".#bucket"); Assertions.assertTrue(metaBucketFolder.exists() && metaBucketFolder.isDirectory()); File aclBucketFile = new File(BASE_PATH + File.separatorChar + ".#bucket" + File.separatorChar + "bucket.acl"); Assertions.assertTrue(aclBucketFile.exists() && aclBucketFile.isFile()); assertException(HttpResponseStatus.CONFLICT.code(), S3ResponseErrorCodes.BUCKET_ALREADY_OWNED_BY_YOU, () -> s3.createBucket(request)); S3Client s3Client2 = getS3Client(false, ROOT_USER_2.getAccessKey(), ROOT_USER_2.getSecretKey()); assertException(HttpResponseStatus.CONFLICT.code(), S3ResponseErrorCodes.BUCKET_ALREADY_EXISTS, () -> s3Client2.createBucket(request)); } } <file_sep>/src/main/java/com/thorinhood/data/multipart/Part.java package com.thorinhood.data.multipart; import com.thorinhood.data.requests.S3ResponseErrorCodes; import com.thorinhood.exceptions.S3Exception; import io.netty.handler.codec.http.HttpResponseStatus; import org.w3c.dom.Node; public class Part { private final String eTag; private final int partNumber; public static Part buildFromNode(Node node) throws S3Exception { String eTag = null; int partNumber = 0; for (int i = 0; i < node.getChildNodes().getLength(); i++) { Node child = node.getChildNodes().item(i); if (child.getNodeName().equals("ETag")) { eTag = child.getChildNodes().item(0).getNodeValue(); } else if (child.getNodeName().equals("PartNumber")) { try { partNumber = Integer.parseInt(child.getChildNodes().item(0).getNodeValue()); } catch (Exception exception) { throw S3Exception.builder("Part number must be an integer between 1 and 10000, " + "inclusive") .setStatus(HttpResponseStatus.BAD_REQUEST) .setCode(S3ResponseErrorCodes.INVALID_ARGUMENT) .setMessage("Part number must be an integer between 1 and 10000, inclusive") .build(); } } } if (eTag == null) { throw S3Exception.builder("Missed ETag value for one of the parts") .setStatus(HttpResponseStatus.BAD_REQUEST) .setCode(S3ResponseErrorCodes.INVALID_REQUEST) .setMessage("Missed ETag value for one of the parts") .build(); } if (partNumber < 1 || partNumber > 10000) { throw S3Exception.builder("Part number must be an integer between 1 and 10000, inclusive") .setStatus(HttpResponseStatus.BAD_REQUEST) .setCode(S3ResponseErrorCodes.INVALID_ARGUMENT) .setMessage("Part number must be an integer between 1 and 10000, inclusive") .build(); } return new Part(eTag, partNumber); } private Part(String eTag, int partNumber) { this.eTag = eTag; this.partNumber = partNumber; } public String getETag() { return eTag; } public int getPartNumber() { return partNumber; } } <file_sep>/src/main/java/com/thorinhood/processors/multipart/CompleteMultipartUploadProcessor.java package com.thorinhood.processors.multipart; import com.thorinhood.data.multipart.CompleteMultipartUpload; import com.thorinhood.data.results.CompleteMultipartUploadResult; import com.thorinhood.drivers.main.S3Driver; import com.thorinhood.processors.Processor; import com.thorinhood.utils.DateTimeUtil; import com.thorinhood.utils.ParsedRequest; import com.thorinhood.utils.XmlUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpResponseStatus; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.w3c.dom.Document; import java.util.function.Function; public class CompleteMultipartUploadProcessor extends Processor { private static final Logger log = LogManager.getLogger(CompleteMultipartUploadProcessor.class); public CompleteMultipartUploadProcessor(S3Driver s3Driver) { super(s3Driver); } @Override protected void processInner(ChannelHandlerContext context, FullHttpRequest request, ParsedRequest parsedRequest, Object... arguments) throws Exception { checkRequestPermissions(parsedRequest, "s3:PutObject", true); Document document = XmlUtil.parseXmlFromBytes(parsedRequest.getBytes()); CompleteMultipartUpload completeMultipartUpload = CompleteMultipartUpload .buildFromNode(document.getDocumentElement()); String eTag = S3_DRIVER.completeMultipartUpload( parsedRequest.getS3ObjectPath(), parsedRequest.getQueryParam("uploadId", null, Function.identity()), completeMultipartUpload.getParts(), parsedRequest.getS3User()); CompleteMultipartUploadResult completeMultipartUploadResult = CompleteMultipartUploadResult.builder() .setETag("\"" + eTag + "\"") .setKey(parsedRequest.getS3ObjectPath().getKey()) .setLocation(parsedRequest.getS3ObjectPath().getKeyWithBucket()) .setBucket(parsedRequest.getS3ObjectPath().getBucket()) .build(); String xml = completeMultipartUploadResult.buildXmlText(); sendResponse(context, request, HttpResponseStatus.OK, response -> { response.headers().set("Date", DateTimeUtil.currentDateTime()); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/xml"); }, xml); } @Override protected Logger getLogger() { return log; } } <file_sep>/src/main/java/com/thorinhood/drivers/user/UserDriver.java package com.thorinhood.drivers.user; import com.thorinhood.data.S3User; import com.thorinhood.exceptions.S3Exception; import java.util.Optional; public interface UserDriver { void addUser(S3User s3User) throws S3Exception; void addUser(String pathToIdentity) throws Exception; Optional<S3User> getS3User(String accessKey) throws S3Exception; void removeUser(String accessKey) throws S3Exception; } <file_sep>/src/main/java/com/thorinhood/drivers/entity/EntityDriver.java package com.thorinhood.drivers.entity; import com.thorinhood.data.list.raw.ListBucketResultRaw; import com.thorinhood.data.list.request.GetBucketObjects; import com.thorinhood.data.list.request.GetBucketObjectsV2; import com.thorinhood.data.S3FileBucketPath; import com.thorinhood.data.S3FileObjectPath; import com.thorinhood.data.S3User; import com.thorinhood.data.multipart.Part; import com.thorinhood.data.list.raw.ListBucketV2ResultRaw; import com.thorinhood.data.s3object.HasMetaData; import com.thorinhood.data.s3object.S3Object; import com.thorinhood.exceptions.S3Exception; import com.thorinhood.utils.Pair; import io.netty.handler.codec.http.HttpHeaders; import java.util.List; import java.util.Map; public interface EntityDriver { void createBucket(S3FileBucketPath s3FileBucketPath, S3User s3User) throws S3Exception; HasMetaData getObject(S3FileObjectPath s3FileObjectPath, String eTag, HttpHeaders httpHeaders, boolean isCopyRead) throws S3Exception; HasMetaData headObject(S3FileObjectPath s3FileObjectPath, String eTag, HttpHeaders httpHeaders) throws S3Exception; S3Object putObject(S3FileObjectPath s3FileObjectPath, byte[] bytes, Map<String, String> metadata) throws S3Exception; void deleteObject(S3FileObjectPath s3FileObjectPath) throws S3Exception; void deleteBucket(S3FileBucketPath s3FileBucketPath) throws S3Exception; ListBucketV2ResultRaw getBucketObjectsV2(GetBucketObjectsV2 getBucketObjectsV2) throws S3Exception; ListBucketResultRaw getBucketObjects(GetBucketObjects getBucketObjects) throws S3Exception; List<Pair<S3FileBucketPath, String>> getBuckets(S3User s3User) throws S3Exception; void createMultipartUpload(S3FileObjectPath s3FileObjectPath, String uploadId) throws S3Exception; void abortMultipartUpload(S3FileObjectPath s3FileObjectPath, String uploadId) throws S3Exception; String putUploadPart(S3FileObjectPath s3FileObjectPath, String uploadId, int partNumber, byte[] bytes) throws S3Exception; String completeMultipartUpload(S3FileObjectPath s3FileObjectPath, String uploadId, List<Part> parts) throws S3Exception; } <file_sep>/src/main/java/com/thorinhood/drivers/main/S3FileDriverImpl.java package com.thorinhood.drivers.main; import com.thorinhood.data.*; import com.thorinhood.data.acl.*; import com.thorinhood.data.list.eventual.ListBucketResult; import com.thorinhood.data.list.raw.ListBucketResultRaw; import com.thorinhood.data.list.request.GetBucketObjects; import com.thorinhood.data.list.request.GetBucketObjectsV2; import com.thorinhood.data.multipart.Part; import com.thorinhood.data.policy.BucketPolicy; import com.thorinhood.data.policy.Statement; import com.thorinhood.data.results.CopyObjectResult; import com.thorinhood.data.results.GetBucketsResult; import com.thorinhood.data.list.eventual.ListBucketV2Result; import com.thorinhood.data.list.raw.ListBucketV2ResultRaw; import com.thorinhood.data.s3object.HasMetaData; import com.thorinhood.data.s3object.S3Object; import com.thorinhood.data.requests.S3ResponseErrorCodes; import com.thorinhood.data.s3object.S3ObjectETag; import com.thorinhood.drivers.FileDriver; import com.thorinhood.drivers.lock.EntityLockDriver; import com.thorinhood.drivers.acl.AclDriver; import com.thorinhood.drivers.entity.EntityDriver; import com.thorinhood.drivers.metadata.FileMetadataDriver; import com.thorinhood.drivers.metadata.MetadataDriver; import com.thorinhood.drivers.principal.PolicyDriver; import com.thorinhood.exceptions.S3Exception; import com.thorinhood.utils.DateTimeUtil; import com.thorinhood.utils.Pair; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpResponseStatus; import org.apache.commons.codec.digest.DigestUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.io.IOException; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.function.Function; import java.util.stream.Collectors; public class S3FileDriverImpl implements S3Driver { private final MetadataDriver metadataDriver; private final AclDriver aclDriver; private final PolicyDriver policyDriver; private final EntityDriver entityDriver; private final EntityLockDriver entityLockDriver; private final FileDriver fileDriver; private static final Logger log = LogManager.getLogger(S3FileDriverImpl.class); public S3FileDriverImpl(MetadataDriver metadataDriver, AclDriver aclDriver, PolicyDriver policyDriver, EntityDriver entityDriver, FileDriver fileDriver, EntityLockDriver entityLockDriver) { this.metadataDriver = metadataDriver; this.aclDriver = aclDriver; this.policyDriver = policyDriver; this.entityDriver = entityDriver; this.entityLockDriver = entityLockDriver; this.fileDriver = fileDriver; } @Override public Optional<Boolean> checkBucketPolicy(S3FileBucketPath s3FileBucketPath, String key, String methodName, S3User s3User) throws S3Exception { fileDriver.checkBucket(s3FileBucketPath); String policyFilePath = s3FileBucketPath.getPathToBucketPolicyFile(); if (!fileDriver.isFileExists(policyFilePath)) { return Optional.empty(); } Optional<BucketPolicy> bucketPolicy = entityLockDriver.readMeta( s3FileBucketPath.getPathToBucket(), s3FileBucketPath.getPathToBucketMetadataFolder(), policyFilePath, () -> getBucketPolicy(s3FileBucketPath) ); if (bucketPolicy.isEmpty()) { return Optional.empty(); } for (Statement statement : bucketPolicy.get().getStatements()) { Optional<Boolean> checkResult = checkStatement(statement, s3FileBucketPath.getBucket(), key, methodName, s3User); if (checkResult.isPresent()) { return checkResult; } } return Optional.empty(); } private Optional<Boolean> checkStatement(Statement statement, String bucket, String key, String methodName, S3User s3User) { boolean isThisPrincipal = checkPrincipal(statement.getPrinciple().getAWS(), s3User.getArn()); if (!isThisPrincipal) { return Optional.empty(); } boolean hasAction = statement.getAction().stream().anyMatch(action -> checkAction(action, methodName)); if (!hasAction) { return Optional.empty(); } boolean isThisResource = statement.getResource().stream().anyMatch(resource -> checkResource(resource, bucket, key)); if (!isThisResource) { return Optional.empty(); } return Optional.of(checkEffect(statement.getEffect())); } private boolean checkEffect(Statement.EffectType effect) { return Statement.EffectType.Allow.equals(effect); } private boolean checkPrincipal(List<String> patterns, String arn) { return patterns.stream().anyMatch(pattern -> match(pattern, arn)); } private boolean checkResource(String pattern, String bucket, String key) { String resource = "arn:aws:s3:::" + bucket + (key != null && !key.isEmpty() ? "/" + key : ""); return match(pattern, resource); } private boolean checkAction(String pattern, String toCheck) { return match(pattern, toCheck); } @Override public Optional<byte[]> getBucketPolicyBytes(S3FileBucketPath s3FileBucketPath) throws S3Exception { Optional<BucketPolicy> bucketPolicy = entityLockDriver.readMeta( s3FileBucketPath.getPathToBucket(), s3FileBucketPath.getPathToBucketMetadataFolder(), s3FileBucketPath.getPathToBucketPolicyFile(), () -> getBucketPolicy(s3FileBucketPath) ); if (bucketPolicy.isEmpty()) { return Optional.empty(); } return Optional.of(policyDriver.convertBucketPolicy(s3FileBucketPath, bucketPolicy.get())); } @Override public Optional<BucketPolicy> getBucketPolicy(S3FileBucketPath s3FileBucketPath) throws S3Exception { return entityLockDriver.readMeta( s3FileBucketPath.getPathToBucket(), s3FileBucketPath.getPathToBucketMetadataFolder(), s3FileBucketPath.getPathToBucketPolicyFile(), () -> policyDriver.getBucketPolicy(s3FileBucketPath) ); } @Override public void putBucketPolicy(S3FileBucketPath s3FileBucketPath, byte[] bytes) throws S3Exception { entityLockDriver.writeMeta( s3FileBucketPath.getPathToBucket(), s3FileBucketPath.getPathToBucketMetadataFolder(), s3FileBucketPath.getPathToBucketPolicyFile(), () -> policyDriver.putBucketPolicy(s3FileBucketPath, bytes) ); } @Override public void isBucketExists(S3FileBucketPath s3FileBucketPath) throws S3Exception { fileDriver.checkBucket(s3FileBucketPath); } @Override public boolean checkAclPermission(boolean isBucketAcl, S3FileObjectPath s3FileObjectPath, String methodName, S3User s3User) throws S3Exception { if (isBucketAcl) { AccessControlPolicy acl = getBucketAcl(s3FileObjectPath); return checkPermission(Permission::getMethodsBucket, acl, methodName, s3User); } else { fileDriver.checkObject(s3FileObjectPath); AccessControlPolicy acl = getObjectAcl(s3FileObjectPath); return checkPermission(Permission::getMethodsObject, acl, methodName, s3User); } } private boolean checkPermission(Function<Permission, Set<String>> methodsGetter, AccessControlPolicy acl, String methodName, S3User s3User) { return acl.getAccessControlList().stream() .filter(grant -> (grant.getGrantee().getDisplayName().equals(s3User.getAccountName()) && grant.getGrantee().getId().equals(s3User.getCanonicalUserId()))) .map(Grant::getPermission) .map(methodsGetter) .flatMap(Collection::stream) .distinct() .anyMatch(name -> name.equals(methodName)); } @Override public boolean isOwner(boolean isBucket, S3FileObjectPath s3FileObjectPath, S3User s3User) throws S3Exception { return (isBucket ? isOwner(getBucketAcl(s3FileObjectPath), s3User) : isOwner(getObjectAcl(s3FileObjectPath), s3User)); } private boolean isOwner(AccessControlPolicy acl, S3User s3User) throws S3Exception { return acl.getOwner().getDisplayName().equals(s3User.getAccountName()) && acl.getOwner().getId().equals(s3User.getCanonicalUserId()); } @Override public AccessControlPolicy getBucketAcl(S3FileBucketPath s3FileBucketPath) throws S3Exception { return entityLockDriver.readMeta( s3FileBucketPath.getPathToBucket(), s3FileBucketPath.getPathToBucketMetadataFolder(), s3FileBucketPath.getPathToBucketAclFile(), () -> aclDriver.getBucketAcl(s3FileBucketPath) ); } @Override public AccessControlPolicy getObjectAcl(S3FileObjectPath s3FileObjectPath) throws S3Exception { fileDriver.checkObject(s3FileObjectPath); return entityLockDriver.readMeta( s3FileObjectPath.getPathToBucket(), s3FileObjectPath.getPathToObjectMetadataFolder(), s3FileObjectPath.getPathToObjectAclFile(), () -> aclDriver.getObjectAcl(s3FileObjectPath) ); } @Override public void putBucketAcl(S3FileBucketPath s3FileBucketPath, byte[] bytes) throws S3Exception { AccessControlPolicy acl = aclDriver.parseFromBytes(bytes); entityLockDriver.writeMeta( s3FileBucketPath.getPathToBucket(), s3FileBucketPath.getPathToBucketMetadataFolder(), s3FileBucketPath.getPathToBucketAclFile(), () -> aclDriver.putBucketAcl(s3FileBucketPath, acl) ); } @Override public String putObjectAcl(S3FileObjectPath s3FileObjectPath, byte[] bytes) throws S3Exception { fileDriver.checkObject(s3FileObjectPath); AccessControlPolicy acl = aclDriver.parseFromBytes(bytes); return entityLockDriver.writeMeta( s3FileObjectPath.getPathToBucket(), s3FileObjectPath.getPathToObjectMetadataFolder(), s3FileObjectPath.getPathToObjectAclFile(), () -> aclDriver.putObjectAcl(s3FileObjectPath, acl) ); } @Override public void createBucket(S3FileBucketPath s3FileBucketPath, S3User s3User) throws S3Exception { File bucketFile = new File(s3FileBucketPath.getPathToBucket()); if (bucketFile.exists() && bucketFile.isDirectory()) { boolean isOwner = isOwner(true, (S3FileObjectPath) s3FileBucketPath, s3User); if (!isOwner) { throw S3Exception.BUCKET_ALREADY_EXISTS(); } else { throw S3Exception.BUCKET_ALREADY_OWNED_BY_YOU(bucketFile.getAbsolutePath()); } } entityLockDriver.writeBucket( s3FileBucketPath, () -> { entityDriver.createBucket(s3FileBucketPath, s3User); fileDriver.createFolder(s3FileBucketPath.getPathToBucketMetadataFolder()); aclDriver.putBucketAcl(s3FileBucketPath, createDefaultAccessControlPolicy(s3User)); } ); } @Override public S3Object getObject(S3FileObjectPath s3FileObjectPath, HttpHeaders httpHeaders) throws S3Exception { fileDriver.checkObject(s3FileObjectPath); return entityLockDriver.readObject( s3FileObjectPath, () -> { Map<String, String> objectMetadata = metadataDriver.getObjectMetadata(s3FileObjectPath); HasMetaData rawS3Object = entityDriver.getObject(s3FileObjectPath, objectMetadata.get(FileMetadataDriver.ETAG), httpHeaders, false); objectMetadata.remove(FileMetadataDriver.ETAG); return rawS3Object.setMetaData(objectMetadata); } ); } @Override public CopyObjectResult copyObject(S3FileObjectPath source, S3FileObjectPath target, HttpHeaders httpHeaders, S3User s3User) throws S3Exception { S3Object sourceObject = entityLockDriver.readObject( source, () -> { Map<String, String> metadata = metadataDriver.getObjectMetadata(source); String sourceETag = metadata.get(FileMetadataDriver.ETAG); metadata.remove(FileMetadataDriver.ETAG); return entityDriver.getObject(source, sourceETag, httpHeaders, true) .setMetaData(metadata); } ); S3Object targetObject = putObject(target, sourceObject.getRawBytes(), sourceObject.getMetaData(), s3User); return CopyObjectResult.builder() .setETag("\"" + targetObject.getETag() + "\"") .setLastModified(DateTimeUtil.parseDateTimeISO(targetObject.getFile())) .build(); } @Override public S3Object headObject(S3FileObjectPath s3FileObjectPath, HttpHeaders httpHeaders) throws S3Exception { fileDriver.checkObject(s3FileObjectPath); return entityLockDriver.readObject( s3FileObjectPath, () -> { Map<String, String> objectMetadata = metadataDriver.getObjectMetadata(s3FileObjectPath); HasMetaData rawS3Object = entityDriver.headObject(s3FileObjectPath, objectMetadata.get(FileMetadataDriver.ETAG), httpHeaders); objectMetadata.remove(FileMetadataDriver.ETAG); return rawS3Object.setMetaData(objectMetadata); } ); } @Override public S3Object putObject(S3FileObjectPath s3FileObjectPath, byte[] bytes, Map<String, String> metadata, S3User s3User) throws S3Exception { return entityLockDriver.writeObject( s3FileObjectPath, () -> { fileDriver.createFolder(s3FileObjectPath.getPathToObjectMetadataFolder()); S3Object s3Object = entityDriver.putObject(s3FileObjectPath, bytes, metadata); metadataDriver.putObjectMetadata(s3FileObjectPath, metadata, s3Object.getETag()); aclDriver.putObjectAcl(s3FileObjectPath, createDefaultAccessControlPolicy(s3User)); return s3Object; } ); } @Override public void deleteObject(S3FileObjectPath s3FileObjectPath) throws S3Exception { fileDriver.checkObject(s3FileObjectPath); entityLockDriver.deleteObject(s3FileObjectPath, () -> entityDriver.deleteObject(s3FileObjectPath)); } @Override public void deleteBucket(S3FileBucketPath s3FileBucketPath) throws S3Exception { entityLockDriver.writeBucket(s3FileBucketPath, () -> entityDriver.deleteBucket(s3FileBucketPath)); } @Override public ListBucketV2Result getBucketObjectsV2(S3FileBucketPath s3FileBucketPath, GetBucketObjectsV2 getBucketObjectsV2) throws S3Exception { ListBucketV2ResultRaw rawResult = entityDriver.getBucketObjectsV2(getBucketObjectsV2); List<S3Content> s3Contents = makeContents(rawResult.getS3FileObjectsPaths()); return ListBucketV2Result.builder() .setMaxKeys(getBucketObjectsV2.getMaxKeys()) .setName(getBucketObjectsV2.getBucket()) .setContents(s3Contents) .setPrefix(getBucketObjectsV2.getPrefix()) .setStartAfter(getBucketObjectsV2.getStartAfter()) .setIsTruncated(rawResult.isTruncated()) .setKeyCount(rawResult.getKeyCount()) .setContinuationToken(getBucketObjectsV2.getContinuationToken()) .setNextContinuationToken(rawResult.getNextContinuationToken()) .setDelimiter(getBucketObjectsV2.getDelimiter()) .setCommonPrefixes(rawResult.getCommonPrefixes()) .build(); } @Override public ListBucketResult getBucketObjects(GetBucketObjects getBucketObjects) throws S3Exception { ListBucketResultRaw rawResult = entityDriver.getBucketObjects(getBucketObjects); List<S3Content> s3Contents = makeContents(rawResult.getS3FileObjectsPaths()); return ListBucketResult.builder() .setMaxKeys(getBucketObjects.getMaxKeys()) .setName(getBucketObjects.getBucket()) .setContents(s3Contents) .setPrefix(getBucketObjects.getPrefix()) .setIsTruncated(rawResult.isTruncated()) .setDelimiter(getBucketObjects.getDelimiter()) .setCommonPrefixes(rawResult.getCommonPrefixes()) .setMarker(getBucketObjects.getMarker()) .setNextMarker(rawResult.isTruncated() ? rawResult.getNextMarker() : null) .build(); } @Override public GetBucketsResult getBuckets(S3User s3User) throws S3Exception { List<Pair<S3FileBucketPath, String>> buckets = entityDriver.getBuckets(s3User); ExecutorService executorService = Executors.newFixedThreadPool(3); List<Future<Pair<S3FileBucketPath, Pair<AccessControlPolicy, String>>>> bucketsWithAclFutures = buckets.stream() .map(pair -> executorService.submit(() -> { AccessControlPolicy acl = entityLockDriver.readMeta( pair.getFirst().getPathToBucket(), pair.getFirst().getPathToBucketMetadataFolder(), pair.getFirst().getPathToBucketAclFile(), () -> aclDriver.getBucketAcl(pair.getFirst()) ); return Pair.of(pair.getFirst(), Pair.of(acl, pair.getSecond())); })) .collect(Collectors.toList()); List<Pair<String, String>> bucketsFiltered = new ArrayList<>(); for (Future<Pair<S3FileBucketPath, Pair<AccessControlPolicy, String>>> bucketWithAclFuture : bucketsWithAclFutures) { try { Pair<S3FileBucketPath, Pair<AccessControlPolicy, String>> bucketWithAcl = bucketWithAclFuture.get(); AccessControlPolicy acl = bucketWithAcl.getSecond().getFirst(); if (s3User.getCanonicalUserId().equals(acl.getOwner().getId()) && s3User.getAccountName().equals(acl.getOwner().getDisplayName())) { bucketsFiltered.add(Pair.of(bucketWithAcl.getFirst().getBucket(), bucketWithAcl.getSecond().getSecond())); } } catch (InterruptedException | ExecutionException e) { throw S3Exception.INTERNAL_ERROR(e); } } return GetBucketsResult.builder() .setBuckets(bucketsFiltered) .setOwner(Owner.builder() .setDisplayName(s3User.getAccountName()) .setId(s3User.getCanonicalUserId()) .build()) .build(); } @Override public String createMultipartUpload(S3FileObjectPath s3FileObjectPath, S3User s3User) throws S3Exception { String uploadId = DigestUtils.md5Hex(DateTimeUtil.currentDateTime() + new Random().nextLong() + new File(s3FileObjectPath.getPathToObject()).getAbsolutePath()) + "_" + s3User.getAccessKey(); entityLockDriver.createUpload( s3FileObjectPath.getPathToBucket(), s3FileObjectPath.getPathToObjectMetadataFolder(), s3FileObjectPath.getPathToObjectUploadFolder(uploadId), () -> entityDriver.createMultipartUpload(s3FileObjectPath, uploadId) ); return uploadId; } @Override public void abortMultipartUpload(S3FileObjectPath s3FileObjectPath, String uploadId) throws S3Exception { if (uploadId == null) { return; } if (!fileDriver.isFolderExists(s3FileObjectPath.getPathToObjectUploadFolder(uploadId))) { return; } entityLockDriver.deleteUpload( s3FileObjectPath.getPathToBucket(), s3FileObjectPath.getPathToObjectMetadataFolder(), uploadId, () -> entityDriver.abortMultipartUpload(s3FileObjectPath, uploadId) ); } @Override public String putUploadPart(S3FileObjectPath s3FileObjectPath, String uploadId, int partNumber, byte[] bytes) throws S3Exception { String pathToUpload = s3FileObjectPath.getPathToObjectUploadFolder(uploadId); if (!fileDriver.isFolderExists(pathToUpload)) { throw S3Exception.NO_SUCH_UPLOAD(uploadId); } return entityLockDriver.writeUpload( s3FileObjectPath.getPathToBucket(), s3FileObjectPath.getPathToObjectMetadataFolder(), pathToUpload, s3FileObjectPath.getPathToObjectUploadPart(uploadId, partNumber), () -> entityDriver.putUploadPart(s3FileObjectPath, uploadId, partNumber, bytes) ); } @Override public String completeMultipartUpload(S3FileObjectPath s3FileObjectPath, String uploadId, List<Part> parts, S3User s3User) throws S3Exception { if (parts == null || parts.size() == 0) { throw S3Exception.builder("No parts to complete multipart upload") .setStatus(HttpResponseStatus.BAD_REQUEST) .setCode(S3ResponseErrorCodes.INVALID_REQUEST) .setMessage("No parts to complete multipart upload") .build(); } File file = new File(s3FileObjectPath.getPathToObject()); if (!file.exists()) { try { if (!file.createNewFile()) { throw S3Exception.INTERNAL_ERROR("Can't create file : " + s3FileObjectPath.getPathToObject()); } } catch (IOException exception) { throw S3Exception.INTERNAL_ERROR(exception); } } return entityLockDriver.completeUpload( s3FileObjectPath, s3FileObjectPath.getPathToObjectUploadFolder(uploadId), () -> { String eTag = entityDriver.completeMultipartUpload(s3FileObjectPath, uploadId, parts); metadataDriver.putObjectMetadata(s3FileObjectPath, Map.of(), eTag); aclDriver.putObjectAcl(s3FileObjectPath, createDefaultAccessControlPolicy(s3User)); return eTag; } ); } @Override public S3FileObjectPath buildPathToObject(String bucketKeyToObject) { return fileDriver.buildPathToObject(bucketKeyToObject); } private List<S3Content> makeContents(List<S3FileObjectPath> s3FileObjectPaths) { ExecutorService executorService = Executors.newFixedThreadPool(3); List<Future<S3ObjectETag>> s3objectETagFutures = s3FileObjectPaths.stream() .map(s3FileObjectPath -> executorService.submit(() -> { Map<String, String> metaData = entityLockDriver.readMeta( s3FileObjectPath.getPathToBucket(), s3FileObjectPath.getPathToObjectMetadataFolder(), s3FileObjectPath.getPathToObjectMetaFile(), () -> metadataDriver.getObjectMetadata(s3FileObjectPath) ); return new S3ObjectETag(metaData.get(FileMetadataDriver.ETAG), s3FileObjectPath); })) .collect(Collectors.toList()); List<S3ObjectETag> s3ObjectETags = new ArrayList<>(); for (Future<S3ObjectETag> s3ObjectETagFuture : s3objectETagFutures) { try { s3ObjectETags.add(s3ObjectETagFuture.get()); } catch (InterruptedException | ExecutionException e) { throw S3Exception.INTERNAL_ERROR(e); } } List<Future<S3Content>> s3ContentFutures = s3ObjectETags.stream() .map(s3ObjectETag -> executorService.submit(() -> S3Content.builder() .setETag("\"" + s3ObjectETag.getETag() + "\"") .setKey(s3ObjectETag.getS3FileObjectPath().getKey()) .setLastModified(DateTimeUtil.parseDateTimeISO(s3ObjectETag.getFile())) .setOwner(entityLockDriver.readMeta( s3ObjectETag.getS3FileObjectPath().getPathToBucket(), s3ObjectETag.getS3FileObjectPath().getPathToObjectMetadataFolder(), s3ObjectETag.getS3FileObjectPath().getPathToObjectAclFile(), () -> aclDriver.getObjectAcl(s3ObjectETag.getS3FileObjectPath()).getOwner())) .setSize(s3ObjectETag.getFile().length()) .setStorageClass("STANDART") .build())) .collect(Collectors.toList()); List<S3Content> s3Contents = new ArrayList<>(); for (Future<S3Content> s3ContentFuture : s3ContentFutures) { try { s3Contents.add(s3ContentFuture.get()); } catch (InterruptedException | ExecutionException e) { throw S3Exception.INTERNAL_ERROR(e); } } executorService.shutdown(); return s3Contents; } private AccessControlPolicy createDefaultAccessControlPolicy(S3User s3User) { return AccessControlPolicy.builder() .setOwner(Owner.builder() .setDisplayName(s3User.getAccountName()) .setId(s3User.getCanonicalUserId()) .build()) .setAccessControlList(Collections.singletonList( Grant.builder() .setGrantee(Grantee.builder() .setDisplayName(s3User.getAccountName()) .setId(s3User.getCanonicalUserId()) .setType("Canonical User") .build()) .setPermission(Permission.FULL_CONTROL) .build() )) .build(); } private boolean match(String first, String second) { if (first.length() == 0 && second.length() == 0) return true; if (first.length() > 1 && first.charAt(0) == '*' && second.length() == 0) return false; if ((first.length() != 0 && second.length() != 0 && first.charAt(0) == second.charAt(0))) return match(first.substring(1), second.substring(1)); if (first.length() > 0 && first.charAt(0) == '*') return match(first.substring(1), second) || match(first, second.substring(1)); return false; } } <file_sep>/src/main/java/com/thorinhood/data/S3Content.java package com.thorinhood.data; import com.thorinhood.utils.XmlObject; import org.w3c.dom.Document; import org.w3c.dom.Element; public class S3Content implements XmlObject { private String key; private String lastModified; private String eTag; private long size; private Owner owner; private String storageClass; public static Builder builder() { return new Builder(); } private S3Content() { } @Override public Element buildXmlRootNode(Document doc) { return createElement(doc, "Contents", createTextElement(doc, "Key", key), createTextElement(doc, "LastModified", lastModified), createTextElement(doc, "ETag", eTag), createTextElement(doc, "Size", String.valueOf(size)), createTextElement(doc, "StorageClass", storageClass), owner != null ? owner.buildXmlRootNode(doc) : null); } public static class Builder { private final S3Content s3Content; public Builder() { s3Content = new S3Content(); } public Builder setKey(String key) { s3Content.key = key; return this; } public Builder setLastModified(String lastModified) { s3Content.lastModified = lastModified; return this; } public Builder setETag(String eTag) { s3Content.eTag = eTag; return this; } public Builder setSize(long size) { s3Content.size = size; return this; } public Builder setOwner(Owner owner) { s3Content.owner = owner; return this; } public Builder setStorageClass(String storageClass) { s3Content.storageClass = storageClass; return this; } public S3Content build() { return s3Content; } } } <file_sep>/src/main/java/com/thorinhood/data/list/request/GetBucketObjects.java package com.thorinhood.data.list.request; public class GetBucketObjects { private String bucket; private String marker; private int maxKeys = 1000; private String prefix; private String delimiter; public static Builder builder() { return new Builder(); } private GetBucketObjects() { } public String getBucket() { return bucket; } public String getMarker() { return marker; } public int getMaxKeys() { return maxKeys; } public String getPrefix() { return prefix; } public String getDelimiter() { return delimiter; } public static class Builder { private final GetBucketObjects getBucketObjects; public Builder() { getBucketObjects = new GetBucketObjects(); } public Builder setBucket(String bucket) { getBucketObjects.bucket = bucket; return this; } public Builder setMarker(String marker) { getBucketObjects.marker = marker; return this; } public Builder setPrefix(String prefix) { getBucketObjects.prefix = prefix; return this; } public Builder setDelimiter(String delimiter) { getBucketObjects.delimiter = delimiter; return this; } public Builder setMaxKeys(int maxKeys) { getBucketObjects.maxKeys = maxKeys; return this; } public GetBucketObjects build() { return getBucketObjects; } } } <file_sep>/src/main/java/com/thorinhood/processors/lists/ListObjectsV2Processor.java package com.thorinhood.processors.lists; import com.thorinhood.data.list.request.GetBucketObjectsV2; import com.thorinhood.data.list.eventual.ListBucketV2Result; import com.thorinhood.drivers.main.S3Driver; import com.thorinhood.processors.Processor; import com.thorinhood.utils.DateTimeUtil; import com.thorinhood.utils.ParsedRequest; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaderNames; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.function.Function; import static io.netty.handler.codec.http.HttpResponseStatus.OK; public class ListObjectsV2Processor extends Processor { private static final Logger log = LogManager.getLogger(ListObjectsV2Processor.class); public ListObjectsV2Processor(S3Driver s3Driver) { super(s3Driver); } @Override protected void processInner(ChannelHandlerContext context, FullHttpRequest request, ParsedRequest parsedRequest, Object... arguments) throws Exception { checkRequestPermissions(parsedRequest, "s3:ListBucket", true); GetBucketObjectsV2 getBucketObjectsV2 = GetBucketObjectsV2.builder() .setBucket(parsedRequest.getS3BucketPath().getBucket()) .setPrefix(parsedRequest.getQueryParam("prefix", "", Function.identity())) .setMaxKeys(parsedRequest.getQueryParam("max-keys", 1000, Integer::valueOf)) .setStartAfter(parsedRequest.getQueryParam("start-after", null, Function.identity())) .setContinuationToken(parsedRequest.getQueryParam("continuation-token", null, Function.identity())) .setDelimiter(parsedRequest.getQueryParam("delimiter", null, delimiter -> delimiter.equals("") ? null : delimiter)) .build(); ListBucketV2Result listBucketV2Result = S3_DRIVER.getBucketObjectsV2(parsedRequest.getS3BucketPath(), getBucketObjectsV2); String xml = listBucketV2Result.buildXmlText(); sendResponse(context, request, OK, response -> { response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/xml"); response.headers().set("Date", DateTimeUtil.currentDateTime()); }, xml); } @Override protected Logger getLogger() { return log; } } <file_sep>/src/main/java/com/thorinhood/drivers/S3Runnable.java package com.thorinhood.drivers; import com.thorinhood.exceptions.S3Exception; import java.io.IOException; public interface S3Runnable { void run() throws S3Exception, IOException; }<file_sep>/src/main/java/com/thorinhood/data/policy/AWSPrincipal.java package com.thorinhood.data.policy; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; public class AWSPrincipal { @JsonProperty(value = "AWS", required = true) @JsonFormat(with = { JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, JsonFormat.Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED }) private List<String> aws; public AWSPrincipal() {} public AWSPrincipal(List<String> aws) { this.aws = aws; } public List<String> getAWS() { return aws; } } <file_sep>/src/main/java/com/thorinhood/processors/policies/GetBucketPolicyProcessor.java package com.thorinhood.processors.policies; import com.thorinhood.data.requests.S3ResponseErrorCodes; import com.thorinhood.drivers.main.S3Driver; import com.thorinhood.exceptions.S3Exception; import com.thorinhood.utils.DateTimeUtil; import com.thorinhood.utils.ParsedRequest; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpUtil; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.Optional; import static io.netty.handler.codec.http.HttpResponseStatus.OK; public class GetBucketPolicyProcessor extends BucketPolicyProcessor { private static final Logger log = LogManager.getLogger(PutBucketPolicyProcessor.class); public GetBucketPolicyProcessor(S3Driver s3Driver) { super(s3Driver); } @Override protected void processInner(ChannelHandlerContext context, FullHttpRequest request, ParsedRequest parsedRequest, Object... arguments) throws Exception { checkRequestPermissions(parsedRequest, true); Optional<byte[]> bucketPolicy = S3_DRIVER.getBucketPolicyBytes(parsedRequest.getS3BucketPath()); if (bucketPolicy.isEmpty()) { throw S3Exception.builder("The bucket policy does not exist") .setStatus(HttpResponseStatus.NOT_FOUND) .setCode(S3ResponseErrorCodes.INVALID_REQUEST) .setMessage("The bucket policy does not exist") .build(); } sendResponse(context, request, OK, response -> { response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json"); response.headers().set("Date", DateTimeUtil.currentDateTime()); }, bucketPolicy.get()); } @Override protected Logger getLogger() { return log; } } <file_sep>/src/main/java/com/thorinhood/data/s3object/HasETag.java package com.thorinhood.data.s3object; public interface HasETag { HasFile setETag(String ETag); String getETag(); } <file_sep>/src/test/java/com/thorinhood/utils/SdkUtil.java package com.thorinhood.utils; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.client.config.ClientAsyncConfiguration; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.retry.conditions.RetryCondition; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.*; import java.net.URI; import java.time.Duration; public class SdkUtil { public static S3AsyncClient buildAsync(int port, Region region, boolean chunked, String accessKey, String secretKey) { S3AsyncClientBuilder s3 = S3AsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey))) .httpClient(NettyNioAsyncHttpClient.builder().readTimeout(Duration.ofSeconds(240)).build()) .endpointOverride(URI.create("http://localhost:" + port)) .region(region); if (!chunked) { s3.serviceConfiguration(S3Configuration.builder() .chunkedEncodingEnabled(false) .build()); } return s3.build(); } public static S3Client build(int port, Region region, boolean chunked, String accessKey, String secretKey) { S3ClientBuilder s3 = S3Client.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey))) .endpointOverride(URI.create("http://localhost:" + port)) .region(region); if (!chunked) { s3.serviceConfiguration(S3Configuration.builder() .chunkedEncodingEnabled(false) .build()); } return s3.build(); } } <file_sep>/src/test/java/com/thorinhood/list/ListObjectsV2Test.java package com.thorinhood.list; import com.thorinhood.BaseTest; import com.thorinhood.data.requests.S3ResponseErrorCodes; import io.netty.handler.codec.http.HttpResponseStatus; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.*; import java.util.List; import java.util.Map; public class ListObjectsV2Test extends BaseTest { public ListObjectsV2Test() { super("testS3Java", 9999); } @Test public void listObjectsV2Simple() { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); String content = "hello, s3!!!"; putObjectRaw(s3, "bucket", "folder1/folder2/file.txt", content, null); putObjectRaw(s3, "bucket", "folder1/file.txt", content, Map.of("key", "value")); putObjectRaw(s3, "bucket", "file.txt", content, null); List<S3Object> expected = List.of( buildS3Object("folder1/folder2/file.txt", ROOT_USER, content), buildS3Object("folder1/file.txt", ROOT_USER, content), buildS3Object("file.txt", ROOT_USER, content)); listObjects(s3, "bucket", null, null, null, null, expected); } @Test public void listObjectsV2Unauthorized() { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); String content = "hello, s3!!!"; putObjectRaw(s3, "bucket", "folder1/folder2/file.txt", content, null); putObjectRaw(s3, "bucket", "folder1/file.txt", content, Map.of("key", "value")); putObjectRaw(s3, "bucket", "file.txt", content, null); List<S3Object> expected = List.of( buildS3Object("folder1/folder2/file.txt", ROOT_USER, content), buildS3Object("folder1/file.txt", ROOT_USER, content), buildS3Object("file.txt", ROOT_USER, content) ); S3Client s3NotAuth = getS3Client(false, NOT_AUTH_ROOT_USER.getAccessKey(), NOT_AUTH_ROOT_USER.getSecretKey()); assertException(HttpResponseStatus.FORBIDDEN.code(), S3ResponseErrorCodes.ACCESS_DENIED, () -> { listObjects(s3NotAuth, "bucket", null, null, null, null, expected); }); } @Test public void listObjectsV2AnotherUser() { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); String content = "hello, s3!!!"; putObjectRaw(s3, "bucket", "folder1/folder2/file.txt", content, null); putObjectRaw(s3, "bucket", "folder1/file.txt", content, Map.of("key", "value")); putObjectRaw(s3, "bucket", "file.txt", content, null); List<S3Object> expected = List.of( buildS3Object("folder1/folder2/file.txt", ROOT_USER, content), buildS3Object("folder1/file.txt", ROOT_USER, content), buildS3Object("file.txt", ROOT_USER, content) ); S3Client s3Client2 = getS3Client(false, ROOT_USER_2.getAccessKey(), ROOT_USER_2.getSecretKey()); assertException(HttpResponseStatus.FORBIDDEN.code(), S3ResponseErrorCodes.ACCESS_DENIED, () -> { listObjects(s3Client2, "bucket", null, null, null, null, expected); }); } @Test public void listObjectsV2MaxKeys() { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); String content = "hello, s3!!!"; putObjectRaw(s3, "bucket", "folder1/folder2/file.txt", content, null); putObjectRaw(s3, "bucket", "folder1/file.txt", content, Map.of("key", "value")); putObjectRaw(s3, "bucket", "file.txt", content, null); List<S3Object> expected = List.of( buildS3Object("folder1/file.txt", ROOT_USER, content), buildS3Object("file.txt", ROOT_USER, content) ); s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); listObjects(s3, "bucket", 2, null, null, null, expected); } @Test public void listObjectsV2Prefix() { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); String content = "hello, s3!!!"; putObjectRaw(s3, "bucket", "folder1/folder2/file.txt", content, null); putObjectRaw(s3, "bucket", "folder1/file.txt", content, Map.of("key", "value")); putObjectRaw(s3, "bucket", "file.txt", content, null); putObjectRaw(s3, "bucket", "afile.txt", content, null); putObjectRaw(s3, "bucket", "file/dfile.txt", content, null); List<S3Object> expected = List.of( buildS3Object("file/dfile.txt", ROOT_USER, content), buildS3Object("file.txt", ROOT_USER, content) ); s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); listObjects(s3, "bucket", null, "file", null, null, expected); } @Test public void listObjectsV2StartAfter() { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); String content = "hello, s3!!!"; putObjectRaw(s3, "bucket", "folder1/folder2/file.txt", content, null); putObjectRaw(s3, "bucket", "folder1/file.txt", content, Map.of("key", "value")); putObjectRaw(s3, "bucket", "file.txt", content, null); putObjectRaw(s3, "bucket", "afile.txt", content, null); putObjectRaw(s3, "bucket", "file/dfile.txt", content, null); List<S3Object> expected = List.of( buildS3Object("folder1/folder2/file.txt", ROOT_USER, content), buildS3Object("folder1/file.txt", ROOT_USER, content) ); s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); listObjects(s3, "bucket", null, null, "folder1", null, expected); } @Test public void listObjectsV2ContinuousToken() { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); String content = "hello, s3!!!"; putObjectRaw(s3, "bucket", "folder1/folder2/file.txt", content, null); putObjectRaw(s3, "bucket", "folder1/file.txt", content, Map.of("key", "value")); putObjectRaw(s3, "bucket", "file.txt", content, null); putObjectRaw(s3, "bucket", "afile.txt", content, null); putObjectRaw(s3, "bucket", "file/dfile.txt", content, null); s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); String nextContinuousToken; List<S3Object> expected = List.of( buildS3Object("afile.txt", ROOT_USER, content), buildS3Object("file.txt", ROOT_USER, content) ); nextContinuousToken = listObjects(s3, "bucket", 2, null, null, null, expected); Assertions.assertNotNull(nextContinuousToken); expected = List.of( buildS3Object("file/dfile.txt", ROOT_USER, content), buildS3Object("folder1/file.txt", ROOT_USER, content) ); nextContinuousToken = listObjects(s3, "bucket", 2, null, null, nextContinuousToken, expected); Assertions.assertNotNull(nextContinuousToken); expected = List.of( buildS3Object("folder1/folder2/file.txt", ROOT_USER, content) ); nextContinuousToken = listObjects(s3, "bucket", 2, null, null, nextContinuousToken, expected); Assertions.assertNull(nextContinuousToken); } public String listObjects(S3Client s3, String bucket, Integer maxKeys, String prefix, String startAfter, String continuousToken, List<S3Object> expected) { ListObjectsV2Request.Builder request = ListObjectsV2Request.builder() .bucket(bucket); if (maxKeys != null) { request.maxKeys(maxKeys); } request.prefix(prefix) .startAfter(startAfter) .continuationToken(continuousToken); ListObjectsV2Response response = s3.listObjectsV2(request.build()); Assertions.assertEquals(maxKeys != null ? maxKeys : 1000, response.maxKeys()); Assertions.assertEquals(continuousToken, response.continuationToken()); Assertions.assertEquals(prefix == null ? "" : prefix, response.prefix()); Assertions.assertEquals(bucket, response.name()); Assertions.assertEquals(expected.size(), response.contents().size()); for (S3Object expectedS3Object : expected) { Assertions.assertTrue(response.contents().stream() .anyMatch(actualS3Object -> equalsS3Objects(expectedS3Object, actualS3Object))); } return response.nextContinuationToken(); } } <file_sep>/src/main/java/com/thorinhood/chunks/ChunkInfo.java package com.thorinhood.chunks; public class ChunkInfo { private final int chunkSize; private final String signature; public ChunkInfo(int chunkSize, String signature) { this.chunkSize = chunkSize; this.signature = signature; } public int getChunkSize() { return chunkSize; } public String getSignature() { return signature; } } <file_sep>/src/main/java/com/thorinhood/chunks/ChunkReader.java package com.thorinhood.chunks; import com.thorinhood.data.S3FileObjectPath; import com.thorinhood.data.requests.S3ResponseErrorCodes; import com.thorinhood.exceptions.S3Exception; import com.thorinhood.utils.Credential; import com.thorinhood.utils.ParsedRequest; import com.thorinhood.utils.SignUtil; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; import java.io.ByteArrayInputStream; import java.io.IOException; public class ChunkReader { public static byte[] readChunks(FullHttpRequest request, ParsedRequest parsedRequest) throws S3Exception { String prevSignature = parsedRequest.getSignature(); byte[] result = new byte[parsedRequest.getDecodedContentLength()]; int index = 0; try (ByteArrayInputStream is = new ByteArrayInputStream(parsedRequest.getBytes())) { ChunkInfo chunkInfo = new ChunkInfo(1, null); boolean first = true; while (chunkInfo.getChunkSize() != 0) { chunkInfo = ChunkReader.readInfoChunkLine(is, !first); if (chunkInfo.getChunkSize() != 0) { byte[] chunk = ChunkReader.readChunk(chunkInfo.getChunkSize(), is); checkChunk( parsedRequest.getS3ObjectPath(), chunkInfo.getSignature(), prevSignature, chunk, request, parsedRequest.getCredential(), parsedRequest.getS3User().getSecretKey() ); if (chunkInfo.getChunkSize() >= 0) { System.arraycopy(chunk, 0, result, index, chunkInfo.getChunkSize()); } index += chunkInfo.getChunkSize(); } first = false; prevSignature = chunkInfo.getSignature(); } } catch (IOException exception) { throw S3Exception.INTERNAL_ERROR(exception.getMessage()); } return result; } private static void checkChunk(S3FileObjectPath s3FileObjectPath, String chunkSignature, String prevSignature, byte[] chunkData, FullHttpRequest request, Credential credential, String secretKey) throws S3Exception { String calculatedChunkSignature = SignUtil.calcPayloadSignature(request, credential, prevSignature, chunkData, secretKey); if (!calculatedChunkSignature.equals(chunkSignature)) { throw S3Exception.builder("Chunk signature is incorrect") .setStatus(HttpResponseStatus.BAD_REQUEST) .setCode(S3ResponseErrorCodes.SIGNATURE_DOES_NOT_MATCH) .setMessage("Chunk signature is incorrect") .build(); } } private static ChunkInfo readInfoChunkLine(ByteArrayInputStream bytes, boolean skip) { StringBuilder info = new StringBuilder(); if (skip) { bytes.skip(2); } char b; char prev = (char) bytes.read(); info.append(prev); int chunkSize = 0; while ((b = (char)bytes.read()) != '\n' && (prev != '\r')) { if (b == ';') { chunkSize = Integer.parseInt(info.toString(), 16); info.setLength(0); } else if (b == '=') { info.setLength(0); } else if (b != '\r') { info.append(b); } prev = b; } return new ChunkInfo(chunkSize, info.toString()); } private static byte[] readChunk(int chunkSize, ByteArrayInputStream bytes) { byte[] result = new byte[chunkSize]; bytes.read(result, 0, chunkSize); return result; } } <file_sep>/src/main/java/com/thorinhood/utils/Credential.java package com.thorinhood.utils; import io.netty.handler.codec.http.FullHttpRequest; import java.util.Map; public class Credential { public static final String ACCESS_KEY = "accessKey"; public static final String DATE = "date"; public static final String REGION_NAME = "regionName"; public static final String SERVICE_NAME = "serviceName"; public static final String REQUEST_TYPE = "requestType"; private final Map<String, String> keyValue; private final String credential; private final String credentialWithoutAccessKey; public static Credential parse(FullHttpRequest request) { String credential = getCredential(request); String credentialWithoutAccessKey = getCredentialWithoutAccessKey(credential); Map<String, String> keyValue = extractCredentials(credential); return new Credential(keyValue, credential, credentialWithoutAccessKey); } private Credential(Map<String, String> keyValue, String credential, String credentialWithoutAccessKey) { this.keyValue = keyValue; this.credential = credential; this.credentialWithoutAccessKey = credentialWithoutAccessKey; } private static Map<String, String> extractCredentials(String credential) { int slash = credential.indexOf("/"); int slash2 = credential.indexOf("/", slash + 1); int slash3 = credential.indexOf("/", slash2 + 1); int slash4 = credential.indexOf("/", slash3 + 1); String accessKey = credential.substring(0, slash); String date = credential.substring(slash + 1, slash2); String regionName = credential.substring(slash2 + 1, slash3); String serviceName = credential.substring(slash3 + 1, slash4); String requestType = credential.substring(slash4 + 1); return Map.of( ACCESS_KEY, accessKey, DATE, date, REGION_NAME, regionName, SERVICE_NAME, serviceName, REQUEST_TYPE, requestType ); } private static String getCredentialWithoutAccessKey(String credential) { return credential.substring(credential.indexOf("/") + 1); } private static String getCredential(FullHttpRequest request) { String authorization = request.headers().get("Authorization"); String credential = authorization.substring(authorization.indexOf("Credential=") + "Credential=".length()); credential = credential.substring(0, credential.indexOf(",")).trim(); return credential; } public String getValue(String key) { return keyValue.get(key); } public String getCredential() { return credential; } public String getCredentialWithoutAccessKey() { return credentialWithoutAccessKey; } } <file_sep>/src/main/java/com/thorinhood/drivers/acl/FileAclDriver.java package com.thorinhood.drivers.acl; import com.thorinhood.data.Owner; import com.thorinhood.data.S3FileBucketPath; import com.thorinhood.data.S3FileObjectPath; import com.thorinhood.data.acl.AccessControlPolicy; import com.thorinhood.data.acl.Grant; import com.thorinhood.drivers.FileDriver; import com.thorinhood.exceptions.S3Exception; import com.thorinhood.utils.DateTimeUtil; import com.thorinhood.utils.XmlUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; public class FileAclDriver extends FileDriver implements AclDriver { public FileAclDriver(String baseFolderPath, String configFolderPath, String usersFolderPath) { super(baseFolderPath, configFolderPath, usersFolderPath); } @Override public String putObjectAcl(S3FileObjectPath s3FileObjectPath, AccessControlPolicy acl) throws S3Exception { String pathToObjectAclFile = s3FileObjectPath.getPathToObjectAclFile(); String pathToMetadataFolder = s3FileObjectPath.getPathToObjectMetadataFolder(); String xml = acl.buildXmlText(); File metadataFolder = new File(pathToMetadataFolder); File metaFile = new File(pathToObjectAclFile); Path source = createPreparedTmpFile(metadataFolder.toPath(), metaFile.toPath(), xml.getBytes()); commitFile(source, metaFile.toPath()); return metaFile.exists() ? DateTimeUtil.parseDateTime(metaFile) : null; } @Override public AccessControlPolicy getObjectAcl(S3FileObjectPath s3FileObjectPath) throws S3Exception { return getAcl(s3FileObjectPath, s3FileObjectPath::getPathToObjectAclFile); } @Override public void putBucketAcl(S3FileBucketPath s3FileBucketPath, AccessControlPolicy acl) throws S3Exception { String xml = acl.buildXmlText(); File metadataFolder = new File(s3FileBucketPath.getPathToBucketMetadataFolder()); File metaFile = new File(s3FileBucketPath.getPathToBucketAclFile()); Path source = createPreparedTmpFile(metadataFolder.toPath(), metaFile.toPath(), xml.getBytes()); commitFile(source, metaFile.toPath()); } @Override public AccessControlPolicy getBucketAcl(S3FileBucketPath s3FileBucketPath) throws S3Exception { return getAcl(s3FileBucketPath, s3FileBucketPath::getPathToBucketAclFile); } private AccessControlPolicy getAcl(S3FileBucketPath s3FileBucketPath, Supplier<String> pathGetter) throws S3Exception { String pathToAclFile = pathGetter.get(); File file = new File(pathToAclFile); if (!file.exists()) { throw S3Exception.INTERNAL_ERROR("Can't find acl file : " + pathToAclFile); } byte[] bytes = null; try { bytes = new FileInputStream(file).readAllBytes(); } catch (IOException exception) { throw S3Exception.INTERNAL_ERROR(exception); } Document document = XmlUtil.parseXmlFromBytes(bytes); return AccessControlPolicy.buildFromNode(document.getDocumentElement()); } public AccessControlPolicy parseFromBytes(byte[] bytes) throws S3Exception { Document document = XmlUtil.parseXmlFromBytes(bytes); Element accessControlPolicyNode = (Element) document.getElementsByTagName("AccessControlPolicy").item(0); AccessControlPolicy.Builder aclBuilder = AccessControlPolicy.builder(); aclBuilder.setXmlns(accessControlPolicyNode.getAttributes().getNamedItem("xmlns").getNodeValue()); Owner owner = Owner.buildFromNode(accessControlPolicyNode.getElementsByTagName("Owner").item(0)); aclBuilder.setOwner(owner); List<Grant> grantList = new ArrayList<>(); Node grants = accessControlPolicyNode.getElementsByTagName("AccessControlList").item(0); for (int i = 0; i < grants.getChildNodes().getLength(); i++) { Grant grant = Grant.buildFromNode(grants.getChildNodes().item(i)); grantList.add(grant); } aclBuilder.setAccessControlList(grantList); return aclBuilder.build(); } } <file_sep>/src/main/java/com/thorinhood/drivers/S3Supplier.java package com.thorinhood.drivers; import com.thorinhood.exceptions.S3Exception; import java.io.IOException; public interface S3Supplier<T> { T get() throws S3Exception, IOException; } <file_sep>/src/main/java/com/thorinhood/data/acl/AccessControlPolicy.java package com.thorinhood.data.acl; import com.thorinhood.data.Owner; import com.thorinhood.utils.XmlObject; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; public class AccessControlPolicy implements Serializable, XmlObject { private Owner owner; private List<Grant> accessControlList; private String xmlns = "http://s3.amazonaws.com/doc/2006-03-01/"; public static AccessControlPolicy buildFromNode(Node node) { return new Builder().setFromRootNode(node).build(); } public static Builder builder() { return new Builder(); } private AccessControlPolicy() { } public Owner getOwner() { return owner; } public List<Grant> getAccessControlList() { return accessControlList; } public String getXmlns() { return xmlns; } @Override public Element buildXmlRootNode(Document doc) { Element accessControlListNode = doc.createElement("AccessControlList"); if (accessControlList != null) { accessControlList.forEach(grant -> { accessControlListNode.appendChild(grant.buildXmlRootNode(doc)); }); } Element root = createElement(doc, "AccessControlPolicy", owner != null ? owner.buildXmlRootNode(doc) : null, accessControlList != null && !accessControlList.isEmpty() ? accessControlListNode : null); return appendAttributes(root, Map.of( "xmlns", xmlns )); } public static class Builder { private final AccessControlPolicy accessControlPolicy; public Builder() { accessControlPolicy = new AccessControlPolicy(); } public Builder setXmlns(String xmlns) { accessControlPolicy.xmlns = xmlns; return this; } public Builder setOwner(Owner owner) { accessControlPolicy.owner = owner; return this; } public Builder setAccessControlList(List<Grant> accessControlList) { accessControlPolicy.accessControlList = accessControlList; return this; } public Builder setFromRootNode(Node node) { for (int i = 0; i < node.getChildNodes().getLength(); i++) { Node child = node.getChildNodes().item(i); if (child.getNodeName().equals("Owner")) { accessControlPolicy.owner = Owner.buildFromNode(child); } else if (child.getNodeName().equals("AccessControlList")) { List<Grant> grants = new ArrayList<>(); for (int j = 0; j < child.getChildNodes().getLength(); j++) { if (child.getChildNodes().item(j).getNodeName().equals("Grant")) { grants.add(Grant.buildFromNode(child.getChildNodes().item(j))); } } accessControlPolicy.accessControlList = grants; } } accessControlPolicy.xmlns = node.getAttributes().getNamedItem("xmlns").getNodeValue(); return this; } public AccessControlPolicy build() { return accessControlPolicy; } } } <file_sep>/src/test/java/com/thorinhood/acl/AclTest.java package com.thorinhood.acl; import com.thorinhood.BaseTest; import com.thorinhood.data.requests.S3ResponseErrorCodes; import io.netty.handler.codec.http.HttpResponseStatus; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.*; import java.io.IOException; import java.util.List; public class AclTest extends BaseTest { public AclTest() { super("testS3Java", 9999); } @Test public void putAndGetBucketAcl() throws IOException { S3Client s3Client = getS3Client(true, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); S3Client s3Client2 = getS3Client(true, ROOT_USER_2.getAccessKey(), ROOT_USER_2.getSecretKey()); createBucketRaw(s3Client, "bucket"); String content = createContent(500); assertException(HttpResponseStatus.FORBIDDEN.code(), S3ResponseErrorCodes.ACCESS_DENIED, () -> putObjectRaw(s3Client2, "bucket", "file.txt", content, null)); AccessControlPolicy acl = AccessControlPolicy.builder() .owner(Owner.builder() .displayName(ROOT_USER.getAccountName()) .id(ROOT_USER.getCanonicalUserId()) .build()) .grants(Grant.builder() .permission("WRITE") .grantee(Grantee.builder() .displayName(ROOT_USER_2.getAccountName()) .id(ROOT_USER_2.getCanonicalUserId()) .type(Type.CANONICAL_USER) .build()) .build(), Grant.builder() .permission("FULL_CONTROL") .grantee(Grantee.builder() .displayName(ROOT_USER.getAccountName()) .id(ROOT_USER.getCanonicalUserId()) .type(Type.CANONICAL_USER) .build()) .build()) .build(); s3Client.putBucketAcl(PutBucketAclRequest.builder() .bucket("bucket") .accessControlPolicy(acl) .build()); putObjectRaw(s3Client2, "bucket", "file.txt", content, null); checkObject("bucket", null, "file.txt", content, null); GetBucketAclResponse response = s3Client.getBucketAcl(GetBucketAclRequest.builder() .bucket("bucket") .build()); assertAcl(acl.grants(), acl.owner(), response.grants(), response.owner()); } @Test public void putAndGetObjectAcl() { S3Client s3Client = getS3Client(true, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); S3Client s3Client2 = getS3Client(true, ROOT_USER_2.getAccessKey(), ROOT_USER_2.getSecretKey()); createBucketRaw(s3Client, "bucket"); String content = createContent(500); putObjectRaw(s3Client, "bucket", "file.txt", content, null); assertException(HttpResponseStatus.FORBIDDEN.code(), S3ResponseErrorCodes.ACCESS_DENIED, () -> getObject(s3Client2, "bucket", "file.txt", content, null)); AccessControlPolicy acl = AccessControlPolicy.builder() .owner(Owner.builder() .displayName(ROOT_USER.getAccountName()) .id(ROOT_USER.getCanonicalUserId()) .build()) .grants(Grant.builder() .permission("READ") .grantee(Grantee.builder() .displayName(ROOT_USER_2.getAccountName()) .id(ROOT_USER_2.getCanonicalUserId()) .type(Type.CANONICAL_USER) .build()) .build(), Grant.builder() .permission("FULL_CONTROL") .grantee(Grantee.builder() .displayName(ROOT_USER.getAccountName()) .id(ROOT_USER.getCanonicalUserId()) .type(Type.CANONICAL_USER) .build()) .build()) .build(); s3Client.putObjectAcl(PutObjectAclRequest.builder() .bucket("bucket") .key("file.txt") .accessControlPolicy(acl) .build()); getObject(s3Client2, "bucket", "file.txt", content, null); GetObjectAclResponse response = s3Client.getObjectAcl(GetObjectAclRequest.builder() .bucket("bucket") .key("file.txt") .build()); assertAcl(acl.grants(), acl.owner(), response.grants(), response.owner()); } private void assertAcl(List<Grant> expectedGrants, Owner expectedOwner, List<Grant> actualGrants, Owner actualOwner) { Assertions.assertEquals(expectedOwner.id(), actualOwner.id()); Assertions.assertEquals(expectedOwner.displayName(), actualOwner.displayName()); Assertions.assertEquals(expectedGrants.size(), actualGrants.size()); for (Grant expectedGrant : expectedGrants) { Assertions.assertTrue(actualGrants.stream() .anyMatch(actualGrant -> equalsGrants(expectedGrant, actualGrant))); } } private boolean equalsGrants(Grant expectedGrant, Grant actualGrant) { return expectedGrant.grantee().id().equals(actualGrant.grantee().id()) && expectedGrant.grantee().displayName().equals(actualGrant.grantee().displayName()) && expectedGrant.permission().equals(actualGrant.permission()); } } <file_sep>/src/test/java/com/thorinhood/list/ListObjectsTest.java package com.thorinhood.list; import com.thorinhood.BaseTest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.*; import java.util.List; import java.util.Map; public class ListObjectsTest extends BaseTest { public ListObjectsTest() { super("testS3Java", 9999); } @Test public void withCommonPrefixes() { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); String content = "hello, s3!!!"; putObjectRaw(s3, "bucket", "folder1/folder2/file.txt", content, null); putObjectRaw(s3, "bucket", "folder1/file.txt", content, Map.of("key", "value")); putObjectRaw(s3, "bucket", "file.txt", content, null); String nextMarker = listObjects(s3, "bucket", 1000, "", "/", null, "folder1/", false, List.of( buildS3Object("file.txt", ROOT_USER, content)), List.of(CommonPrefix.builder().prefix("folder1/").build())); nextMarker = listObjects(s3, "bucket", 1000, nextMarker, "/", null, "folder2/", false, List.of(buildS3Object("folder1/file.txt", ROOT_USER, content)), List.of(CommonPrefix.builder().prefix("folder1/folder2/").build())); listObjects(s3, "bucket", 1000, nextMarker, "/", null, null, false, List.of(buildS3Object("folder1/folder2/file.txt", ROOT_USER, content)), List.of()); } @Test public void simpleListObjects() { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); String content = "hello, s3!!!"; putObjectRaw(s3, "bucket", "folder1/folder2/file.txt", content, null); putObjectRaw(s3, "bucket", "folder1/file.txt", content, Map.of("key", "value")); putObjectRaw(s3, "bucket", "file.txt", content, null); listObjects(s3, "bucket", 1000, "", null, null, null, false, List.of( buildS3Object("file.txt", ROOT_USER, content), buildS3Object("folder1/folder2/file.txt", ROOT_USER, content), buildS3Object("folder1/file.txt", ROOT_USER, content)), List.of()); listObjects(s3, "bucket", 1, "", null, null, null, true, List.of(buildS3Object("file.txt", ROOT_USER, content)), List.of()); } public String listObjects(S3Client s3, String bucket, Integer maxKeys, String prefix, String delimeter, String marker, String nextMarker, boolean isTruncated, List<S3Object> expectedContents, List<CommonPrefix> expectedCommonPrefixes) { ListObjectsRequest.Builder request = ListObjectsRequest.builder() .bucket(bucket); if (maxKeys != null) { request.maxKeys(maxKeys); } request.prefix(prefix); if (delimeter != null) { request.delimiter(delimeter); } if (marker != null) { request.marker(marker); } ListObjectsResponse response = s3.listObjects(request.build()); Assertions.assertEquals(isTruncated, response.isTruncated()); Assertions.assertEquals(maxKeys != null ? maxKeys : 1000, response.maxKeys()); Assertions.assertEquals(marker, response.marker()); Assertions.assertEquals(prefix != null ? prefix : "", response.prefix()); Assertions.assertEquals(bucket, response.name()); Assertions.assertEquals(expectedContents.size(), response.contents().size()); Assertions.assertEquals(expectedCommonPrefixes.size(), response.commonPrefixes().size()); for (S3Object expectedS3Object : expectedContents) { Assertions.assertTrue(response.contents().stream() .anyMatch(actualS3Object -> equalsS3Objects(expectedS3Object, actualS3Object))); } for (CommonPrefix commonPrefix : expectedCommonPrefixes) { Assertions.assertTrue(response.commonPrefixes().stream() .anyMatch(actualCommonPrefix -> actualCommonPrefix.prefix().equals(commonPrefix.prefix()))); } return response.nextMarker(); } } <file_sep>/src/main/java/com/thorinhood/data/s3object/HasS3Path.java package com.thorinhood.data.s3object; import com.thorinhood.data.S3FileObjectPath; public interface HasS3Path { HasETag setS3Path(S3FileObjectPath s3FileObjectPath); S3FileObjectPath getS3Path(); } <file_sep>/src/main/java/com/thorinhood/data/s3object/HasLastModified.java package com.thorinhood.data.s3object; public interface HasLastModified { HasMetaData setLastModified(String lastModified); String getLastModified(); } <file_sep>/src/test/java/com/thorinhood/actions/DeleteObjectTest.java package com.thorinhood.actions; import com.thorinhood.BaseTest; import com.thorinhood.data.requests.S3ResponseErrorCodes; import io.netty.handler.codec.http.HttpResponseStatus; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; import java.io.IOException; import java.util.Map; public class DeleteObjectTest extends BaseTest { public DeleteObjectTest() { super("testS3Java", 9999); } @Test public void deleteObjectSimple() throws IOException { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); putObjectRaw(s3, "bucket", "file.txt", "hello, s3!!!", Map.of("key", "value")); checkObject("bucket", null, "file.txt", "hello, s3!!!", Map.of("key", "value"), true); deleteObject(s3, "bucket", "file.txt"); checkObjectNotExists("bucket", null, "file.txt"); } @Test public void deleteObjectCompositeKey() throws IOException { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); putObjectRaw(s3, "bucket", "folder1/folder2/file.txt", "hello, s3!!!", null); checkObject("bucket", "folder1/folder2", "file.txt", "hello, s3!!!", null, true); deleteObject(s3, "bucket", "folder1/folder2/file.txt"); checkObjectNotExists("bucket", "folder1/folder2", "file.txt"); } @Test public void deleteObjectSimilarFolder() throws IOException { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); putObjectRaw(s3, "bucket", "folder1/file.txt", "hello, s3!!!", null); putObjectRaw(s3, "bucket", "folder1/file2.txt", "hello, s3!!!", null); checkObject("bucket", "folder1", "file.txt", "hello, s3!!!", null, true); checkObject("bucket", "folder1", "file2.txt", "hello, s3!!!", null, true); deleteObject(s3, "bucket", "folder1/file2.txt"); checkObjectNotExists("bucket", "folder1", "file2.txt"); checkObject("bucket", "folder1", "file.txt", "hello, s3!!!", null); } @Test public void deleteObjectSimilarNames() throws IOException { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); putObjectRaw(s3, "bucket", "folder1/file.txt", "hello, s3!!!", null); putObjectRaw(s3, "bucket", "folder2/file.txt", "hello, s3!!!", null); checkObject("bucket", "folder1", "file.txt", "hello, s3!!!", null); checkObject("bucket", "folder2", "file.txt", "hello, s3!!!", null); deleteObject(s3, "bucket", "folder1/file.txt"); checkObjectNotExists("bucket", "folder1", "file.txt"); checkObject("bucket", "folder2", "file.txt", "hello, s3!!!", null); } @Test public void deleteObjectDifferentBuckets() throws IOException { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); createBucketRaw(s3, "bucket2"); putObjectRaw(s3, "bucket", "folder1/file.txt", "hello, s3!!!", null); putObjectRaw(s3, "bucket2", "folder1/file.txt", "hello, s3!!!", null); checkObject("bucket", "folder1", "file.txt", "hello, s3!!!", null); checkObject("bucket2", "folder1", "file.txt", "hello, s3!!!", null); deleteObject(s3, "bucket2", "folder1/file.txt"); checkObjectNotExists("bucket2", "folder1", "file.txt"); checkObject("bucket", "folder1", "file.txt", "hello, s3!!!", null); } @Test public void deleteObjectUnauthorizedUser() throws IOException { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); putObjectRaw(s3, "bucket", "folder1/file.txt", "hello, s3!!!", null); checkObject("bucket", "folder1", "file.txt", "hello, s3!!!", null); S3Client s3NotAuth = getS3Client(false, NOT_AUTH_ROOT_USER.getAccessKey(), NOT_AUTH_ROOT_USER.getSecretKey()); assertException(HttpResponseStatus.FORBIDDEN.code(), S3ResponseErrorCodes.ACCESS_DENIED, () -> { deleteObject(s3NotAuth, "bucket", "folder1/file.txt"); }); } @Test public void deleteObjectOtherUser() throws IOException { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); putObjectRaw(s3, "bucket", "folder1/file.txt", "hello, s3!!!", null); checkObject("bucket", "folder1", "file.txt", "hello, s3!!!", null); S3Client s3Client2 = getS3Client(false, ROOT_USER_2.getAccessKey(), ROOT_USER_2.getSecretKey()); assertException(HttpResponseStatus.FORBIDDEN.code(), S3ResponseErrorCodes.ACCESS_DENIED, () -> { deleteObject(s3Client2, "bucket", "folder1/file.txt"); }); } private void deleteObject(S3Client s3, String bucket, String key) { DeleteObjectRequest request = DeleteObjectRequest.builder() .key(key) .bucket(bucket) .build(); s3.deleteObject(request); } } <file_sep>/src/main/java/com/thorinhood/data/policy/Statement.java package com.thorinhood.data.policy; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; public class Statement { public enum EffectType { Allow, Deny; } @JsonProperty(value = "Sid") private String sid; @JsonProperty(value = "Effect", required = true) private EffectType effect; @JsonProperty(value = "Principal", required = true) private AWSPrincipal principle; @JsonProperty(value = "Action", required = true) @JsonFormat(with = { JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, JsonFormat.Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED }) private List<String> action; @JsonProperty(value = "Resource", required = true) @JsonFormat(with = { JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, JsonFormat.Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED }) private List<String> resource; public Statement() { } public Statement(String sid, EffectType effect, AWSPrincipal principle, List<String> action, List<String> resource) { this.sid = sid; this.effect = effect; this.principle = principle; this.action = action; this.resource = resource; } public String getSid() { return sid; } public EffectType getEffect() { return effect; } public AWSPrincipal getPrinciple() { return principle; } public List<String> getAction() { return action; } public List<String> getResource() { return resource; } } <file_sep>/src/main/java/com/thorinhood/processors/selectors/IfUnmodifiedSince.java package com.thorinhood.processors.selectors; import com.thorinhood.data.requests.S3ResponseErrorCodes; import com.thorinhood.exceptions.S3Exception; import io.netty.handler.codec.http.HttpResponseStatus; import java.util.Date; public class IfUnmodifiedSince implements Selector<Date> { @Override public void check(Date actual, Date expected) throws S3Exception { if (actual.after(expected)) { throw S3Exception.builder("IfUnmodifiedSince failed") .setStatus(HttpResponseStatus.NOT_MODIFIED) .setCode(S3ResponseErrorCodes.INVALID_REQUEST) .setMessage("At least one of the pre-conditions you specified did not hold") .build(); } } } <file_sep>/src/main/java/com/thorinhood/processors/selectors/Selector.java package com.thorinhood.processors.selectors; import com.thorinhood.exceptions.S3Exception; public interface Selector<T> { void check(T actual, T expected) throws S3Exception; } <file_sep>/src/main/java/com/thorinhood/drivers/user/FileUserDriver.java package com.thorinhood.drivers.user; import com.fasterxml.jackson.databind.ObjectMapper; import com.thorinhood.data.S3User; import com.thorinhood.drivers.FileDriver; import com.thorinhood.exceptions.S3Exception; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.io.IOException; import java.util.Optional; public class FileUserDriver extends FileDriver implements UserDriver { private static final Logger log = LogManager.getLogger(FileUserDriver.class); private static final String USER_FILE_NAME = "identity.json"; private final ObjectMapper objectMapper; public FileUserDriver(String baseFolderPath, String configFolderPath, String usersFolderPath) { super(baseFolderPath, configFolderPath, usersFolderPath); this.objectMapper = new ObjectMapper(); } @Override public void addUser(S3User s3User) throws S3Exception { String userFolderPath = USERS_FOLDER_PATH + File.separatorChar + s3User.getAccessKey(); createFolder(userFolderPath); try { objectMapper.writeValue(new File(userFolderPath + File.separatorChar + USER_FILE_NAME), s3User); } catch (IOException exception) { throw S3Exception.INTERNAL_ERROR("Can't create user"); } } @Override public void addUser(String pathToIdentity) throws Exception { File userFile = new File(pathToIdentity); if (!userFile.exists() || !userFile.isFile()) { throw new Exception("Can't find user json : " + pathToIdentity); } S3User s3User; try { s3User = objectMapper.readValue(userFile, S3User.class); } catch (IOException exception) { throw new Exception("Can't parse user json file : " + pathToIdentity); } addUser(s3User); } @Override public Optional<S3User> getS3User(String accessKey) throws S3Exception { String userPath = USERS_FOLDER_PATH + File.separatorChar + accessKey + File.separatorChar + USER_FILE_NAME; File file = new File(userPath); if (!file.exists() || !file.isFile()) { return Optional.empty(); } try { return Optional.of(objectMapper.readValue(new File(userPath), S3User.class)); } catch (IOException exception) { throw S3Exception.INTERNAL_ERROR("Can't get user"); } } @Override public void removeUser(String accessKey) throws S3Exception { String userPath = USERS_FOLDER_PATH + File.separatorChar + accessKey; deleteFolder(userPath); } } <file_sep>/src/main/java/com/thorinhood/processors/Processor.java package com.thorinhood.processors; import com.thorinhood.chunks.ChunkReader; import com.thorinhood.data.S3FileObjectPath; import com.thorinhood.data.S3User; import com.thorinhood.drivers.main.S3Driver; import com.thorinhood.exceptions.S3Exception; import com.thorinhood.exceptions.S3ExceptionFull; import com.thorinhood.utils.ParsedRequest; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.*; import io.netty.util.CharsetUtil; import org.apache.logging.log4j.Logger; import javax.activation.MimetypesFileTypeMap; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Map; import java.util.Optional; import java.util.function.Consumer; import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_0; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; public abstract class Processor { protected final S3Driver S3_DRIVER; protected final String METHOD_NAME; public Processor(S3Driver s3Driver) { this.S3_DRIVER = s3Driver; METHOD_NAME = "s3:" + this.getClass().getSimpleName().substring(0, this.getClass().getSimpleName().indexOf("Processor")); } protected byte[] processChunkedContent(ParsedRequest parsedRequest, FullHttpRequest request) { return ChunkReader.readChunks(request, parsedRequest); } protected void checkRequestPermissions(ParsedRequest request, boolean isBucketAcl) throws S3Exception { checkRequestPermissions(request, METHOD_NAME, isBucketAcl); } protected void checkRequestPermissions(ParsedRequest request, String methodName, boolean isBucketAcl) throws S3Exception { checkRequestPermissions(request.getS3ObjectPathUnsafe(), request.getS3User(), methodName, isBucketAcl); } protected void checkRequestPermissions(S3FileObjectPath s3FileObjectPath, S3User s3User, String methodName, boolean isBucketAcl) throws S3Exception { if (!methodName.equals("s3:CreateBucket")) { S3_DRIVER.isBucketExists(s3FileObjectPath); } boolean aclCheckResult = S3_DRIVER.checkAclPermission(isBucketAcl, s3FileObjectPath, methodName, s3User); Optional<Boolean> policyCheckResult = S3_DRIVER.checkBucketPolicy(s3FileObjectPath, s3FileObjectPath.getKeyUnsafe(), methodName, s3User); if ((policyCheckResult.isPresent() && !policyCheckResult.get()) || (policyCheckResult.isEmpty() && !aclCheckResult)) { throw S3Exception.ACCESS_DENIED(); } } private void wrapProcess(Logger log, ChannelHandlerContext ctx, FullHttpRequest request, ParsedRequest parsedRequest, Process process) { try { process.process(); } catch (S3Exception s3Exception) { sendError(ctx, request, S3ExceptionFull.build(s3Exception, parsedRequest.getS3ObjectPathUnsafe(), "1")); log.error(s3Exception.getMessage(), s3Exception); } catch (Exception exception) { S3Exception s3Exception = S3Exception.INTERNAL_ERROR(exception); sendError(ctx, request, S3ExceptionFull.build(s3Exception, parsedRequest.getS3ObjectPathUnsafe(), "1")); log.error(exception.getMessage(), exception); } } public void sendResponse(ChannelHandlerContext ctx, FullHttpRequest request, HttpResponseStatus httpResponseStatus, Consumer<FullHttpResponse> headersSetter) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, httpResponseStatus); headersSetter.accept(response); sendAndCleanupConnection(ctx, response, request); } public void sendResponse(ChannelHandlerContext ctx, FullHttpRequest request, HttpResponseStatus httpResponseStatus, Consumer<FullHttpResponse> headersSetter, String content) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, httpResponseStatus, Unpooled.copiedBuffer(content, CharsetUtil.UTF_8)); headersSetter.accept(response); HttpUtil.setContentLength(response, response.content().readableBytes()); sendAndCleanupConnection(ctx, response, request); } public void sendResponse(ChannelHandlerContext ctx, FullHttpRequest request, HttpResponseStatus httpResponseStatus, Consumer<FullHttpResponse> headersSetter, byte[] content) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, httpResponseStatus, Unpooled.copiedBuffer(content)); headersSetter.accept(response); HttpUtil.setContentLength(response, response.content().readableBytes()); sendAndCleanupConnection(ctx, response, request); } public static void sendError(ChannelHandlerContext ctx, FullHttpRequest request, S3ExceptionFull s3Exception) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, s3Exception.getStatus(), Unpooled.copiedBuffer(s3Exception.buildXmlText(), CharsetUtil.UTF_8)); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/xml"); HttpUtil.setContentLength(response, response.content().readableBytes()); sendAndCleanupConnection(ctx, response, request); } protected void sendError(ChannelHandlerContext ctx, HttpResponseStatus status, FullHttpRequest request) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8)); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); HttpUtil.setContentLength(response, response.content().readableBytes()); sendAndCleanupConnection(ctx, response, request); } protected void sendResponseWithoutContent(ChannelHandlerContext ctx, HttpResponseStatus status, FullHttpRequest request, Map<String, Object> headers) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status); headers.forEach((header, value) -> response.headers().set(header, value)); HttpUtil.setContentLength(response, 0); sendAndCleanupConnection(ctx, response, request); } protected static void sendAndCleanupConnection(ChannelHandlerContext ctx, FullHttpResponse response, FullHttpRequest request) { final boolean keepAlive = HttpUtil.isKeepAlive(request); if (!keepAlive) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); } else if (request.protocolVersion().equals(HTTP_1_0)) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } ChannelFuture flushPromise = ctx.writeAndFlush(response); if (!keepAlive) { flushPromise.addListener(ChannelFutureListener.CLOSE); } } protected void setContentTypeHeader(HttpResponse response, File file) throws IOException { Path path = file.toPath(); String mimeType = Files.probeContentType(path); if (mimeType == null) { MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap(); mimeType = fileTypeMap.getContentType(file.getName()); if (mimeType == null) { mimeType = "text/plain"; } } response.headers().set(HttpHeaderNames.CONTENT_TYPE, mimeType); } public void process(ChannelHandlerContext context, FullHttpRequest request, ParsedRequest parsedRequest, Object... arguments) { if (!request.decoderResult().isSuccess()) { sendError(context, BAD_REQUEST, request); return; } wrapProcess(getLogger(), context, request, parsedRequest, () -> processInner(context, request, parsedRequest, arguments)); } protected abstract void processInner(ChannelHandlerContext context, FullHttpRequest request, ParsedRequest parsedRequest, Object... arguments) throws Exception; protected abstract Logger getLogger(); } <file_sep>/src/main/java/com/thorinhood/utils/PayloadSignType.java package com.thorinhood.utils; public enum PayloadSignType { CHUNKED("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"), UNSIGNED_PAYLOAD("UNSIGNED-PAYLOAD"), SINGLE_CHUNK(null); private String value; PayloadSignType(String value) { this.value = value; } public String getValue() { return value; } }<file_sep>/src/test/java/com/thorinhood/actions/PutObjectTest.java package com.thorinhood.actions; import com.thorinhood.BaseTest; import com.thorinhood.data.requests.S3ResponseErrorCodes; import io.netty.handler.codec.http.HttpResponseStatus; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; public class PutObjectTest extends BaseTest { public PutObjectTest() { super("testS3Java", 9999); } @Test public void putObjectSimple() throws Exception { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); putObject(s3, "bucket", null, "file.txt", createContent(5242880)); } @Test public void putObjectCompositeKey() throws Exception { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); putObject(s3, "bucket", "folder1/folder2", "file.txt", "hello, s3!!!"); } @Test public void putTwoObjectsCompositeKey() throws Exception { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); putObject(s3, "bucket", "folder1", "file.txt", "hello, s3!!!"); putObject(s3, "bucket", "folder1/folder3", "file.txt", "hello, s3!!!"); checkObject("bucket", "folder1", "file.txt", "hello, s3!!!", null, true); } @Test public void putTwoObjectsInDifferentBuckets() throws Exception { S3Client s3 = getS3Client(false, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); createBucketRaw(s3, "bucket2"); putObject(s3, "bucket", "folder1", "file.txt", "hello, s3!!!"); putObject(s3, "bucket2", "folder1", "file.txt", "hello, s3!!!"); checkObject("bucket", "folder1", "file.txt", "hello, s3!!!", null, true); checkObject("bucket2", "folder1", "file.txt", "hello, s3!!!", null, true); } @Test public void putChunkedFile() throws Exception { S3Client s3 = getS3Client(true, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); String largeContent = createContent(5242880); putObject(s3, "bucket", "folder1", "file.txt", largeContent); putObject(s3, "bucket", "folder1", "file2.txt", "hello, s3, again!!!"); checkObject("bucket", "folder1", "file.txt", largeContent, null, true); checkObject("bucket", "folder1", "file2.txt", "hello, s3, again!!!", null, true); } @Test public void putObjectInWrongBucket() { S3Client s3 = getS3Client(true, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); assertException(HttpResponseStatus.NOT_FOUND.code(), S3ResponseErrorCodes.NO_SUCH_BUCKET, () -> { try { putObject(s3, "bucket2", "folder1", "file.txt", "hello, s3!!!"); } catch (IOException exception) { Assertions.fail(exception); } }); } @Test public void putObjectCyrillicSymbolsInKey() throws Exception { S3Client s3 = getS3Client(true, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); putObject(s3, "bucket", null, "файл.txt", "привет, s3!!!"); } @Test public void putObjectWithMetaData() throws Exception { S3Client s3 = getS3Client(true, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); putObject(s3, "bucket", null, "файл.txt", "привет, s3!!!", Map.of( "key1", "value1", "key2", "value2")); } @Test public void putObjectWithMetaDataRewrite() throws Exception { S3Client s3 = getS3Client(true, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); putObject(s3, "bucket", null, "файл.txt", "привет, s3!!!", Map.of( "key1", "value1", "key2", "value2")); putObject(s3, "bucket", null, "файл.txt", "привет, s3!!!", Map.of( "key1", "value1")); } @Test public void putObjectUnregisterUser() { S3Client s3 = getS3Client(true, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); S3Client s3NotAuth = getS3Client(true, NOT_AUTH_ROOT_USER.getAccessKey(), NOT_AUTH_ROOT_USER.getSecretKey()); assertException(HttpResponseStatus.FORBIDDEN.code(), S3ResponseErrorCodes.ACCESS_DENIED, () -> { try { putObject(s3NotAuth, "bucket", null, "файл.txt", "привет, s3!!!", Map.of( "key1", "value1", "key2", "value2")); } catch (IOException exception) { Assertions.fail(exception); } }); } @Test public void putObjectAnotherUser() { S3Client s3 = getS3Client(true, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); S3Client s3Client2 = getS3Client(true, ROOT_USER_2.getAccessKey(), ROOT_USER_2.getSecretKey()); assertException(HttpResponseStatus.FORBIDDEN.code(), S3ResponseErrorCodes.ACCESS_DENIED, () -> { try { putObject(s3Client2, "bucket", null, "файл.txt", "привет, s3!!!", Map.of( "key1", "value1", "key2", "value2")); } catch (IOException exception) { Assertions.fail(exception); } }); } @Test public void putObjectSeveralRequests() throws Exception { S3Client s3 = getS3Client(true, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); S3AsyncClient s3Async = getS3AsyncClient(true, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3, "bucket"); String firstContent = createContent(5242880); String secondContent = createContent(5242880 * 2); List<String> contents = new ArrayList<>(); for (int i = 0; i < 200; i++) { contents.add(i % 2 == 0 ? firstContent : secondContent); } List<CompletableFuture<PutObjectResponse>> futureList = putObjectAsync(s3Async, "bucket", "folder1/folder2", "file.txt", contents, null); checkPutObjectAsync("bucket", "folder1/folder2", "file.txt", futureList, contents, null); } private void putObject(S3Client s3Client, String bucket, String keyWithoutName, String fileName, String content) throws IOException { putObject(s3Client, bucket, keyWithoutName, fileName, content, null); } private void putObject(S3Client s3Client, String bucket, String keyWithoutName, String fileName, String content, Map<String, String> metadata) throws IOException { PutObjectRequest.Builder request = PutObjectRequest.builder() .bucket(bucket) .key(buildKey(keyWithoutName, fileName)); if (metadata != null) { request.metadata(metadata); } PutObjectResponse response = s3Client.putObject(request.build(), RequestBody.fromString(content)); Assertions.assertEquals(response.eTag(), "\"" + calcETag(content) + "\""); checkObject(bucket, keyWithoutName, fileName, content, metadata, true); } } <file_sep>/src/main/java/com/thorinhood/drivers/FileDriver.java package com.thorinhood.drivers; import com.thorinhood.data.S3FileBucketPath; import com.thorinhood.data.S3FileObjectPath; import com.thorinhood.data.S3FileStatic; import com.thorinhood.data.requests.S3ResponseErrorCodes; import com.thorinhood.exceptions.S3Exception; import io.netty.handler.codec.http.HttpResponseStatus; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.Objects; import java.util.Random; public class FileDriver { private static final Logger log = LogManager.getLogger(FileDriver.class); protected static final String CONFIG_FOLDER_NAME = ".##config"; protected static final String USERS_FOLDER_NAME = "users"; protected final String BASE_FOLDER_PATH; protected final String CONFIG_FOLDER_PATH; protected final String USERS_FOLDER_PATH; protected FileDriver(String baseFolderPath, String configFolderPath, String usersFolderPath) { this.BASE_FOLDER_PATH = baseFolderPath; this.CONFIG_FOLDER_PATH = configFolderPath; this.USERS_FOLDER_PATH = usersFolderPath; } public boolean isConfigFolder(Path path) { return Files.isDirectory(path) && path.getFileName().toString().equals(CONFIG_FOLDER_NAME); } public boolean isMetadataFolder(Path path) { return Files.isDirectory(path) && path.getFileName().toString().startsWith(S3FileStatic.METADATA_FOLDER_PREFIX); } protected boolean isMetadataFile(Path path) { return Files.isRegularFile(path) && isMetadataFolder(path.getParent()); } public boolean isBucket(Path path) { return Files.isDirectory(path) && path.getParent().toString().equals(BASE_FOLDER_PATH); } protected void commitFile(Path source, Path target) throws S3Exception { try { Files.move(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } catch (IOException exception) { throw S3Exception.INTERNAL_ERROR(exception); } } protected Path createPreparedTmpFile(Path tmpFolder, Path file, byte[] bytes) { File tmpFile = new File(tmpFolder.toAbsolutePath().toString() + File.separatorChar + file.getFileName().toString() + "." + new Random().nextLong()); while (tmpFile.exists()) { tmpFile = new File(tmpFolder.toAbsolutePath().toString() + File.separatorChar + file.getFileName().toString() + "." + new Random().nextLong()); } try { if (tmpFile.createNewFile()) { try (FileOutputStream outputStream = new FileOutputStream(tmpFile)) { outputStream.write(bytes); } return tmpFile.toPath(); } else { throw S3Exception.INTERNAL_ERROR("Can't create file : " + tmpFile.getAbsolutePath()); } } catch (IOException exception) { throw S3Exception.INTERNAL_ERROR(exception); } } public void createFolder(String path) throws S3Exception { File folder = new File(path); if (!folder.exists() && !folder.mkdirs()) { exception("Can't create folder " + folder); } } protected void deleteFolder(String path) throws S3Exception { File folder = new File(path); if (folder.exists() && folder.isDirectory()) { try { Files.walkFileTree(folder.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc == null) { Files.delete(dir); return FileVisitResult.CONTINUE; } else { throw exc; } } }); } catch (IOException exception) { exception("Can't delete folder " + path); } } } protected void deleteEmptyKeys(File file) throws S3Exception { try { Path parent = file.toPath().getParent(); while (!isBucket(parent) && !parent.toString().equals(BASE_FOLDER_PATH) && Objects.requireNonNull(parent.toFile().list()).length == 0) { Files.delete(parent); parent = parent.getParent(); } } catch (Exception e) { throw S3Exception.INTERNAL_ERROR(e.getMessage()); } } protected void deleteFile(String path) throws S3Exception { File file = new File(path); if (isFileExists(file)) { if (!file.delete()) { exception("Can't delete file " + path); } } } protected void exception(String msg) throws S3Exception { log.error(msg); throw S3Exception.INTERNAL_ERROR(msg); } public void checkObject(S3FileObjectPath s3FileObjectPath) throws S3Exception { Path pathToObject = new File(s3FileObjectPath.getPathToObject()).toPath(); if (!isFileExists(pathToObject)) { throw S3Exception.builder("File not found : " + pathToObject.toAbsolutePath()) .setStatus(HttpResponseStatus.NOT_FOUND) .setCode(S3ResponseErrorCodes.NO_SUCH_KEY) .setMessage("The resource you requested does not exist") .build(); } Path pathToObjectMetadataFolder = new File(s3FileObjectPath.getPathToObjectMetadataFolder()).toPath(); Path pathToObjectMetaFile = new File(s3FileObjectPath.getPathToObjectMetaFile()).toPath(); Path pathToObjectAclFile = new File(s3FileObjectPath.getPathToObjectAclFile()).toPath(); if (!isFolderExists(pathToObjectMetadataFolder) || !isMetadataFolder(pathToObjectMetadataFolder) || !isFileExists(pathToObjectMetaFile) || !isMetadataFile(pathToObjectMetaFile) || !isFileExists(pathToObjectAclFile) || !isMetadataFile(pathToObjectAclFile)) { throw S3Exception.INTERNAL_ERROR("Object is corrupt"); } } public void checkBucket(S3FileBucketPath s3FileBucketPath) throws S3Exception { Path pathToBucket = new File(s3FileBucketPath.getPathToBucket()).toPath(); if (!isFolderExists(pathToBucket) || !isBucket(pathToBucket)) { throw S3Exception.builder("Bucket does not exist") .setStatus(HttpResponseStatus.NOT_FOUND) .setCode(S3ResponseErrorCodes.NO_SUCH_BUCKET) .setMessage("The specified bucket does not exist") .build(); } Path pathToMetadataBucket = new File(s3FileBucketPath.getPathToBucketMetadataFolder()).toPath(); Path pathToBucketAcl = new File(s3FileBucketPath.getPathToBucketAclFile()).toPath(); if (!isFolderExists(pathToMetadataBucket) || !isMetadataFolder(pathToMetadataBucket) || !isFileExists(pathToBucketAcl) || !isMetadataFile(pathToBucketAcl)) { throw S3Exception.INTERNAL_ERROR("Bucket is corrupt"); } } public boolean isFolderExists(String path) { File folder = new File(path); return folder.exists() && folder.isDirectory(); } public boolean isFolderExists(File folder) { return folder.exists() && folder.isDirectory(); } public boolean isFolderExists(Path folder) { return isFolderExists(folder.toFile()); } public boolean isFileExists(String path) { File file = new File(path); return file.exists() && file.isFile(); } public boolean isFileExists(File file) { return file.exists() && file.isFile(); } public boolean isFileExists(Path path) { return isFileExists(path.toFile()); } public S3FileObjectPath buildPathToObject(String bucketKey) { if (bucketKey.startsWith("/")) { bucketKey = bucketKey.substring(1); } return S3FileObjectPath.relative(BASE_FOLDER_PATH, bucketKey); } } <file_sep>/src/main/java/com/thorinhood/data/list/raw/ListBucketResultRaw.java package com.thorinhood.data.list.raw; public class ListBucketResultRaw extends ListBucketResultRawAbstract { private String nextMarker; public static Builder builder() { return new Builder(); } private ListBucketResultRaw() { } public String getNextMarker() { return nextMarker; } public static class Builder extends ListBucketResultRawAbstract.Builder<Builder> { private final ListBucketResultRaw listBucketResultRaw; public Builder() { listBucketResultRaw = new ListBucketResultRaw(); init(listBucketResultRaw, this); } public Builder setNextMarker(String nextMarker) { listBucketResultRaw.nextMarker = nextMarker; return this; } public ListBucketResultRaw build() { return listBucketResultRaw; } } } <file_sep>/src/main/java/com/thorinhood/data/acl/Grantee.java package com.thorinhood.data.acl; import com.thorinhood.utils.XmlObject; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import java.io.Serializable; import java.util.Map; public class Grantee implements Serializable, XmlObject { private String displayName; private String emailAddress; private String id; private String type; private String xsi = "http://www.w3.org/2001/XMLSchema-instance"; public static Grantee buildFromNode(Node node) { return new Builder().setFromRootNode(node).build(); } public static Builder builder() { return new Builder(); } private Grantee() { } public String getDisplayName() { return displayName; } public String getEmailAddress() { return emailAddress; } public String getId() { return id; } public String getType() { return type; } public String getXsi() { return xsi; } @Override public Element buildXmlRootNode(Document doc) { Element root = createElement(doc, "Grantee", displayName != null ? createElement(doc, "DisplayName", doc.createTextNode(displayName)) : null, emailAddress != null ? createElement(doc, "EmailAddress", doc.createTextNode(emailAddress)) : null, id != null ? createElement(doc, "ID", doc.createTextNode(id)) : null); return appendAttributes(root, Map.of( "xmlns:xsi", xsi, "xsi:type", type )); } public static class Builder { private final Grantee grantee; public Builder() { grantee = new Grantee(); } public Builder setId(String id) { grantee.id = id; return this; } public Builder setType(String type) { grantee.type = type; return this; } public Builder setEmailAddress(String emailAddress) { grantee.emailAddress = emailAddress; return this; } public Builder setDisplayName(String displayName) { grantee.displayName = displayName; return this; } public Builder setXsi(String xsi) { grantee.xsi = xsi; return this; } public Builder setFromRootNode(Node node) { for (int i = 0; i < node.getChildNodes().getLength(); i++) { Node child = node.getChildNodes().item(i); if (child.getNodeName().equals("DisplayName")) { grantee.displayName = child.getChildNodes().item(0).getNodeValue(); } else if (child.getNodeName().equals("EmailAddress")) { grantee.emailAddress = child.getChildNodes().item(0).getNodeValue(); } else if (child.getNodeName().equals("ID")) { grantee.id = child.getChildNodes().item(0).getNodeValue(); } } grantee.type = node.getAttributes().getNamedItem("xsi:type").getNodeValue(); grantee.xsi = node.getAttributes().getNamedItem("xmlns:xsi").getNodeValue(); return this; } public Grantee build() { return grantee; } } } <file_sep>/src/test/java/com/thorinhood/actions/CopyObjectTest.java package com.thorinhood.actions; import com.thorinhood.BaseTest; import com.thorinhood.data.requests.S3ResponseErrorCodes; import io.netty.handler.codec.http.HttpResponseStatus; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.CopyObjectRequest; import software.amazon.awssdk.services.s3.model.CopyObjectResponse; import software.amazon.awssdk.services.s3.model.PutBucketPolicyRequest; import software.amazon.awssdk.services.s3.model.S3Exception; import java.io.File; import java.io.IOException; import java.util.Map; public class CopyObjectTest extends BaseTest { public CopyObjectTest() { super("testS3Java", 9999); } @Test public void simpleCopy() throws IOException { String bucket = "bucket"; String sourceKeyWithoutBucket = "folder/file.txt"; String content = createContent(5 * 1024 * 1024); String targetKey = "folder2/file.txt"; Map<String, String> metadata = Map.of( "key1", "value1", "key2", "value2" ); S3Client s3Client = getS3Client(true, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3Client, bucket); putObjectRaw(s3Client, bucket, sourceKeyWithoutBucket, content, metadata); CopyObjectResponse response = s3Client.copyObject(CopyObjectRequest.builder() .copySource("/" + bucket + File.separatorChar + sourceKeyWithoutBucket) .destinationKey(targetKey) .destinationBucket(bucket) .build()); checkObject(bucket, "folder", "file.txt", content, metadata); checkObject(bucket, "folder2", "file.txt", content, metadata); Assertions.assertEquals("\"" + calcETag(content) + "\"", response.copyObjectResult().eTag()); String bucket2 = "bucket2"; createBucketRaw(s3Client, bucket2); response = s3Client.copyObject(CopyObjectRequest.builder() .copySource("/" + bucket + File.separatorChar + sourceKeyWithoutBucket) .destinationBucket(bucket2) .destinationKey(sourceKeyWithoutBucket) .build()); checkObject(bucket, "folder", "file.txt", content, metadata); checkObject(bucket2, "folder", "file.txt", content, metadata); Assertions.assertEquals("\"" + calcETag(content) + "\"", response.copyObjectResult().eTag()); } @Test public void copyObjectMatches() throws IOException { String bucket = "bucket"; String sourceKeyWithoutBucket = "folder/file.txt"; String content = createContent(5 * 1024 * 1024); String targetKey = "folder2/file.txt"; S3Client s3Client = getS3Client(true, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3Client, bucket); putObjectRaw(s3Client, bucket, sourceKeyWithoutBucket, content, null); CopyObjectResponse response = s3Client.copyObject(CopyObjectRequest.builder() .copySource("/" + bucket + File.separatorChar + sourceKeyWithoutBucket) .destinationKey(targetKey) .destinationBucket(bucket) .copySourceIfMatch("\"" + calcETag(content) + "\"") .copySourceIfNoneMatch("w0Y2qfo") .build()); checkObject(bucket, "folder", "file.txt", content, null); checkObject(bucket, "folder2", "file.txt", content, null); Assertions.assertEquals("\"" + calcETag(content) + "\"", response.copyObjectResult().eTag()); try { s3Client.copyObject(CopyObjectRequest.builder() .copySource("/" + bucket + File.separatorChar + sourceKeyWithoutBucket) .destinationKey("key.txt") .destinationBucket(bucket) .copySourceIfMatch("14dC7U0q") .build()); Assertions.fail("Must be exception"); } catch (S3Exception exception) { Assertions.assertEquals(HttpResponseStatus.PRECONDITION_FAILED.code(), exception.statusCode()); } try { s3Client.copyObject(CopyObjectRequest.builder() .copySource("/" + bucket + File.separatorChar + sourceKeyWithoutBucket) .destinationKey("key.txt") .destinationBucket(bucket) .copySourceIfNoneMatch("\"" + calcETag(content) + "\"") .build()); Assertions.fail("Must be exception"); } catch (S3Exception exception) { Assertions.assertEquals(HttpResponseStatus.PRECONDITION_FAILED.code(), exception.statusCode()); } } @Test public void copyObjectPermission() throws IOException { String bucket = "bucket"; String bucket2 = "bucket2"; String sourceKeyWithoutBucket = "folder/file.txt"; String content = createContent(5 * 1024 * 1024); S3Client s3Client = getS3Client(true, ROOT_USER.getAccessKey(), ROOT_USER.getSecretKey()); createBucketRaw(s3Client, bucket); putObjectRaw(s3Client, bucket, sourceKeyWithoutBucket, content, null); S3Client s3Client2 = getS3Client(true, ROOT_USER_2.getAccessKey(), ROOT_USER_2.getSecretKey()); createBucketRaw(s3Client2, bucket2); assertException(HttpResponseStatus.FORBIDDEN.code(), S3ResponseErrorCodes.ACCESS_DENIED, () -> { s3Client.copyObject(CopyObjectRequest.builder() .copySource("/" + bucket + File.separatorChar + sourceKeyWithoutBucket) .destinationKey("key.txt") .destinationBucket(bucket2) .build()); }); assertException(HttpResponseStatus.FORBIDDEN.code(), S3ResponseErrorCodes.ACCESS_DENIED, () -> { s3Client2.copyObject(CopyObjectRequest.builder() .copySource("/" + bucket + File.separatorChar + sourceKeyWithoutBucket) .destinationKey("key.txt") .destinationBucket(bucket2) .build()); }); s3Client.putBucketPolicy(PutBucketPolicyRequest.builder() .bucket(bucket) .policy("{\n" + " \"Statement\" : [\n" + " {\n" + " \"Effect\" : \"Allow\",\n" + " \"Action\" : [\"*\"],\n" + " \"Resource\" : \"arn:aws:s3:::bucket/*\",\n" + " \"Principal\" : {\n" + " \"AWS\": \"" + ROOT_USER_2.getArn() + "\"\n" + " }\n" + " }]\n" + "}") .build()); CopyObjectResponse response = s3Client2.copyObject(CopyObjectRequest.builder() .copySource("/" + bucket + File.separatorChar + sourceKeyWithoutBucket) .destinationKey("key.txt") .destinationBucket(bucket2) .build()); checkObject(bucket, "folder", "file.txt", content, null); checkObject(bucket2, null, "key.txt", content, null); Assertions.assertEquals("\"" + calcETag(content) + "\"", response.copyObjectResult().eTag()); s3Client2.putBucketPolicy(PutBucketPolicyRequest.builder() .bucket(bucket2) .policy("{\n" + " \"Statement\" : [\n" + " {\n" + " \"Effect\" : \"Allow\",\n" + " \"Action\" : [\"*\"],\n" + " \"Resource\" : \"arn:aws:s3:::bucket2/*\",\n" + " \"Principal\" : {\n" + " \"AWS\": \"" + ROOT_USER.getArn() + "\"\n" + " }\n" + " }]\n" + "}") .build()); response = s3Client.copyObject(CopyObjectRequest.builder() .copySource("/" + bucket + File.separatorChar + sourceKeyWithoutBucket) .destinationKey("folder/key.txt") .destinationBucket(bucket2) .build()); checkObject(bucket, "folder", "file.txt", content, null); checkObject(bucket2, "folder", "key.txt", content, null); Assertions.assertEquals("\"" + calcETag(content) + "\"", response.copyObjectResult().eTag()); } } <file_sep>/src/main/java/com/thorinhood/processors/actions/HeadObjectProcessor.java package com.thorinhood.processors.actions; import com.thorinhood.data.s3object.S3Object; import com.thorinhood.drivers.main.S3Driver; import com.thorinhood.exceptions.S3Exception; import com.thorinhood.processors.Processor; import com.thorinhood.utils.DateTimeUtil; import com.thorinhood.utils.ParsedRequest; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpUtil; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; import java.util.Map; public class HeadObjectProcessor extends Processor { private static final Logger log = LogManager.getLogger(HeadObjectProcessor.class); public HeadObjectProcessor(S3Driver s3Driver) { super(s3Driver); } @Override protected void processInner(ChannelHandlerContext context, FullHttpRequest request, ParsedRequest parsedRequest, Object... arguments) throws Exception { checkRequestPermissions(parsedRequest, "s3:GetObject", false); S3Object s3Object = S3_DRIVER.headObject(parsedRequest.getS3ObjectPath(), parsedRequest.getHeaders()); sendResponse(context, request, HttpResponseStatus.OK, response -> { HttpUtil.setContentLength(response, s3Object.getFile().length()); try { setContentTypeHeader(response, s3Object.getFile()); } catch (IOException exception) { throw S3Exception.INTERNAL_ERROR(exception); } response.headers().set("ETag", "\"" + s3Object.getETag() + "\""); response.headers().set("Last-Modified", s3Object.getLastModified()); response.headers().set("Date", DateTimeUtil.currentDateTime()); s3Object.getMetaData().forEach((metaKey, metaValue) -> response.headers().set("x-amz-meta-" + metaKey, metaValue)); }); } @Override protected Logger getLogger() { return log; } } <file_sep>/src/main/java/com/thorinhood/processors/policies/BucketPolicyProcessor.java package com.thorinhood.processors.policies; import com.thorinhood.drivers.main.S3Driver; import com.thorinhood.exceptions.S3Exception; import com.thorinhood.processors.Processor; import com.thorinhood.utils.ParsedRequest; import java.util.Optional; public abstract class BucketPolicyProcessor extends Processor { public BucketPolicyProcessor(S3Driver s3Driver) { super(s3Driver); } @Override protected void checkRequestPermissions(ParsedRequest request, boolean isBucketAcl) throws S3Exception { S3_DRIVER.isBucketExists(request.getS3BucketPath()); boolean aclCheckResult = S3_DRIVER.isOwner(isBucketAcl, request.getS3ObjectPathUnsafe(), request.getS3User()); if (!aclCheckResult) { throw S3Exception.ACCESS_DENIED(); } if (!request.getS3User().isRootUser()) { Optional<Boolean> policyCheckResult = S3_DRIVER.checkBucketPolicy(request.getS3BucketPath(), request.getS3ObjectPathUnsafe().getKeyUnsafe(), METHOD_NAME, request.getS3User()); if (policyCheckResult.isEmpty() || !policyCheckResult.get()) { throw S3Exception.ACCESS_DENIED(); } } } } <file_sep>/src/main/java/com/thorinhood/processors/actions/DeleteBucketProcessor.java package com.thorinhood.processors.actions; import com.thorinhood.drivers.main.S3Driver; import com.thorinhood.processors.Processor; import com.thorinhood.utils.DateTimeUtil; import com.thorinhood.utils.ParsedRequest; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.Map; public class DeleteBucketProcessor extends Processor { private static final Logger log = LogManager.getLogger(DeleteBucketProcessor.class); public DeleteBucketProcessor(S3Driver s3Driver) { super(s3Driver); } @Override protected void processInner(ChannelHandlerContext context, FullHttpRequest request, ParsedRequest parsedRequest, Object... arguments) throws Exception { checkRequestPermissions(parsedRequest, true); S3_DRIVER.deleteBucket(parsedRequest.getS3BucketPath()); sendResponseWithoutContent(context, HttpResponseStatus.OK, request, Map.of( "Date", DateTimeUtil.currentDateTime() )); } @Override protected Logger getLogger() { return log; } } <file_sep>/src/main/java/com/thorinhood/Server.java package com.thorinhood; import com.thorinhood.drivers.main.S3Driver; import com.thorinhood.drivers.user.UserDriver; import com.thorinhood.utils.RequestUtil; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; public class Server { private final int port; private final ServerInitializer serverInitializer; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; private ChannelFuture future; public Server(int port, S3Driver s3Driver, RequestUtil requestUtil) { this.port = port; serverInitializer = new ServerInitializer(s3Driver, requestUtil); } public void run() throws Exception { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(serverInitializer); future = bootstrap.bind(port).sync(); Channel channel = future.channel(); channel.closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } public void stop() { try { bossGroup.shutdownGracefully().sync(); workerGroup.shutdownGracefully().sync(); future.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } } } <file_sep>/src/test/java/com/thorinhood/ArgumentParserTest.java package com.thorinhood; import com.thorinhood.utils.ArgumentParser; import junit.framework.TestCase; import org.junit.Assert; import java.util.Map; import java.util.Set; public class ArgumentParserTest extends TestCase { public void testParseArguments() { Map<String, String> result = ArgumentParser.parseArguments(new String[]{ "--dbUser=xxx", "--param=yyy", "--yyet=zzz" }); Map<String, String> expected = Map.of( "dbUser", "xxx", "param", "yyy", "yyet", "zzz" ); Assert.assertEquals(result.size(), 3); for (String key : expected.keySet()) { Assert.assertTrue(result.containsKey(key)); Assert.assertEquals(result.get(key), expected.get(key)); } } public void testCheckArguments() { Set<String> result = ArgumentParser.checkArguments(Map.of( "first", "1", "second", "2" ), "first", "third", "second"); Assert.assertEquals(result.size(), 1); Assert.assertEquals(result.iterator().next(), "third"); } }<file_sep>/src/main/java/com/thorinhood/drivers/lock/EntityLockDriver.java package com.thorinhood.drivers.lock; import com.thorinhood.data.S3FileBucketPath; import com.thorinhood.data.S3FileObjectPath; import com.thorinhood.drivers.S3Runnable; import com.thorinhood.drivers.S3Supplier; import com.thorinhood.exceptions.S3Exception; import java.io.File; import java.io.IOException; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.nio.file.StandardOpenOption; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class EntityLockDriver { private final Map<String, ReadWriteLock> lockMap; private final Set<String> fileLocks; public EntityLockDriver() { lockMap = new ConcurrentHashMap<>(); fileLocks = Collections.newSetFromMap(new ConcurrentHashMap<>()); } public void writeBucket(S3FileBucketPath s3FileBucketPath, S3Runnable s3Runnable) throws S3Exception { write(s3FileBucketPath.getPathToBucket(), s3Runnable); } public <T> T completeUpload(S3FileObjectPath s3FileObjectPath, String uploadId, S3Supplier<T> s3Supplier) throws S3Exception { return read(s3FileObjectPath.getPathToBucket(), () -> read(s3FileObjectPath.getPathToBucketMetadataFolder(), () -> write(uploadId, () -> writeObject(s3FileObjectPath, s3Supplier)))); } public void createUpload(String bucket, String metaFolder, String upload, S3Runnable s3Runnable) throws S3Exception { read(bucket, () -> read(metaFolder, () -> write(upload, s3Runnable))); } public void deleteUpload(String bucket, String metaFolder, String upload, S3Runnable s3Runnable) throws S3Exception { read(bucket, () -> write(metaFolder, () -> write(upload, s3Runnable))); } public <T> T writeUpload(String bucket, String metaFolder, String upload, String part, S3Supplier<T> s3Runnable) throws S3Exception { return read(bucket, () -> read(metaFolder, () -> read(upload, () -> write(part, s3Runnable)))); } public <T> T writeMeta(String bucket, String metaFolder, String file, S3Supplier<T> s3Supplier) throws S3Exception { return read(bucket, () -> read(metaFolder, () -> write(file, s3Supplier))); } public void writeMeta(String bucket, String metaFolder, String file, S3Runnable s3Runnable) throws S3Exception { read(bucket, () -> read(metaFolder, () -> write(file, s3Runnable))); } public <T> T readMeta(String bucket, String metaFolder, String file, S3Supplier<T> s3Supplier) throws S3Exception { return read(bucket, () -> read(metaFolder, () -> read(file, s3Supplier))); } public <T> T readObject(S3FileObjectPath s3FileObjectPath, S3Supplier<T> s3Supplier) throws S3Exception { return read(s3FileObjectPath.getPathToBucket(), () -> read(s3FileObjectPath.getPathToObject(), () -> read(s3FileObjectPath.getPathToObjectMetadataFolder(), () -> read(s3FileObjectPath.getPathToObjectMetaFile(), s3Supplier)))); } public void deleteObject(S3FileObjectPath s3FileObjectPath, S3Runnable s3Runnable) throws S3Exception { read(s3FileObjectPath.getPathToBucket(), () -> write(s3FileObjectPath.getPathToObject(), () -> write(s3FileObjectPath.getPathToObjectMetadataFolder(), () -> write(s3FileObjectPath.getPathToObjectMetaFile(), () -> write(s3FileObjectPath.getPathToObjectAclFile(), s3Runnable))))); } public <T> T writeObject(S3FileObjectPath s3FileObjectPath, S3Supplier<T> s3Supplier) throws S3Exception { return read(s3FileObjectPath.getPathToBucket(), () -> write(s3FileObjectPath.getPathToObject(), () -> read(s3FileObjectPath.getPathToObjectMetadataFolder(), () -> write(s3FileObjectPath.getPathToObjectMetaFile(), () -> write(s3FileObjectPath.getPathToObjectAclFile(), s3Supplier))))); } private <T> T write(String key, S3Supplier<T> s3Supplier) throws S3Exception { ReadWriteLock lock = getLock(key); try { lock.writeLock().lock(); return supplier(key, s3Supplier); } catch (IOException exception) { throw S3Exception.INTERNAL_ERROR(exception); } finally { lock.writeLock().unlock(); } } private void write(String key, S3Runnable s3Runnable) throws S3Exception { ReadWriteLock lock = getLock(key); try { lock.writeLock().lock(); runnable(key, s3Runnable); } catch (IOException exception) { throw S3Exception.INTERNAL_ERROR(exception); } finally { lock.writeLock().unlock(); } } private <T> T read(String key, S3Supplier<T> s3Supplier) throws S3Exception { ReadWriteLock lock = getLock(key); try { lock.readLock().lock(); return supplier(key, s3Supplier); } catch (IOException exception) { throw S3Exception.INTERNAL_ERROR(exception); } finally { lock.readLock().unlock(); } } private void read(String key, S3Runnable s3Runnable) throws S3Exception { ReadWriteLock lock = getLock(key); try { lock.readLock().lock(); runnable(key, s3Runnable); } catch (IOException exception) { throw S3Exception.INTERNAL_ERROR(exception); } finally { lock.readLock().unlock(); } } private void runnable(String key, S3Runnable s3Runnable) throws IOException { File file = new File(key); if (file.isFile()) { if (!fileLocks.contains(key)) { try (FileChannel fileChannel = FileChannel.open(file.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); FileLock fileLock = fileChannel.lock(0, Long.MAX_VALUE, true)) { fileLocks.add(key); s3Runnable.run(); } catch(OverlappingFileLockException exception) { s3Runnable.run(); } finally { fileLocks.remove(key); } } else { s3Runnable.run(); } } else { s3Runnable.run(); } } private <T> T supplier(String key, S3Supplier<T> s3Supplier) throws IOException { File file = new File(key); if (file.isFile()) { if (!fileLocks.contains(key)) { try (FileChannel fileChannel = FileChannel.open(file.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); FileLock fileLock = fileChannel.lock(0, Long.MAX_VALUE, true)) { fileLocks.add(key); return s3Supplier.get(); } catch (OverlappingFileLockException exception) { return s3Supplier.get(); } finally { fileLocks.remove(key); } } else { return s3Supplier.get(); } } else { return s3Supplier.get(); } } private ReadWriteLock getLock(String key) { ReadWriteLock lock = lockMap.get(key); if (lock != null) { return lock; } lock = new ReentrantReadWriteLock(); ReadWriteLock current = lockMap.putIfAbsent(key, lock); return current == null ? lock : current; } } <file_sep>/src/main/java/com/thorinhood/processors/policies/PutBucketPolicyProcessor.java package com.thorinhood.processors.policies; import com.thorinhood.drivers.main.S3Driver; import com.thorinhood.utils.DateTimeUtil; import com.thorinhood.utils.ParsedRequest; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.FullHttpRequest; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.Map; import static io.netty.handler.codec.http.HttpResponseStatus.OK; public class PutBucketPolicyProcessor extends BucketPolicyProcessor { private static final Logger log = LogManager.getLogger(PutBucketPolicyProcessor.class); public PutBucketPolicyProcessor(S3Driver s3Driver) { super(s3Driver); } @Override protected void processInner(ChannelHandlerContext context, FullHttpRequest request, ParsedRequest parsedRequest, Object... arguments) throws Exception { checkRequestPermissions(parsedRequest, true); S3_DRIVER.putBucketPolicy(parsedRequest.getS3BucketPath(), parsedRequest.getBytes()); sendResponseWithoutContent(context, OK, request, Map.of( "Date", DateTimeUtil.currentDateTime() )); } @Override protected Logger getLogger() { return log; } } <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <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>com.thorinhood</groupId> <artifactId>s3server</artifactId> <version>1.0</version> <properties> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.10.Final</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.15</version> </dependency> <!-- aws sdk --> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>s3</artifactId> <version>2.16.33</version> </dependency> <!-- jackson json serialzation/deserialization --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.1</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api --> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.0-b170201.1204</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.activation/activation --> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.glassfish.jaxb/jaxb-runtime --> <dependency> <groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> <version>2.3.0-b170127.1453</version> </dependency> <!-- logging --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.14.0</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.14.0</version> </dependency> <dependency> <groupId>com.lmax</groupId> <artifactId>disruptor</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>3.1.2</version> <configuration> <configLocation>checkstyle.xml</configLocation> </configuration> </plugin> </plugins> </reporting> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.4.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>com.thorinhood.MainServer</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/README.md # S3 Java server ## Как запустить > java -jar <>.jar > Флаги \ --port=9090 (порт, по которому будет работать сервер)\ --basePath=путь (путь до основной папки, где будут храниться бакеты и объекты) \ --users=пути (пути до json файлов через запятую, где описаны пользователи) \ Примечание: Все пути должны быть абсолютными > Пример json файла пользователя \ { \ "accessKey" : <ключ по которому определяется пользователь>, \ "secretKey" : <серкетный ключ, которым будет подписываться каждый запрос>, \ "userId" : "504587744049" <id пользователя>, \ "userName" : <если это IAM пользователь>, \ "arn" : "arn:aws:iam::504587744049:<root или user/userName", \ "canonicalUserId" : <каноничный id пользователя, используется в ACL>, \ "accountName" : <имя основного аккаунта> \ } ## Методы > ###Реализованные методы: > * GetBucketAcl > * GetObjectAcl > * PutBucketAcl > * PutObjectAcl > * CopyObject > * CreateBucket > * DeleteBucket > * DeleteObject > * GetObject > * PutObject > * ListBuckets > * ListObjects > * ListObjectsV2 > * AbortMultipartUpload > * CompleteMultipartUpload > * CreateMultipartUpload > * UploadPart > * GetBucketPolicy > * PutBucketPolicy > * HeadObject
63a06ea7dc8b42c35c3d9ff351ad059fa7a34ce4
[ "Markdown", "Java", "Maven POM" ]
52
Java
THORinHOOD/s3server
670d5457b71c3274762282ddd8285e5c3b1bb099
36ecb4e9bb8b01d7eef953df23857c50065616cf
refs/heads/master
<file_sep>#pragma once #include<stdio.h> #include<malloc.h> #pragma warning(disable:4996) typedef struct stuInfo { int stuID; char stuName[10]; int Age; }data; typedef struct node { struct stuInfo data; struct node *next; }LinkNode; void Creatlist(LinkNode *&L); void Sortlist(LinkNode *&L); bool ListInsert(LinkNode *&L); void Listcombine(LinkNode *&L1, LinkNode *&L2); void Listreverse(LinkNode *&L); void PrintList(LinkNode *&L); void Listflush(LinkNode *&L);<file_sep>#include"stuinfo.h" #include"view.h" int main(void){ int choice, flag = 0; LinkNode *L, *L2; L = (LinkNode *)malloc(sizeof(LinkNode)); L->next = NULL; boundar(); do { printf("\n 请输入你要使用的功能:"); scanf(" %d", &choice); switch (choice) { case 1: Creatlist(L);break; case 2:ListInsert(L);break; case 3:Listcombine(L, L2);break; case 4:Listreverse(L);break; case 5:PrintList(L);break; case 6:Listflush(L);break; default:;break; } } while (choice != 6); } <file_sep># data_structure_stuinfo A homework for year1 data_structure learning ## 实验目的: 本实验通过定义单向链表的数据结构,设计创建链表、插入结点、遍历结点等基本算法,使学生掌握线性链表的基本特征和算法,并能熟练编写C程序,培养理论联系实际和自主学习的能力,提高程序设计水平。 ## 实验内容: 实现带头结点的单向链表的创建、删除链表、插入结点等操作,可每个学生的学号互不相同,学号不同而姓名相同则为不同的学生,每个学生的学号在合并后的链表中不重复,如果出现重复,则删除年龄较小结点。最后打印输出合并后的链表元素,验证结果的正确性。 1. 设计学生信息结点的数据结构; 2. 用C语言实现创建升序链表的函数,每个结点的学号不同,按照学号升序排列; 3. 用C语言实现结点的插入的函数,插入后仍然为升序; 4. 编程实现两个单向链表合并,合并后仍然升序; 5. 编程实现合并后链表逆序排列的算法; 6. 打印输出合并后的链表元素。 <file_sep>#include"stuinfo.h" #include <stdlib.h> #include <stdio.h> #include<string.h> void Sortlist(LinkNode *&L) { LinkNode *p, *pre, *q; p = L->next->next; L->next->next = NULL; while (p != NULL) { q = p->next; pre = L; while (pre->next != NULL && pre->next->data.stuID < p->data.stuID) pre = pre->next; p->next = pre->next; pre->next = p; p = q; } } bool ListInsert(LinkNode *&L) { LinkNode *p = L->next, *s; struct stuInfo newdata; printf(" 请输入学生的学号,姓名,年龄:"); scanf("%d %s %d", &newdata.stuID, &newdata.stuName, &newdata.Age); while (p->data.stuID < newdata.stuID && p->next!= NULL) p = p->next; if (p == NULL) return false; else { s = (LinkNode*)malloc(sizeof(LinkNode)); s->data.stuID = newdata.stuID; s->data.Age = newdata.Age; strcpy(s->data.stuName, newdata.stuName); s->next = p->next; p->next = s; Sortlist(L); return true; } } void Listcombine(LinkNode *&L1, LinkNode *&L2) { LinkNode *p = L1->next, *s = L2->next, *t; int flag; t = (LinkNode*)malloc(sizeof(LinkNode)); if (L1->next->data.stuID > L2->next->data.stuID) { p = L2->next; s = L1->next; flag = 1; } while (p != NULL) { while (p->next->data.stuID < s->data.stuID && p != NULL) { p = p->next; } t = p->next; p->next = s; p->next->next = t; s = s->next; } if (flag = 1) L1 = L2; } void Listreverse(LinkNode *&L) { LinkNode *p1 = L->next, *p2 = p1->next, *p3 = p2->next; p1->next = NULL; while (p3 != NULL){ p2->next = p1; p1 = p2; p2 = p3; p3 = p3->next; } p2->next = p1; L->next = p2; } void PrintList(LinkNode *&L) { LinkNode *p = L->next; while (p != NULL) { printf("\n %d %s %d", p->data.stuID, p->data.stuName, p->data.Age); p = p->next; } } void Creatlist(LinkNode *&L) { FILE *fp; LinkNode *s, *r; L = (LinkNode *)malloc(sizeof(LinkNode)); r = L; fp = fopen("信息.txt", "r"); if (fp == NULL) { printf(" 文件不存在或无法打开\n"); exit(EXIT_FAILURE); } do { s = (LinkNode *)malloc(sizeof(LinkNode)); fscanf(fp, "%d %s %d", &(s->data.stuID),&(s->data.stuName), &(s->data.Age)); r->next = s; r = s; } while (!feof(fp)); r->next = NULL; fclose(fp); Sortlist(L); } void Listflush(LinkNode *&L) { FILE *fp; fp = fopen("信息.txt", "w"); if (fp == NULL) { printf(" 文件不存在或无法打开\n"); exit(EXIT_FAILURE); } else { for (;L->next != NULL;) { L = L->next; fprintf(fp, "%d %s %d\n", L->data.stuID, L->data.stuName, L->data.Age); } } fclose(fp); }<file_sep>#pragma once #pragma warning(disable:4996) void boundar(void);
e9cb198c5f2c3398902a3bcc9615d8e06a3d6613
[ "Markdown", "C", "C++" ]
5
C
allenx555/data_structure_stuinfo
b292d1e6bf8c7cf39e7d454c9ec749fe6ebfa280
9f217eb4c32ec49e31fe5de2fe68855a50cea58d
refs/heads/master
<file_sep><?php function doctype() { echo "<!DOCTYPE html>\n"; } function startHTML5() { doctype(); echo "<html>\n"; } function endHTML5() { echo "</html>\n\n"; } function insertScripts() { echo "\t<!-- javascript goes here -->\n"; } function insertHeader($title, $css = "") { echo "<head>\n"; echo "\t<meta charset=\"UTF-8\">\n"; if($css != "") echo "\t<link rel=\"stylesheet\" href=\"style/". $css ."\">\n"; insertScripts(); echo "\t<title>". $title . "</title>\n"; echo "</head>\n"; } function insertBodyDocument($body) { echo "<body>\n"; echo $body."\n"; echo "</body>\n"; } function getContent($filename) { return "\n" . file_get_contents("content/".$filename) . "\n"; } ?> <file_sep># PrgoWeb4A Repository for the website we develop in class - Ybalrid : <NAME> <<EMAIL>> - Kevl95 : <NAME> <<EMAIL>> ______ The website code is on the "webdir" subfolder of the repo. The website is hosted on a dedicated server (by OVH) here : http://progweb.ybalrid.info/ <file_sep><?php //Enable the session system session_start(); //Import our custom template engine require_once("./template/engine.php"); //Throw some clean HTML code on the page using the engine functions startHTML5(); insertHeader("This is the index","main.css"); $content = getContent("startPage.html"); insertBodyDocument($content); endHTML5(); ?>
4a277dc673846a8803f0deb85707991a09a0122c
[ "Markdown", "PHP" ]
3
PHP
Ybalrid/ProgWeb4A
f3ee5fc8055d5b5f482436e47827a5d8cd03cefc
110bddda2833e129541ad9c625bdcfecde478690
refs/heads/master
<repo_name>germancardenasm/jsbootstraping<file_sep>/README.md ## Frontend Bootstrapping <NAME> Se borro cambio en Readme<file_sep>/JS/script.js let about = document.getElementById("about"); let getAbout = document.getElementById("getAbout"); let resume = document.getElementById("resume"); let getResume = document.getElementById("getResume"); let works = document.getElementById("works"); let getWorks = document.getElementById("getWorks"); let worksCategories = document.getElementById('worksCategories'); let worksContent = document.getElementById('works-content'); let contact = document.getElementById("contact"); let contact_me = document.getElementById("contact_me"); let getContact = document.getElementById("getContact"); let send = document.getElementById("send"); let email = document.getElementById("email"); let form = document.getElementById("form"); var modal = document.getElementById("myModal"); let modalImg = document.getElementById("modalImg"); let modalTitle = document.getElementById("modalTitle"); let modalAnchor = document.getElementById("modalAnchor"); var span = document.getElementsByClassName("close")[0]; function removeSection() { about.classList.remove("view"); getAbout.classList.remove("selected"); resume.classList.remove("view"); getResume.classList.remove("selected"); works.classList.remove("view"); getWorks.classList.remove("selected"); contact.classList.remove("view"); getContact.classList.remove("selected"); } getAbout.addEventListener("click", function(e) { getSection(e, about, getAbout); }); getResume.addEventListener("click", function(e) { getSection(e, resume, getResume); }); getWorks.addEventListener("click", function(e) { getSection(e, works, getWorks); }); getContact.addEventListener("click", function(e) { getSection(e, contact, getContact); }); contact_me.addEventListener("click", function(e) { getSection(e, contact, getContact); }); function getSection(event, section, getButton) { if (window.innerWidth > 1040) { event.preventDefault(); removeSection(); section.classList.add("view"); getButton.classList.add("selected"); } } worksCategories.addEventListener('click', function(e){ let worksContainers = document.getElementsByClassName('work-container'); for(let i = 0; i < worksContainers.length; i++) { if(worksCategories.children[i].innerHTML.toLowerCase() == e.target.innerHTML.toLowerCase()) worksCategories.children[i].classList.add('selected'); else worksCategories.children[i].classList.remove('selected'); if(e.target.innerHTML.toLowerCase()==='all') worksContainers[i].classList.remove('hidden'); else if(!worksContainers[i].classList.contains(e.target.innerHTML.toLowerCase())) worksContainers[i].classList.add('hidden'); else worksContainers[i].classList.remove('hidden'); } }) worksContent.addEventListener('click', function(event){ var parent = getClosestParent(event.target, '.work-container'); if(parent) { modalImg.src = parent.getElementsByTagName('img')[0].src; modalTitle.innerHTML = parent.getElementsByTagName('h4')[0].innerText modalAnchor.href = parent.getAttribute('href'); modal.style.top = works.scrollTop+'px'; modal.style.display = "block"; } }); email.addEventListener("input", function(event) { if (email.validity.typeMismatch) { email.setCustomValidity("I expect an e-mail!"); } else { email.setCustomValidity(""); } }); form.addEventListener("submit", function(event) { var name = document.getElementById("name").value; var message = document.getElementById("message").value; var email = document.getElementById("email").value; event.preventDefault(); var form= { name: name, email: email, text: message, } localStorage.setItem("contactForm",JSON.stringify(form)); document.getElementById("form").reset(); alert( ` ${JSON.parse(localStorage.contactForm).name} gracias por contactarme. Te respondere cuanto antes.`) }); span.onclick = function() { modal.style.display = "none"; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } function getClosestParent(elem, selector) { for ( ; elem && elem !== document; elem = elem.parentNode ) { if ( elem.matches( selector ) ) return elem; } return null; };
fb5a640353f83b501a2b6fa8af79a291d6e37e11
[ "Markdown", "JavaScript" ]
2
Markdown
germancardenasm/jsbootstraping
b08146e389491fd0f4584222f0e5addb144e7de0
77ee96e5b682eaff951935e85ce1d863de6b215a
refs/heads/master
<file_sep># webpack-startup A webpack startup example for mobile development. Copy all files to your new project folder and run 'npm install' than run 'npm run watch', that't it. It include a static server, just type 'npm start'. <file_sep>'use strict'; require('../style/main.scss'); // let React = require('react'); // let ReactDOM = require('react-dom'); //
d3692e2425cc0a7fc847b3924b0f44e9769dd0a4
[ "Markdown", "JavaScript" ]
2
Markdown
elantion/webpack-startup
0c057e970b955afc678594bae7bacae0685a5500
3eea5ba2340f622c8bf53bde880179daaaf5f9c1
refs/heads/master
<repo_name>amberwilson/pluralsight-js-dev-env<file_sep>/buildScripts/srcServer.js import express from "express"; import path from "path"; import webpack from "webpack"; import config from "../webpack.config.dev"; /* eslint-disable no-console */ const port = 3000; const app = express(); const compiler = webpack(config); app.use( require("webpack-dev-middleware")(compiler, { noInfo: true, publicPath: config.output.publicPath }) ); app.get("/", (req, res) => { res.sendFile(path.join(__dirname, "../src/index.html")); }); app.get("/users", (req, res) => { // Hard coding for simplicity. Pretend this hits a real database. https://www.mockaroo.com/ res.json([ {"id":"652bb054-c2cf-45c4-a9d9-8ba3522c1e4d","firstName":"Karena","lastName":"Fer","email":"<EMAIL>"}, {"id":"410bf1fb-fcac-406c-ac97-3016009f10f6","firstName":"Carley","lastName":"Cosans","email":"<EMAIL>"}, {"id":"081ecfe8-0f8b-498d-9d1d-3af454783132","firstName":"Rriocard","lastName":"MacGiany","email":"<EMAIL>"}, {"id":"3f75054f-3506-41bc-ba64-e8b2f8d942b2","firstName":"Ira","lastName":"Stovin","email":"<EMAIL>"}, {"id":"13246a95-8dbb-4806-823b-7d6c5fc34924","firstName":"Ozzy","lastName":"Heynen","email":"<EMAIL>"}, {"id":"cf28e841-534d-4aa6-8972-f9d933a9a086","firstName":"Weylin","lastName":"Daintrey","email":"<EMAIL>"}, {"id":"deb58939-ebf1-4cd0-8c08-f752ca2919d8","firstName":"Faustine","lastName":"Chattell","email":"<EMAIL>"}, {"id":"fabf8656-2f1d-42ad-aeca-9b7990e30dd3","firstName":"Gusty","lastName":"Seamans","email":"<EMAIL>"}, {"id":"a90be49e-9e43-4b75-9f72-28cdeac5fa30","firstName":"Marybeth","lastName":"Pexton","email":"<EMAIL>"}, {"id":"4ffd0937-5a44-4746-9c47-16a18f80c7fb","firstName":"Diann","lastName":"Georgi","email":"<EMAIL>"} ]); }); app.listen(port, err => { if (err) { console.log(err); } else { console.log(`Server is running... http://localhost:${port}`); } }); <file_sep>/src/api/userApi.js import getBaseUrl from "./baseUrl"; const baseUrl = getBaseUrl(); export const getUsers = () => get("users"); export const deleteUser = id => del(`users/${id}`); const onSuccess = response => response.json(); const onError = error => console.log(error); // eslint-disable-line no-console const get = url => fetch(baseUrl + url).then(onSuccess, onError); // Can't call the function "delete" since it's a reserved word. const del = url => { const request = new Request(baseUrl + url, { method: "DELETE" }); return fetch(request).then(onSuccess, onError); }; <file_sep>/README.md # pluralsight-js-dev-env JavaScript Development Environment from Pluralsight Course UP NEXT: https://app.pluralsight.com/player?course=javascript-development-environment&author=cory-house&name=javascript-development-environment-m7&clip=0
cabd654da10bd91917975d701e5c8b9ecd0993c2
[ "JavaScript", "Markdown" ]
3
JavaScript
amberwilson/pluralsight-js-dev-env
61e98a717f3a94146c383944b467515a5a088123
25d735024e4ca9856cf072f808165c829f58a468
refs/heads/master
<file_sep>package com.quincy.auth.freemarker; import java.io.IOException; import java.io.Writer; import java.util.List; import java.util.Map; import com.quincy.auth.AuthHelper; import com.quincy.auth.o.XSession; import freemarker.core.Environment; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; public abstract class AbstractHtmlTemplateDirectiveModel implements TemplateDirectiveModel { protected abstract String reallyExecute(Environment env, Map params, TemplateModel[] loopVars) throws IOException; @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { boolean output = false; Object permission = params.get("permission"); if(permission==null) { output = true; } else { String permissionName = permission.toString(); XSession session = AuthHelper.getSession(); List<String> permissions = session.getPermissions(); for(String p:permissions) { if(p.equalsIgnoreCase(permissionName)) { output = true; break; } } } if(output) { String html = this.reallyExecute(env, params, loopVars); if(html!=null) { if(body!=null) { body.render(new PlaceHolderWriter(env.getOut(), html)); } else env.getOut().write(html); } } } private static class PlaceHolderWriter extends Writer { private final Writer out; private String html; public PlaceHolderWriter(Writer out, String html) { this.out = out; this.html = html; } @Override public void write(char[] cbuf, int off, int len) throws IOException { int index = html.indexOf("</"); StringBuilder sb = new StringBuilder(200).append(html.substring(0, index)).append(cbuf).append(html.substring(index, html.length())); out.write(sb.toString()); } @Override public void flush() throws IOException { out.flush(); } @Override public void close() throws IOException { out.close(); } } }<file_sep>vcode.null=Verification code is required. vcode.expire=Verification code you have got is expired, please reference a new. vcode.not_matched=Verification code is inputed incorrectly.<file_sep>package com.quincy.core.entity; import java.util.Date; import java.util.List; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.EntityListeners; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Transient; import lombok.Data; @Data @DynamicInsert @DynamicUpdate @EntityListeners({AuditingEntityListener.class}) @Entity(name = "s_transaction") public class Transaction { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id") private Long id; @Column(name="application_name") private String applicationName; @Column(name="bean_name") private String beanName; @Column(name="method_name") private String methodName; @Column(name="creation_time") private Date creationTime; @Column(name="last_executed") private Date lastExecuted; @Column(name="type") private Integer type;//0失败重试(定时任务执行status为0的原子操作); 1失败撤消(定时任务执行status为1的原子操作) @Column(name="status") private Integer status;//0正在执行; 1执行结束 @Column(name="version") private Integer version; @Column(name="frequency_batch") private String frequencyBatch;//频率批次名称 @Column(name="in_order") private Boolean inOrder;//是否有顺序 @Transient private Object[] args; @Transient private Class<?>[] parameterTypes; @Transient private List<TransactionAtomic> atomics; } <file_sep>package com.quincy.core; import org.apache.commons.pool2.impl.AbandonedConfig; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class CommonApplicationContext2 { @Value("${pool.maxTotal:#{null}}") private Integer maxTotal; @Value("${pool.maxIdle:#{null}}") private Integer maxIdle; @Value("${pool.minIdle:#{null}}") private Integer minIdle; @Value("${pool.maxWaitMillis:#{null}}") private Long maxWaitMillis; @Value("${pool.minEvictableIdleTimeMillis:#{null}}") private Long minEvictableIdleTimeMillis; @Value("${pool.timeBetweenEvictionRunsMillis:#{null}}") private Long timeBetweenEvictionRunsMillis; @Value("${pool.numTestsPerEvictionRun:#{null}}") private Integer numTestsPerEvictionRun; @Value("${pool.blockWhenExhausted:#{null}}") private Boolean blockWhenExhausted; @Value("${pool.testOnBorrow:#{null}}") private Boolean testOnBorrow; @Value("${pool.testOnCreate:#{null}}") private Boolean testOnCreate; @Value("${pool.testOnReturn:#{null}}") private Boolean testOnReturn; @Value("${pool.testWhileIdle:#{null}}") private Boolean testWhileIdle; @Value("${pool.fairness:#{null}}") private Boolean fairness; @Value("${pool.lifo:#{null}}") private Boolean lifo; @Value("${pool.evictionPolicyClassName:#{null}}") private String evictionPolicyClassName; @Value("${pool.softMinEvictableIdleTimeMillis:#{null}}") private Long softMinEvictableIdleTimeMillis; @Value("${pool.jmxEnabled:#{null}}") private Boolean jmxEnabled; @Value("${pool.jmxNameBase:#{null}}") private String jmxNameBase; @Value("${pool.jmxNamePrefix:#{null}}") private String jmxNamePrefix; @Bean public GenericObjectPoolConfig genericObjectPoolConfig() { // String maxTotal = CommonHelper.trim(properties.getProperty("pool.maxTotal")); // String maxIdle = CommonHelper.trim(properties.getProperty("pool.maxIdle")); // String minIdle = CommonHelper.trim(properties.getProperty("pool.minIdle")); // String maxWaitMillis = CommonHelper.trim(properties.getProperty("pool.maxWaitMillis")); // String minEvictableIdleTimeMillis = CommonHelper.trim(properties.getProperty("pool.minEvictableIdleTimeMillis")); // String timeBetweenEvictionRunsMillis = CommonHelper.trim(properties.getProperty("pool.timeBetweenEvictionRunsMillis")); // String numTestsPerEvictionRun = CommonHelper.trim(properties.getProperty("pool.numTestsPerEvictionRun")); // String blockWhenExhausted = CommonHelper.trim(properties.getProperty("pool.blockWhenExhausted")); // String testOnBorrow = CommonHelper.trim(properties.getProperty("pool.testOnBorrow")); // String testOnCreate = CommonHelper.trim(properties.getProperty("pool.testOnCreate")); // String testOnReturn = CommonHelper.trim(properties.getProperty("pool.testOnReturn")); // String testWhileIdle = CommonHelper.trim(properties.getProperty("pool.testWhileIdle")); // String fairness = CommonHelper.trim(properties.getProperty("pool.fairness")); // String lifo = CommonHelper.trim(properties.getProperty("pool.lifo")); // String evictionPolicyClassName = CommonHelper.trim(properties.getProperty("pool.evictionPolicyClassName")); // String softMinEvictableIdleTimeMillis = CommonHelper.trim(properties.getProperty("pool.softMinEvictableIdleTimeMillis")); // String jmxEnabled = CommonHelper.trim(properties.getProperty("pool.jmxEnabled")); // String jmxNameBase = CommonHelper.trim(properties.getProperty("pool.jmxNameBase")); // String jmxNamePrefix = CommonHelper.trim(properties.getProperty("pool.jmxNamePrefix")); GenericObjectPoolConfig poolParams = new GenericObjectPoolConfig(); if(maxTotal!=null) poolParams.setMaxTotal(maxTotal); if(maxIdle!=null) poolParams.setMaxIdle(maxIdle); if(minIdle!=null) poolParams.setMinIdle(minIdle); if(maxWaitMillis!=null) poolParams.setMaxWaitMillis(maxWaitMillis); if(minEvictableIdleTimeMillis!=null) poolParams.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); if(timeBetweenEvictionRunsMillis!=null) poolParams.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); if(numTestsPerEvictionRun!=null) poolParams.setNumTestsPerEvictionRun(numTestsPerEvictionRun); if(blockWhenExhausted!=null) poolParams.setBlockWhenExhausted(blockWhenExhausted); if(testOnBorrow!=null) poolParams.setTestOnBorrow(testOnBorrow); if(testOnCreate!=null) poolParams.setTestOnCreate(testOnCreate); if(testOnReturn!=null) poolParams.setTestOnReturn(testOnReturn); if(testWhileIdle!=null) poolParams.setTestWhileIdle(testWhileIdle); if(fairness!=null) poolParams.setFairness(fairness); if(lifo!=null) poolParams.setLifo(lifo); if(evictionPolicyClassName!=null) poolParams.setEvictionPolicyClassName(evictionPolicyClassName); if(softMinEvictableIdleTimeMillis!=null) poolParams.setSoftMinEvictableIdleTimeMillis(softMinEvictableIdleTimeMillis); if(jmxEnabled!=null) poolParams.setJmxEnabled(jmxEnabled); if(jmxNameBase!=null) poolParams.setJmxNameBase(jmxNameBase); if(jmxNamePrefix!=null) poolParams.setJmxNamePrefix(jmxNamePrefix); return poolParams; } @Value("${pool.removeAbandonedOnMaintenance:#{null}}") private Boolean removeAbandonedOnMaintenance; @Value("${pool.removeAbandonedOnBorrow:#{null}}") private Boolean removeAbandonedOnBorrow; @Value("${pool.removeAbandonedTimeout:#{null}}") private Integer removeAbandonedTimeout; @Value("${pool.logAbandoned:#{null}}") private Boolean logAbandoned; @Value("${pool.useUsageTracking:#{null}}") private Boolean useUsageTracking; @Value("${pool.requireFullStackTrace:#{null}}") private String requireFullStackTrace; @Bean public AbandonedConfig abandonedConfig() { AbandonedConfig ac = new AbandonedConfig(); if(removeAbandonedOnMaintenance!=null) ac.setRemoveAbandonedOnMaintenance(removeAbandonedOnMaintenance);//在Maintenance的时候检查是否有泄漏 if(removeAbandonedOnBorrow!=null) ac.setRemoveAbandonedOnBorrow(removeAbandonedOnBorrow);//borrow的时候检查泄漏 if(removeAbandonedTimeout!=null) ac.setRemoveAbandonedTimeout(removeAbandonedTimeout);//如果一个对象borrow之后n秒还没有返还给pool,认为是泄漏的对象 if(logAbandoned!=null) ac.setLogAbandoned(logAbandoned); if(useUsageTracking!=null) ac.setUseUsageTracking(useUsageTracking); /*if(requireFullStackTrace!=null) ac.setRequireFullStackTrace(Boolean.parseBoolean(requireFullStackTrace));*/ // ac.setLogWriter(logWriter); return ac; } }<file_sep>package com.quincy.core.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; import org.springframework.core.annotation.Order; import com.quincy.sdk.annotation.DeprecatedSynchronized; import com.quincy.sdk.helper.AopHelper; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPubSub; @Aspect @Order(2) @Component public class DeprecatedSynchronizedAop extends JedisNeededBaseAop { private final static String SET_KEY = "SYNCHRONIZATION"; @Pointcut("@annotation(com.quincy.sdk.annotation.DeprecatedSynchronized)") public void pointCut() {} @Override protected Object before(JoinPoint joinPoint, Jedis jedis) throws NoSuchMethodException, SecurityException, InterruptedException { DeprecatedSynchronized annotation = AopHelper.getAnnotation(joinPoint, DeprecatedSynchronized.class); String key = annotation.value(); String channels = SET_KEY+"_"+key; while(true) { if(jedis.sismember(SET_KEY, key)||jedis.sadd(SET_KEY, key)==0) jedis.subscribe(new MyListener(), channels); else //Successfully held the distributed lock. break; } return key; } @Override protected void after(JoinPoint joinPoint, Jedis jedis, Object obj) { String key = obj.toString(); jedis.srem(SET_KEY, key); jedis.publish(SET_KEY+"_"+key, "Finished"); } public class MyListener extends JedisPubSub { public void onMessage(String channel, String message) { this.unsubscribe(); } } }<file_sep>oauth2.error.server.1=Please contact administrator for OAuthProblemException at server end point. oauth2.error.server.2=Please contact administrator for internal error at server end point. oauth2.error.server.3=The client platform has not been registered into our platform. oauth2.error.server.4=Client secret authentication failed. oauth2.error.server.5=redirect_uri must be present if message format is not JSON. oauth2.error.server.6=Username is required. oauth2.error.server.7=Scope is required. oauth2.error.server.8=Account cannot be found. oauth2.error.server.9=The client platform for this resource has not been authorized by the owner. oauth2.error.server.10=Authorization code cannot be matched to client_id. oauth2.error.server.11=Authentication failed.<file_sep>package com.quincy.core; public class DTransactionConstants { public final static int ARG_TYPE_TX = 0; public final static int ARG_TYPE_ATOMIC = 1; public final static int ATOMIC_STATUS_INIT_FAILURE = 0; public final static int ATOMIC_STATUS_SUCCESS = 1; public final static int ATOMIC_STATUS_CANCELED = 2; public final static int TX_STATUS_ING = 0; public final static int TX_STATUS_ED = 1; public final static int TX_TYPE_CONFIRM = ATOMIC_STATUS_INIT_FAILURE; public final static int TX_TYPE_CANCEL = ATOMIC_STATUS_SUCCESS; public final static String REFERENCE_TO = "REFERENCE_TO: "; }<file_sep>package com.quincy.core.zookeeper; import org.apache.commons.pool2.impl.AbandonedConfig; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.apache.zookeeper.Watcher; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.lang.Nullable; import com.quincy.core.zookeeper.impl.ZooKeeperSourceImpl; public class ZooKeeperSourceBean implements FactoryBean<ZooKeeperSource>, InitializingBean { private String url; private int timeout; private Watcher watcher; private GenericObjectPoolConfig poolCfg; private AbandonedConfig abandonedCfg; private boolean singleton = true; @Nullable private ZooKeeperSource singletonInstance; public ZooKeeperSourceBean(String url, int timeout, Watcher watcher, GenericObjectPoolConfig poolCfg, AbandonedConfig abandonedCfg) { this.url = url; this.timeout = timeout; this.watcher = watcher; this.poolCfg = poolCfg; this.abandonedCfg = abandonedCfg; } @Override public ZooKeeperSource getObject() throws Exception { return this.singletonInstance; } @Override public Class<ZooKeeperSource> getObjectType() { return ZooKeeperSource.class; } public final void setSingleton(boolean singleton) { this.singleton = singleton; } @Override public final boolean isSingleton() { return this.singleton; } @Override public void afterPropertiesSet() throws ClassNotFoundException, InstantiationException, IllegalAccessException { if(this.singleton) this.singletonInstance = create(); } private ZooKeeperSource create() throws ClassNotFoundException, InstantiationException, IllegalAccessException { PoolableZooKeeperFactory f = new PoolableZooKeeperFactory(url, timeout, watcher); return new ZooKeeperSourceImpl(f, poolCfg, abandonedCfg); } }<file_sep>package com.quincy.core; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.quincy.core.zookeeper.ZooKeeperSource; @Component public class ZooKeeperDeamon { @Autowired private ZooKeeperSource zooKeeperSource; @Autowired @Qualifier("zookeeperRootNode") private String zookeeperRootNode; @Autowired @Qualifier("zookeeperSynchronizationNode") private String zookeeperSynchronizationNode; @Value("#{'${zk.distributedLock.keys}'.split(',')}") private String[] distributedLockKeys; @PostConstruct public void init() throws Exception { ZooKeeper zk = null; try { zk = zooKeeperSource.get(); Stat stat = zk.exists(zookeeperRootNode, false); if(stat==null) zk.create(zookeeperRootNode, "Root".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); stat = zk.exists(zookeeperSynchronizationNode, false); if(stat==null) zk.create(zookeeperSynchronizationNode, "Distributed Locks".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); for(String key:distributedLockKeys) { String path = zookeeperSynchronizationNode+"/"+key; stat = zk.exists(path, false); if(stat==null) zk.create(path, "Distributed Locks's Executions".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } finally { if(zk!=null) zk.close(); } } @PreDestroy public void destroy() { if(zooKeeperSource!=null) zooKeeperSource.close(); } }<file_sep>package com.quincy.auth.interceptor; import java.lang.reflect.Method; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import com.quincy.auth.annotation.LoginRequired; import com.quincy.auth.annotation.PermissionNeeded; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @Component("authorizationAnnotationInterceptor") public class AuthorizationAnnotationInterceptor extends AuthorizationInterceptorSupport { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if(handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod)handler; Method method = handlerMethod.getMethod(); PermissionNeeded permissionNeededAnnotation = method.getDeclaredAnnotation(PermissionNeeded.class); boolean permissionNeeded = permissionNeededAnnotation!=null; boolean loginRequired = method.getDeclaredAnnotation(LoginRequired.class)!=null; if(!permissionNeeded&&!loginRequired) { // boolean deleteCookieIfExpired = method.getDeclaredAnnotation(KeepCookieIfExpired.class)==null; // this.setExpiry(request, deleteCookieIfExpired); return true; } else return this.doAuth(request, response, handler, permissionNeeded?permissionNeededAnnotation.value():null); } else return true; } }<file_sep>package com.quincy.auth.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; import com.quincy.auth.entity.ClientSystem; @Repository public interface ClientSystemRepository extends JpaRepository<ClientSystem, Long>, JpaSpecificationExecutor<ClientSystem> { public ClientSystem findByClientId(String clientId); }<file_sep>package com.quincy.sdk.helper; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Properties; import java.util.UUID; import org.apache.commons.codec.digest.HmacAlgorithms; public class AliyunDNTXTUpdate { private final static String HTTP_PREFIX = "https://alidns.aliyuncs.com/?"; private final static String ACTION_UPDATE = "UpdateDomainRecord"; private final static String CHARSET_UTF8 = "UTF-8"; public static void main(String[] args) throws IOException, InvalidKeyException, NoSuchAlgorithmException { Properties pro = new Properties(); InputStream in = null; String id = null; String secret = null; try { in = new FileInputStream(args[0]); pro.load(in); id = pro.getProperty("aliyun.id"); secret = pro.getProperty("aliyun.secret"); } finally { if(in!=null) in.close(); } String action = args[1]; String domain = args[2]; String signatureNonce = UUID.randomUUID().toString().replaceAll("-", ""); Calendar c = Calendar.getInstance(); int zoneOffset = c.get(Calendar.ZONE_OFFSET); c.add(Calendar.HOUR, -(zoneOffset/1000/3600)); String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(c.getTime()); timestamp = timestamp.replaceAll("\\s+", "T")+"Z"; timestamp = URLEncoder.encode(timestamp, CHARSET_UTF8); StringBuilder params = new StringBuilder(500).append("AccessKeyId=").append(id).append("&Action=").append(action); if("DescribeDomainRecords".equals(action)) params.append("&DomainName=").append(domain); params.append("&Format=JSON"); if(ACTION_UPDATE.equals(action)) params.append("&RR=%2A&RecordId=").append(args[3]); params.append("&SignatureMethod=HMAC-SHA1&SignatureNonce=").append(signatureNonce).append("&SignatureVersion=1.0&Timestamp=").append(timestamp); if(ACTION_UPDATE.equals(action)) params.append("&Type=TXT&Value=").append(args[4]); params.append("&Version=2015-01-09"); String stringToSign = "GET&%2F&"+URLEncoder.encode(params.toString(), CHARSET_UTF8); String signature = SecurityHelper.encrypt(HmacAlgorithms.HMAC_SHA_1.getName(), CHARSET_UTF8, secret+"&", stringToSign); String urlEncodedSignature = URLEncoder.encode(signature, CHARSET_UTF8); System.out.println(stringToSign+"\r\n"+signature+"\r\n"+urlEncodedSignature); params.append("&Signature=").append(urlEncodedSignature); String url = HTTP_PREFIX+params.toString(); System.out.println(url); // System.out.println(URLDecoder.decode("%2A", CHARSET_UTF8)+"---"+URLEncoder.encode("*", CHARSET_UTF8)); SimplifiedHttpResponse response = HttpClientHelper.get(url, null, null); String result = response.getContent(); System.out.println(result); } }<file_sep>package com.quincy.sdk; public interface ZKContext { public String getRootPath(); public String getSynPath(); }<file_sep>package com.quincy.core; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import javax.annotation.PreDestroy; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.quincy.core.redis.JedisSource; import com.quincy.core.redis.QuincyJedis; import lombok.extern.slf4j.Slf4j; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisSentinelPool; import redis.clients.jedis.util.Pool; @Slf4j @Configuration public class RedisApplicationContext { @Value("${spring.application.name}") private String applicationName; @Value("#{'${spring.redis.nodes}'.split(',')}") private String[] _clusterNodes; @Value("${spring.redis.password}") private String redisPwd; @Value("${spring.redis.timeout}") private int connectionTimeout; @Value("${spring.redis.sentinel.master:#{null}}") private String sentinelMaster; @Value("${spring.redis.cluster.soTimeout}") private int soTimeout; @Value("${spring.redis.cluster.maxAttempts}") private int maxAttempts; @Autowired private GenericObjectPoolConfig poolCfg; private static Pool<Jedis> pool; private static QuincyJedis quincyJedis; @Bean(InnerConstants.BEAN_NAME_SYS_JEDIS_SOURCE) public JedisSource jedisPool() { if(_clusterNodes.length>1) { Set<String> clusterNodes = new HashSet<String>(Arrays.asList(_clusterNodes)); if(sentinelMaster!=null) {//哨兵 pool = new JedisSentinelPool(sentinelMaster, clusterNodes, poolCfg, connectionTimeout, redisPwd); log.info("REDIS_MODE============SENTINEL"); } else {//集群 Set<HostAndPort> clusterNodes_ = new HashSet<HostAndPort>(clusterNodes.size()); for(String node:clusterNodes) { String[] ss = node.split(":"); clusterNodes_.add(new HostAndPort(ss[0], Integer.valueOf(ss[1]))); } quincyJedis = new QuincyJedis(new JedisCluster(clusterNodes_, connectionTimeout, soTimeout, maxAttempts, redisPwd, poolCfg)); log.info("REDIS_MODE============CLUSTER"); return new JedisSource() { @Override public Jedis get() { return quincyJedis; } }; } } else {//单机 String[] ss = _clusterNodes[0].split(":"); String redisHost = ss[0]; int redisPort = Integer.parseInt(ss[1]); pool = new JedisPool(poolCfg, redisHost, redisPort, connectionTimeout, redisPwd); log.info("REDIS_MODE============SINGLETON"); } return new JedisSource() { @Override public Jedis get() { return pool.getResource(); } }; } @Bean("cacheKeyPrefix") public String cacheKeyPrefix() { return applicationName+".cache."; } @PreDestroy private void destroy() throws IOException { if(pool!=null) pool.close(); if(quincyJedis!=null) { JedisCluster jedisCluster = quincyJedis.getJedisCluster(); if(jedisCluster!=null) jedisCluster.close(); } } }<file_sep>package com.quincy.sdk.annotation.sharding; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.quincy.sdk.MasterOrSlave; @Documented @Retention(value = RetentionPolicy.RUNTIME) @Target(value = {ElementType.METHOD}) public @interface ExecuteQuery { public String sql(); public MasterOrSlave masterOrSlave(); public Class<?> returnItemType(); public boolean anyway() default false; }<file_sep>package com.quincy.sdk.helper; public class SimplifiedHttpResponse { private String content; private String sessionId; public SimplifiedHttpResponse(String content, String sessionId) { this.content = content; this.sessionId = sessionId; } public String getContent() { return content; } public String getSessionId() { return sessionId; } } <file_sep>package com.quincy.sdk; public enum Client { PC(1, "pc"), WAP(2, "wap"), APP(3, "app"); private int code; private String name; private Client(int code, String name) { this.code = code; this.name = name; } public Client get(int code) { for (Client c : Client.values()) { if(c.getCode()==code) return c; } return null; } public int getCode() { return code; } public String getName() { return this.name; } }<file_sep>package com.quincy.core.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; import com.quincy.core.entity.Transaction; @Repository public interface TransactionRepository extends JpaRepository<Transaction, Long>, JpaSpecificationExecutor<Transaction> { public List<Transaction> findByApplicationNameAndStatus(String applicationName, int status); public List<Transaction> findByApplicationNameAndStatusAndFrequencyBatch(String applicationName, int status, String frequencyBatch); } <file_sep>package com.quincy.sdk.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.quincy.sdk.dao.RegionRepository; import com.quincy.sdk.entity.Region; import com.quincy.sdk.service.RegionService; @Service public class RegionServiceImpl implements RegionService { @Autowired private RegionRepository regionRepository; @Override public List<Region> findAll() { return regionRepository.findAll(); } @Override public List<Region> findCountries() { return regionRepository.findByParentId(0l); } } <file_sep>package com.quincy.auth.controller; public enum VCodeCharsFrom { DIGITS("0123456789"), MIXED("23456789abcdefghijkmnpqrstuvwxyzABCDEFGHLJKMNPQRSTUVWXYZ"); private String value; private VCodeCharsFrom(String value) { this.value = value; } public String getValue() { return this.value; } }<file_sep><?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <artifactId>quincy-jdbc</artifactId> <name>JDBC</name> <url>https://github.com/mq7253180/sdk/tree/master/db</url> <parent> <groupId>com.maqiangcgq</groupId> <artifactId>all</artifactId> <version>1.1.2</version> </parent> <dependencies> <dependency> <groupId>com.maqiangcgq</groupId> <artifactId>quincy-jdbc-base</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>javax.transaction-api</artifactId> <version>1.3</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.0.33</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.9.0</version><!-- commons-pool2: 2.10.0, GLOBAL: 2.11.1 --> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.3.2</version> </dependency> <!-- Hibernate注解 --> <dependency> <groupId>org.hibernate.orm</groupId> <artifactId>hibernate-core</artifactId> <version>6.1.4.Final</version> <scope>compile</scope> <exclusions> <exclusion> <artifactId>jboss-transaction-api_1.2_spec</artifactId> <groupId>org.jboss.spec.javax.transaction</groupId> </exclusion> </exclusions> </dependency> <dependency> <!-- org.springframework.data.jpa.domain.support.AuditingEntityListener --> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>3.0.4</version><!-- 匹配Spring版本: 6.0.7 --> <scope>compile</scope> <exclusions> <exclusion> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> </exclusion> <exclusion> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> </exclusion> </exclusions> </dependency> <!-- MyBatis注解; Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required --> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.11</version> </dependency> <!-- 脱离Spring Boot加载JPA抛异常: java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy --> <!-- dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>6.0.7</version> <scope>compile</scope> </dependency--> <dependency> <!-- org.hibernate.boot.spi.XmlMappingBinderAccess.<init>: java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException --> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency> </dependencies> </project><file_sep>package com.quincy.auth.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import com.quincy.auth.entity.Permission; import com.quincy.auth.entity.Role; import com.quincy.auth.o.Menu; @Repository public interface AuthMapper { public List<Role> findRolesByUserId(@Param("userId")Long userId); public List<Permission> findPermissionsByUserId(@Param("userId")Long userId); public List<Menu> findMenusByUserId(@Param("userId")Long userId); }<file_sep>package com.quincy.sdk; import redis.clients.jedis.Jedis; public interface RedisProcessor { public String setAndExpire(String key, String val, int expireSeconds, int retries, long retryIntervalMillis, Jedis jedis); public String setAndExpire(byte[] key, byte[] val, int expireSeconds, int retries, long retryIntervalMillis, Jedis jedis); public String setAndExpire(String key, String val, int expireSeconds, int retries, long retryIntervalMillis); public String setAndExpire(byte[] key, byte[] val, int expireSeconds, int retries, long retryIntervalMillis); public String setAndExpire(String key, String val, int expireSeconds, Jedis jedis); public String setAndExpire(byte[] key, byte[] val, int expireSeconds, Jedis jedis); public String setAndExpire(String key, String val, int expireSeconds); public String setAndExpire(byte[] key, byte[] val, int expireSeconds); }<file_sep>package com.quincy.auth.interceptor; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import org.springframework.web.servlet.support.RequestContext; import com.quincy.auth.AuthCommonConstants; import com.quincy.auth.AuthHelper; import com.quincy.auth.o.XSession; import com.quincy.core.InnerHelper; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; public abstract class AuthorizationInterceptorSupport extends HandlerInterceptorAdapter { @Autowired @Qualifier("signinUrl") private String signinUrl; @Autowired @Qualifier("denyUrl") private String denyUrl; protected boolean doAuth(HttpServletRequest request, HttpServletResponse response, Object handler, String permissionNeeded) throws Exception { XSession xsession = AuthHelper.getSession(request);//authorizationService.getSession(request); if(xsession==null) { InnerHelper.outputOrForward(request, response, handler, 0, new RequestContext(request).getMessage("auth.timeout.ajax"), signinUrl, true); return false; } else { if(permissionNeeded!=null) { List<String> permissions = xsession.getPermissions(); boolean hasPermission = false; for(String permission:permissions) { if(permission.equals(permissionNeeded)) { hasPermission = true; break; } } if(!hasPermission) { String deniedPermissionName = AuthCommonConstants.PERMISSIONS==null?null:AuthCommonConstants.PERMISSIONS.get(permissionNeeded); if(deniedPermissionName==null) deniedPermissionName = permissionNeeded; request.setAttribute(AuthCommonConstants.ATTR_DENIED_PERMISSION, deniedPermissionName); InnerHelper.outputOrForward(request, response, handler, -1, new RequestContext(request).getMessage("status.error.403")+"["+deniedPermissionName+"]", denyUrl, true); return false; } } // request.setAttribute(InnerConstants.ATTR_SESSION, xsession); return true; } } }<file_sep>package com.quincy.core; import javax.annotation.Resource; import org.apache.commons.pool2.impl.AbandonedConfig; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.apache.zookeeper.Watcher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.quincy.core.zookeeper.ContextConstants; import com.quincy.core.zookeeper.ZooKeeperSourceBean; import com.quincy.sdk.ZKContext; import com.quincy.sdk.helper.CommonHelper; @Configuration public class ZooKeeperConfiguration implements ZKContext { @Value("${spring.application.name}") private String applicationName; @Value("${zk.url}") private String url; @Value("${zk.timeout}") private int timeout; @Value("${zk.watcher}") private String watcher; @Autowired private GenericObjectPoolConfig poolCfg; @Autowired private AbandonedConfig abandonedCfg; @Autowired private ApplicationContext applicationContext; @Bean public ZooKeeperSourceBean zkSourceBean() throws ClassNotFoundException, InstantiationException, IllegalAccessException { Watcher w = applicationContext.getBean(CommonHelper.trim(watcher), Watcher.class); ZooKeeperSourceBean b = new ZooKeeperSourceBean(url, timeout, w, poolCfg, abandonedCfg); b.afterPropertiesSet(); return b; } @Bean("zookeeperRootNode") public String zookeeperRootNode() { return "/"+applicationName; } @Autowired @Qualifier("zookeeperRootNode") private String zookeeperRootNode; @Bean("zookeeperSynchronizationNode") public String zookeeperSynchronizationNode() { return zookeeperRootNode+"/"+ContextConstants.SYN_NODE; } @Autowired @Qualifier("zookeeperSynchronizationNode") private String zookeeperSynchronizationNode; @Override public String getRootPath() { return zookeeperRootNode; } @Override public String getSynPath() { return zookeeperSynchronizationNode; } }<file_sep>package com.quincy.core.entity; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.EntityListeners; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import lombok.Data; @Data @DynamicInsert @DynamicUpdate @EntityListeners({AuditingEntityListener.class}) @Entity(name = "s_transaction_arg") public class TransactionArg { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id") private Long id; @Column(name="parent_id") private Long parentId; @Column(name="class") private String clazz; @Column(name="_value") private String value; @Column(name="sort") private Integer sort; @Column(name="type") private Integer type; } <file_sep>auth.timeout.broker=\u6703\u8A71\u8D85\u6642\uFF0C\u6B63\u5728\u8DF3\u8F49... auth.success=\u767B\u9304\u6210\u529F auth.null.username=\u8CEC\u865F\u4E0D\u80FD\u70BA\u7A7A auth.null.password=\<PASSWORD> auth.account.no=\u7121\u6548\u8CEC\u865F auth.account.pwd_incorrect=\<PASSWORD> title.login=\u767B\u9304 title.error=\u932f\u8aa4\u9801 <file_sep>package com.quincy.core.db; import com.quincy.sdk.MasterOrSlave; public class SingleDataSourceHolder extends DataSourceHolder { public static void setMaster() { set(MasterOrSlave.MASTER.value()); } public static void setSlave() { set(MasterOrSlave.SLAVE.value()); } }<file_sep>package com.quincy.core.sftp; import com.jcraft.jsch.ChannelSftp; public interface ChannelSftpSource { public ChannelSftp get() throws Exception; public void close(); } <file_sep>package com.quincy.auth; import java.util.Map; import jakarta.servlet.http.HttpServletRequest; public interface AuthHandler { /** * 如果auth.loginRequired.root=true设置了/需要登录,用于给ModelAndView设置定制化输入对象,用于在模板上引用 * @param request * @return * @throws Exception */ public Map<String, ?> rootViewObjects(HttpServletRequest request) throws Exception; }<file_sep>package com.quincy.sdk.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Retention(value = RetentionPolicy.RUNTIME) @Target(value = {ElementType.METHOD}) public @interface Cache { public int expire() default 60; public String key() default ""; public int setnxDelaySecs() default 3; public int setnxFailRetries() default 3; public long intervalMillis() default 1000; public boolean returnNull() default true; }<file_sep>package com.quincy.core; import org.reflections.Reflections; public class ReflectionsHolder { private static Reflections reflections = null; private static Object lock = new Object(); public static Reflections get() { if(reflections==null) { synchronized(lock) { if(reflections==null) reflections = new Reflections("com"); } } return reflections; } }<file_sep>package com.quincy.auth; import com.quincy.auth.o.XSession; import com.quincy.core.InnerConstants; import com.quincy.sdk.helper.CommonHelper; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; public class AuthHelper { public static XSession getSession(HttpServletRequest request) { HttpSession session = request.getSession(false); XSession xsession = session==null?null:(XSession)session.getAttribute(InnerConstants.ATTR_SESSION); return xsession; } public static XSession getSession() { HttpServletRequest request = CommonHelper.getRequest(); return getSession(request); } }<file_sep>package com.quincy.core.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; import com.quincy.core.entity.TransactionAtomic; @Repository public interface TransactionAtomicRepository extends JpaRepository<TransactionAtomic, Long>, JpaSpecificationExecutor<TransactionAtomic> { public List<TransactionAtomic> findByTxIdAndStatusOrderBySort(Long txId, Integer status); public List<TransactionAtomic> findByTxIdAndStatusOrderBySortDesc(Long txId, Integer status); }<file_sep>package com.quincy.core.web.freemarker; import java.io.IOException; import java.util.Locale; import java.util.Map; import com.quincy.sdk.helper.CommonHelper; import freemarker.core.Environment; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; public class LocaleTemplateDirectiveModelBean implements TemplateDirectiveModel { @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { Locale locale = CommonHelper.getLocale(); env.getOut().write(locale.getLanguage()+"_"+locale.getCountry()); } }<file_sep>package com.quincy.core; import org.apache.commons.pool2.impl.AbandonedConfig; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.quincy.core.sftp.ChannelSftpSource; import com.quincy.core.sftp.PoolableChannelSftpFactory; import com.quincy.core.sftp.impl.ChannelSftpSourceImpl; @Configuration public class SFTPConfiguration { @Autowired private GenericObjectPoolConfig poolCfg; @Autowired private AbandonedConfig abandonedCfg; @Value("${sftp.host}") private String host; @Value("${sftp.port}") private int port; @Value("${sftp.username}") private String username; @Value("${sftp.privateKey}") private String privateKey; @Bean public ChannelSftpSource createChannelSftpSource() { PoolableChannelSftpFactory f = new PoolableChannelSftpFactory(host, port, username, privateKey); ChannelSftpSource s = new ChannelSftpSourceImpl(f, poolCfg, abandonedCfg); return s; } }<file_sep>package com.quincy.sdk; import redis.clients.jedis.Jedis; public interface RedisWebOperation { public Object run(Jedis jedis, String token) throws Exception; }<file_sep>package com.quincy.auth.service.impl; import java.io.IOException; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.quincy.auth.AuthSessionHolder; import com.quincy.auth.entity.Permission; import com.quincy.auth.entity.Role; import com.quincy.auth.mapper.AuthMapper; import com.quincy.auth.o.XSession; import com.quincy.auth.o.Menu; import com.quincy.auth.o.User; import com.quincy.auth.service.AuthCallback; import com.quincy.auth.service.AuthorizationServerService; import com.quincy.core.InnerConstants; import com.quincy.sdk.helper.CommonHelper; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; @Service public class AuthorizationServerServiceImpl implements AuthorizationServerService { @Autowired private AuthMapper authMapper; @Value("${auth.enterprise}") private boolean isEnterprise; protected XSession createSession(Long userId) { XSession session = new XSession(); if(isEnterprise) { //角色 List<Role> roleList = authMapper.findRolesByUserId(userId); Map<Long, String> roleMap = new HashMap<Long, String>(roleList.size()); for(Role role:roleList)//去重 roleMap.put(role.getId(), role.getName()); List<String> roles = new ArrayList<String>(roleMap.size()); roles.addAll(roleMap.values()); session.setRoles(roles); //权限 List<Permission> permissionList = authMapper.findPermissionsByUserId(userId); Map<Long, String> permissionMap = new HashMap<Long, String>(permissionList.size()); for(Permission permission:permissionList)//去重 permissionMap.put(permission.getId(), permission.getName()); List<String> permissions = new ArrayList<String>(permissionMap.size()); permissions.addAll(permissionMap.values()); session.setPermissions(permissions); //菜单 List<Menu> rootMenus = this.findMenusByUserId(userId); session.setMenus(rootMenus); } return session; } protected XSession createSession(User user) { XSession session = this.createSession(user.getId()); session.setUser(user); return session; } private List<Menu> findMenusByUserId(Long userId) { List<Menu> allMenus = authMapper.findMenusByUserId(userId); Map<Long, Menu> duplicateRemovedMenus = new HashMap<Long, Menu>(allMenus.size()); for(Menu menu:allMenus) duplicateRemovedMenus.put(menu.getId(), menu); List<Menu> rootMenus = new ArrayList<Menu>(duplicateRemovedMenus.size()); Set<Entry<Long, Menu>> entrySet = duplicateRemovedMenus.entrySet(); for(Entry<Long, Menu> entry:entrySet) { Menu menu = entry.getValue(); if(menu.getPId()==null) { rootMenus.add(menu); this.loadChildrenMenus(menu, entrySet); } } return rootMenus; } private void loadChildrenMenus(Menu parent, Set<Entry<Long, Menu>> entrySet) { for(Entry<Long, Menu> entry:entrySet) { Menu menu = entry.getValue(); if(parent.getId()==menu.getPId()) { if(parent.getChildren()==null) parent.setChildren(new ArrayList<Menu>(10)); parent.getChildren().add(menu); } } if(parent.getChildren()!=null&&parent.getChildren().size()>0) { for(Menu child:parent.getChildren()) this.loadChildrenMenus(child, entrySet); } } private void excludeSession(String originalJsessionid) { HttpSession httpSession = AuthSessionHolder.SESSIONS.remove(originalJsessionid); if(httpSession!=null) httpSession.invalidate(); } @Value("${server.servlet.session.timeout:#{null}}") private String sessionTimeout; @Value("${server.servlet.session.timeout.app:#{null}}") private String sessionTimeoutApp; @Override public XSession setSession(HttpServletRequest request, AuthCallback callback) { User user = callback.getUser(); String originalJsessionid = CommonHelper.trim(user.getJsessionid()); if(originalJsessionid!=null)//同一user不同客户端登录互踢 this.excludeSession(originalJsessionid); int maxInactiveInterval = -1; if(CommonHelper.isApp(request)) { maxInactiveInterval = sessionTimeoutApp==null?86400:Integer.parseInt(String.valueOf(Duration.parse(sessionTimeoutApp).getSeconds())); } else maxInactiveInterval = sessionTimeout==null?18000:Integer.parseInt(String.valueOf(Duration.parse(sessionTimeout).getSeconds())); HttpSession session = request.getSession(); session.setMaxInactiveInterval(maxInactiveInterval);//验证码接口会设置一个较短的超时时间,登录成功后在这里给恢复回来,如果没有设置取默认半小时 String jsessionid = session.getId(); user.setJsessionid(jsessionid); XSession xsession = this.createSession(user); session.setAttribute(InnerConstants.ATTR_SESSION, xsession); callback.updateLastLogined(jsessionid); return xsession; } @Override public void updateSession(User user) { String jsessionid = CommonHelper.trim(user.getJsessionid()); if(jsessionid!=null) { HttpSession session = AuthSessionHolder.SESSIONS.get(jsessionid); XSession xsession = this.createSession(user); session.setAttribute(InnerConstants.ATTR_SESSION, xsession); } } @Override public void updateSession(List<User> users) throws IOException { for(User user:users) this.updateSession(user); } }<file_sep>package com.quincy.auth.entity; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.EntityListeners; import jakarta.persistence.Id; import lombok.Data; @Data @DynamicInsert @DynamicUpdate @EntityListeners({AuditingEntityListener.class}) @Entity(name = "s_role") public class Role { @Id @Column(name="id") private Long id; // @ManyToMany(cascade = CascadeType.ALL) // @JoinTable(name = "s_role_permission_rel", joinColumns = {@JoinColumn(name = "role_id")}, inverseJoinColumns = {@JoinColumn(name = "permission_id")}) // private Set<Permission> permissions; @Column(name="name") private String name; }<file_sep>package com.quincy.core; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import javax.sql.DataSource; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.quincy.sdk.MasterOrSlave; import com.quincy.core.db.RoutingDataSource; @Configuration //@AutoConfigureAfter(CommonApplicationContext.class) //@Import(CommonApplicationContext.class) public class CoreApplicationContext {//implements TransactionManagementConfigurer { @Value("${spring.datasource.driver-class-name}") private String driverClassName; @Value("${spring.datasource.url}") private String masterUrl; @Value("${spring.datasource.username}") private String masterUserName; @Value("${spring.datasource.password}") private String masterPassword; @Value("${spring.datasource.url.slave}") private String slaveUrl; @Value("${spring.datasource.username.slave}") private String slaveUserName; @Value("${spring.datasource.password.slave}") private String slavePassword; @Value("${spring.datasource.pool.masterRatio}") private int masterRatio; @Autowired private DBCommonApplicationContext dbCommonApplicationContext; @Bean(name = "dataSource") public DataSource routingDataSource() throws SQLException { BasicDataSource masterDB = dbCommonApplicationContext.createBasicDataSource(1); masterDB.setDriverClassName(driverClassName); masterDB.setUrl(masterUrl); masterDB.setUsername(masterUserName); masterDB.setPassword(<PASSWORD>); masterDB.setDefaultAutoCommit(true); // masterDB.setAutoCommitOnReturn(true); masterDB.setRollbackOnReturn(false); masterDB.setDefaultReadOnly(false); BasicDataSource slaveDB = dbCommonApplicationContext.createBasicDataSource(masterRatio); slaveDB.setDriverClassName(driverClassName); slaveDB.setUrl(slaveUrl); slaveDB.setUsername(slaveUserName); slaveDB.setPassword(<PASSWORD>); slaveDB.setDefaultAutoCommit(false); // slaveDB.setAutoCommitOnReturn(false); slaveDB.setRollbackOnReturn(true); slaveDB.setDefaultReadOnly(true); Map<Object, Object> targetDataSources = new HashMap<Object, Object>(2); targetDataSources.put(MasterOrSlave.MASTER.value(), masterDB); targetDataSources.put(MasterOrSlave.SLAVE.value(), slaveDB); RoutingDataSource db = new RoutingDataSource(); db.setTargetDataSources(targetDataSources); db.setDefaultTargetDataSource(masterDB); return db; } }<file_sep>package com.quincy.auth; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.spec.InvalidKeySpecException; import java.util.HashMap; import java.util.List; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import com.quincy.auth.controller.RootController; import com.quincy.auth.dao.PermissionRepository; import com.quincy.auth.entity.Permission; import com.quincy.sdk.helper.RSASecurityHelper; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @Configuration public class AuthServerInitialization {//implements BeanDefinitionRegistryPostProcessor { @Autowired private RequestMappingHandlerMapping requestMappingHandlerMapping; @Autowired private RootController rootController; @Value("${auth.loginRequired.root:false}") private boolean loginRequiredForRoot; @Value("${secret.rsa.privateKey}") private String privateKeyStr; @PostConstruct public void init() throws NoSuchMethodException, SecurityException { this.loadPermissions(); if(loginRequiredForRoot) { RequestMappingInfo.BuilderConfiguration config = new RequestMappingInfo.BuilderConfiguration(); config.setPatternParser(requestMappingHandlerMapping.getPatternParser()); RequestMappingInfo requestMappingInfo = RequestMappingInfo .paths("/") .methods(RequestMethod.GET) .options(config) .build(); requestMappingHandlerMapping.registerMapping(requestMappingInfo, rootController, RootController.class.getMethod("root", HttpServletRequest.class, HttpServletResponse.class)); } } @PreDestroy private void destroy() { } @Autowired private PermissionRepository permissionRepository; private void loadPermissions() { List<Permission> permissoins = permissionRepository.findAll(); AuthCommonConstants.PERMISSIONS = new HashMap<String, String>(permissoins.size()); for(Permission permission:permissoins) { AuthCommonConstants.PERMISSIONS.put(permission.getName(), permission.getDes()); } } @Bean("selfPrivateKey") public PrivateKey privateKey() throws NoSuchAlgorithmException, InvalidKeySpecException { return RSASecurityHelper.extractPrivateKey(privateKeyStr); } /* private final static String SERVICE_BEAN_NAME_TO_REMOVE = "authorizationServerServiceSessionImpl"; @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { if (registry.containsBeanDefinition(SERVICE_BEAN_NAME_TO_REMOVE)) registry.removeBeanDefinition(SERVICE_BEAN_NAME_TO_REMOVE); } */ }<file_sep>package com.quincy.core.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; import com.quincy.core.entity.TransactionArg; @Repository public interface TransactionArgRepository extends JpaRepository<TransactionArg, Long>, JpaSpecificationExecutor<TransactionArg> { public List<TransactionArg> findByParentIdAndTypeOrderBySort(Long parentId, Integer type); }<file_sep>mybatis.config-location=classpath:mybatis.xml mybatis.mapper-locations=classpath*:mybatis/*.xml <file_sep>package com.quincy.core.mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; @Repository public interface CoreMapper { public int deleteTransactionAtomicArgs(@Param("txId")Long txId); public int deleteTransactionAtomics(@Param("txId")Long txId); public int deleteArgs(@Param("parentId")Long parentId, @Param("type")Integer type); public int deleteTransaction(@Param("id")Long id); public int updateTransactionVersion(@Param("id")Long id, @Param("version")Integer version); public int updateTransactionAtomicArgs(@Param("txId")Long txId, @Param("classFrom")String classFrom, @Param("classTo")String classTo, @Param("_value")String value); }<file_sep>package com.quincy.auth.controller; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.text.MessageFormat; import java.util.Random; import javax.imageio.ImageIO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import com.quincy.auth.AuthCommonConstants; import com.quincy.core.InnerConstants; import com.quincy.sdk.EmailService; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; @Controller @RequestMapping("/auth") public class AuthorizationCommonController { /** * 登出 */ @RequestMapping("/signout") public String logout(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(false); if(session!=null) { session.invalidate(); } return InnerConstants.VIEW_PATH_RESULT; } /** * 点超链接没权限要进入的页面 */ @RequestMapping("/deny") public String deny() { return "/deny"; } private final double VCODE_RADIANS = Math.PI/180; @Value("${vcode.length}") private int vcodeLength; @Value("${vcode.lines}") private int vcodeLines; /** * Example: 25/10/25/110/35 */ @RequestMapping("/vcode/{size}/{start}/{space}/{width}/{height}") public void genVCode(HttpServletRequest request, HttpServletResponse response, @PathVariable(required = true, name = "size")int size, @PathVariable(required = true, name = "start")int start, @PathVariable(required = true, name = "space")int space, @PathVariable(required = true, name = "width")int width, @PathVariable(required = true, name = "height")int height) throws Exception { this.vcode(request, VCodeCharsFrom.MIXED, vcodeLength, null, new VCodeSender() { @Override public void send(char[] vcode) throws IOException { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics(); Graphics2D gg = (Graphics2D)g; g.setColor(Color.WHITE); g.fillRect(0, 0, width, height);//填充背景 Random random = new Random(); for(int i=0;i<vcodeLines;i++) { g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255))); g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height)); } Font font = new Font("Times New Roman", Font.ROMAN_BASELINE, size); g.setFont(font); // g.translate(random.nextInt(3), random.nextInt(3)); int x = start;//旋转原点的 x 坐标 for(char c:vcode) { double tiltAngle = random.nextInt()%30*VCODE_RADIANS;//角度小于30度 g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255))); gg.rotate(tiltAngle, x, 45); g.drawString(c+"", x, size); gg.rotate(-tiltAngle, x, 45); x += space; } OutputStream out = null; try { out = response.getOutputStream(); ImageIO.write(image, "jpg", out); out.flush(); } finally { if(out!=null) out.close(); } } }); } @Value("${auth.vcode.timeout:120}") private int vcodeTimeoutSeconds; public String vcode(HttpServletRequest request, VCodeCharsFrom _charsFrom, int length, String clientTokenName, VCodeSender sender) throws Exception { String charsFrom = (_charsFrom==null?VCodeCharsFrom.MIXED:_charsFrom).getValue(); Random random = new Random(); StringBuilder sb = new StringBuilder(length); char[] _vcode = new char[length]; for(int i=0;i<length;i++) { char c = charsFrom.charAt(random.nextInt(charsFrom.length())); sb.append(c); _vcode[i] = c; } String vcode = sb.toString(); HttpSession session = request.getSession(); session.setMaxInactiveInterval(vcodeTimeoutSeconds); session.setAttribute(AuthCommonConstants.VCODE_ATTR_KEY, vcode); sender.send(_vcode); return session.getId(); } @Autowired private EmailService emailService; public String vcode(HttpServletRequest request, VCodeCharsFrom charsFrom, int length, String clientTokenName, String emailTo, String subject, String _content) throws Exception { return this.vcode(request, charsFrom, length, clientTokenName, new VCodeSender() { @Override public void send(char[] _vcode) { String vcode = new String(_vcode); String content = MessageFormat.format(_content, vcode); // content = String.format(content, vcode, token); emailService.send(emailTo, subject, content, "", null, null, null, null); } }); } }<file_sep><?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <artifactId>quincy-sdk</artifactId> <name>Common</name> <url>https://github.com/mq7253180/sdk/tree/master/sdk</url> <parent> <groupId>com.maqiangcgq</groupId> <artifactId>all</artifactId> <version>1.1.2</version> </parent> <dependencies> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> <dependency> <groupId>jakarta.servlet</groupId> <artifactId>jakarta.servlet-api</artifactId> <version>6.0.0</version> <scope>compile</scope> </dependency> <!-- dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-core</artifactId> <version>10.1.7</version> </dependency--> <dependency> <!-- org.springframework.web.servlet.LocaleResolver --> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>6.0.7</version> </dependency> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.14</version> <scope>compile</scope> <exclusions> <exclusion> <artifactId>commons-logging</artifactId> <groupId>commons-logging</groupId> </exclusion> </exclusions> <!-- <optional>true</optional> --> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.14</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.19</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.9.19</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.32</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>2.0.7</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.26</version> </dependency> <dependency> <!-- org.apache.tools --> <groupId>org.apache.ant</groupId> <artifactId>ant</artifactId> <version>1.10.13</version> </dependency> <dependency> <!-- PGP --> <groupId>org.bouncycastle</groupId> <artifactId>bcpg-jdk15on</artifactId> <version>1.70</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.11.1</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <!-- com.fasterxml.jackson.annotation.JsonIgnore --> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.14.2</version> </dependency> </dependencies> </project><file_sep>package com.quincy.core.zookeeper; public class ContextConstants { public final static String SYN_NODE = "synchronization"; } <file_sep>package com.quincy.core.zookeeper.impl; import org.apache.commons.pool2.ObjectPool; import org.apache.commons.pool2.SwallowedExceptionListener; import org.apache.commons.pool2.impl.AbandonedConfig; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.ZooKeeper.States; import com.quincy.core.zookeeper.PoolableZooKeeper; import com.quincy.core.zookeeper.PoolableZooKeeperFactory; import com.quincy.core.zookeeper.ZooKeeperSource; import lombok.extern.slf4j.Slf4j; @Slf4j public class ZooKeeperSourceImpl implements ZooKeeperSource { private ObjectPool<PoolableZooKeeper> pool; public ZooKeeperSourceImpl(PoolableZooKeeperFactory f, GenericObjectPoolConfig pc, AbandonedConfig ac) { GenericObjectPool<PoolableZooKeeper> pool = new GenericObjectPool<PoolableZooKeeper>(f, pc, ac); pool.setSwallowedExceptionListener(new SwallowedExceptionListener() { @Override public void onSwallowException(Exception e) { log.error("\r\nSFTP_CONNECTION_POOL_ERR:\r\n", e); } }); f.setPool(pool); this.pool = pool; } @Override public ZooKeeper get() throws Exception { PoolableZooKeeper zk = null; while(true) { log.info("ZK_POOL=================NumActive: {}---NumIdle: {}", pool.getNumActive(), pool.getNumIdle()); zk = pool.borrowObject(); States states = zk.getState(); if(!states.isAlive()) { zk.reallyClose(); pool.invalidateObject(zk); } else return zk; } } @Override public void close() { this.pool.close(); } }<file_sep>package com.quincy.sdk; public class Result { private int status;//1成功, 0会话超时, -1无权限, -2签名传空, -3签名验证失败, -4抛异常, -5验证码输入为空,-6验证码过期, -7验证码输入有误 private String msg; private Object data; private Object accsessToken; private String cluster; public Result() { } public Result(int status, String msg, Object data) { this.status = status; this.msg = msg; this.data = data; } public Result(int status, String msg) { this(status, msg, null); } public Result(int status) { this(status, null, null); } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public Object getAccsessToken() { return accsessToken; } public void setAccsessToken(Object accsessToken) { this.accsessToken = accsessToken; } public String getCluster() { return cluster; } public void setCluster(String cluster) { this.cluster = cluster; } public final static String I18N_KEY_SUCCESS = "status.success"; public final static String I18N_KEY_EXCEPTION = "status.error.500"; public final static String I18N_KEY_TIMEOUT = "status.error.401"; public final static String I18N_KEY_DENY = "status.error.403"; public static Result newSuccess() { return new Result(1, I18N_KEY_SUCCESS); } public static Result newException() { return new Result(-2, I18N_KEY_EXCEPTION); } public static Result newTimeout() { return new Result(0, I18N_KEY_TIMEOUT); } public static Result newDeny() { return new Result(-1, I18N_KEY_DENY); } public Result msg(String msg) { this.msg = msg; return this; } public Result data(Object data) { this.data = data; return this; } public Result cluster(String cluster) { this.cluster = cluster; return this; } }<file_sep>auth.timeout.broker=Timeout, Redirecting... auth.success=Success auth.null.username=Username is Required. auth.null.password=<PASSWORD>. auth.account.no=We cannot find an account with that user name. auth.account.pwd_incorrect=Your <PASSWORD>. title.login=Sign in title.error=Error <file_sep>package com.quincy.sdk; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.sql.SQLException; public interface JdbcDao { public Object executeQuery(String sql, Class<?> returnType, Class<?> returnItemType, Object... args) throws SQLException, IOException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException; public int executeUpdate(String sql, Object... args) throws SQLException; }<file_sep>package com.quincy.sdk; import java.io.IOException; public interface DTransactionContext { public void setTransactionFailure(DTransactionFailure transactionFailure); public void compensate() throws ClassNotFoundException, NoSuchMethodException, IOException, InterruptedException; public void compensate(String frequencyBatch) throws ClassNotFoundException, NoSuchMethodException, IOException, InterruptedException; } <file_sep>package com.quincy.core.web; import java.util.Locale; import org.springframework.web.servlet.LocaleResolver; import com.quincy.sdk.helper.CommonHelper; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * 用在RequestContext requestContext = new RequestContext(request);requestContext.getMessage("key值")获取国际化msg的方式上 */ public class GlobalLocaleResolver implements LocaleResolver { @Override public Locale resolveLocale(HttpServletRequest request) { Locale locale = CommonHelper.getLocale(request); return locale; } @Override public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { /*LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request); localeResolver.setLocale(request, response, this.resolveLocale(request));*/ } }<file_sep>package com.quincy.core; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import javax.sql.DataSource; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.Assert; import com.quincy.core.db.RoutingDataSource; import com.quincy.sdk.MasterOrSlave; @Configuration public class ShardingJdbcConfiguration { @Value("${spring.datasource.driver-class-name}") private String driverClassName; @Value("${spring.datasource.sharding.url.prefix}") private String urlPrefix; @Value("${spring.datasource.sharding.url.suffix}") private String urlSuffix; @Value("${spring.datasource.username}") private String userName; @Value("${spring.datasource.password}") private String password; @Value("${spring.datasource.pool.masterRatio}") private int masterRatio; @Value("${spring.datasource.sharding.count}") private int shardingCount; @Autowired private DBCommonApplicationContext dbCommonApplicationContext; @Autowired private ApplicationContext applicationContext; private final static String PROPERTY_KEY_PREFIX = "spring.datasource.sharding."; @Bean(name = "dataSource") public DataSource routingDataSource() throws SQLException { Map<Object, Object> targetDataSources = new HashMap<Object, Object>(shardingCount*2); for(int i=0;i<shardingCount;i++) { String masterKey = PROPERTY_KEY_PREFIX+i+".master"; String masterVal = applicationContext.getEnvironment().getProperty(masterKey); Assert.hasText(masterVal, "第"+i+"个分片写库没有设置(从0开始)"); String slaveKey = PROPERTY_KEY_PREFIX+i+".slave"; String slaveVal = applicationContext.getEnvironment().getProperty(slaveKey); Assert.hasText(slaveVal, "第"+i+"个分片只读库没有设置(从0开始)"); BasicDataSource masterDB = dbCommonApplicationContext.createBasicDataSource(1); masterDB.setDriverClassName(driverClassName); masterDB.setUrl(urlPrefix+masterVal+urlSuffix); masterDB.setUsername(userName); masterDB.setPassword(<PASSWORD>); masterDB.setDefaultAutoCommit(true); // masterDB.setAutoCommitOnReturn(true); masterDB.setRollbackOnReturn(false); masterDB.setDefaultReadOnly(false); BasicDataSource slaveDB = dbCommonApplicationContext.createBasicDataSource(masterRatio); slaveDB.setDriverClassName(driverClassName); slaveDB.setUrl(urlPrefix+slaveVal+urlSuffix); slaveDB.setUsername(userName); slaveDB.setPassword(<PASSWORD>); slaveDB.setDefaultAutoCommit(false); // slaveDB.setAutoCommitOnReturn(false); slaveDB.setRollbackOnReturn(true); slaveDB.setDefaultReadOnly(true); targetDataSources.put(MasterOrSlave.MASTER.value()+i, masterDB); targetDataSources.put(MasterOrSlave.SLAVE.value()+i, slaveDB); } RoutingDataSource db = new RoutingDataSource(); db.setTargetDataSources(targetDataSources); db.setDefaultTargetDataSource(targetDataSources.get(MasterOrSlave.MASTER.value()+0)); return db; } }<file_sep>package com.quincy.core.web.freemarker; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.quincy.sdk.helper.CommonHelper; import freemarker.core.Environment; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; public class AttributeTemplateDirectiveModelBean implements TemplateDirectiveModel { private static Map<String, Attribute> map = new HashMap<String, Attribute>(5); @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { env.getOut().write(map.get(params.get("key").toString()).getAttribute()); } private static interface Attribute { public String getAttribute(); } static { /*map.put("locale", new Attribute() { @Override public String getAttribute() { HttpServletRequest request = CommonHelper.getRequest(); Object sessionAttribute = WebUtils.getSessionAttribute(request, SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME); return sessionAttribute.toString().toLowerCase(); } });*/ map.put("uri", new Attribute() { @Override public String getAttribute() { return CommonHelper.getRequest().getRequestURI(); } }); map.put("uri_without_first", new Attribute() { @Override public String getAttribute() { String uri = CommonHelper.getRequest().getRequestURI(); String[] ss = uri.split("/"); return ss.length==0?uri:uri.substring(ss[1].length()+1, uri.length()); } }); map.put("url", new Attribute() { @Override public String getAttribute() { return CommonHelper.getRequest().getRequestURL().toString(); } }); map.put("context_path", new Attribute() { @Override public String getAttribute() { return CommonHelper.getRequest().getContextPath(); } }); } }<file_sep>package com.quincy.core; import java.sql.SQLException; import java.util.Arrays; import java.util.Collection; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.pool2.impl.AbandonedConfig; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import com.quincy.sdk.helper.CommonHelper; import lombok.Data; @PropertySource(value = {"classpath:application-sdk.properties"}) @Configuration //@AutoConfigureAfter(CommonApplicationContext.class) //@Import(CommonApplicationContext.class) public class DBCommonApplicationContext {//implements TransactionManagementConfigurer { @Data private class DBConnPoolParams { private boolean poolingStatements; private int maxOpenPreparedStatements; private int initialSize; private Integer defaultQueryTimeoutSeconds; private String validationQuery; private int validationQueryTimeoutSeconds; private long maxConnLifetimeMillis; private Collection<String> connectionInitSqls; private boolean logExpiredConnections; private boolean cacheState; private int defaultTransactionIsolation; private String connectionProperties; private boolean fastFailValidation; private Collection<String> disconnectionSqlCodes; private String defaultCatalog; private boolean accessToUnderlyingConnectionAllowed; } @Value("${spring.datasource.dbcp2.poolPreparedStatements:#{null}}") private Boolean poolPreparedStatements; @Value("${spring.datasource.dbcp2.maxOpenPreparedStatements:#{null}}") private Integer maxOpenPreparedStatements; @Value("${spring.datasource.dbcp2.initialSize:#{null}}") private Integer initialSize; @Value("${spring.datasource.dbcp2.defaultQueryTimeoutSeconds:#{null}}") private Integer defaultQueryTimeoutSeconds; @Value("${spring.datasource.dbcp2.validationQuery:#{null}}") private String validationQuery; @Value("${spring.datasource.dbcp2.validationQueryTimeoutSeconds:#{null}}") private Integer validationQueryTimeoutSeconds; @Value("${spring.datasource.dbcp2.maxConnLifetimeMillis:#{null}}") private Long maxConnLifetimeMillis; @Value("${spring.datasource.dbcp2.logExpiredConnections:#{null}}") private Boolean logExpiredConnections; @Value("${spring.datasource.dbcp2.cacheState:#{null}}") private Boolean cacheState; @Value("${spring.datasource.dbcp2.connectionInitSqls:#{null}}") private String _connectionInitSqls; @Value("${spring.datasource.dbcp2.defaultTransactionIsolation:#{null}}") private Integer defaultTransactionIsolation; @Value("${spring.datasource.dbcp2.connectionProperties:#{null}}") private String connectionProperties; @Value("${spring.datasource.dbcp2.fastFailValidation:#{null}}") private Boolean fastFailValidation; @Value("${spring.datasource.dbcp2.disconnectionSqlCodes:#{null}}") private String _disconnectionSqlCodes; @Value("${spring.datasource.dbcp2.defaultCatalog}") private String defaultCatalog; @Value("${spring.datasource.dbcp2.accessToUnderlyingConnectionAllowed:#{null}}") private Boolean accessToUnderlyingConnectionAllowed; @Bean public DBConnPoolParams dbConnPoolParams() throws SQLException { BasicDataSource ds = new BasicDataSource(); DBConnPoolParams p = new DBConnPoolParams(); p.setPoolingStatements(poolPreparedStatements==null?ds.isPoolPreparedStatements():poolPreparedStatements); p.setMaxOpenPreparedStatements(maxOpenPreparedStatements==null?ds.getMaxOpenPreparedStatements():maxOpenPreparedStatements); p.setInitialSize(initialSize==null?ds.getInitialSize():initialSize); p.setDefaultQueryTimeoutSeconds(defaultQueryTimeoutSeconds==null?ds.getDefaultQueryTimeout():defaultQueryTimeoutSeconds); p.setValidationQuery(validationQuery==null?ds.getValidationQuery():CommonHelper.trim(validationQuery)); p.setValidationQueryTimeoutSeconds(validationQueryTimeoutSeconds==null?ds.getValidationQueryTimeout():validationQueryTimeoutSeconds); p.setMaxConnLifetimeMillis(maxConnLifetimeMillis==null?ds.getMaxConnLifetimeMillis():maxConnLifetimeMillis); p.setLogExpiredConnections(logExpiredConnections==null?ds.getLogExpiredConnections():logExpiredConnections); p.setCacheState(cacheState==null?ds.getCacheState():cacheState); p.setDefaultTransactionIsolation(defaultTransactionIsolation==null?ds.getDefaultTransactionIsolation():defaultTransactionIsolation); p.setConnectionProperties(connectionProperties); p.setFastFailValidation(fastFailValidation==null?ds.getFastFailValidation():fastFailValidation); p.setDefaultCatalog(defaultCatalog); p.setAccessToUnderlyingConnectionAllowed(accessToUnderlyingConnectionAllowed==null?ds.isAccessToUnderlyingConnectionAllowed():accessToUnderlyingConnectionAllowed); if(_connectionInitSqls!=null) { String[] connectionInitSqls = _connectionInitSqls.split(";"); if(connectionInitSqls!=null&&connectionInitSqls.length>0) p.setConnectionInitSqls(Arrays.asList(connectionInitSqls)); } if(_disconnectionSqlCodes!=null) { String[] disconnectionSqlCodes = _disconnectionSqlCodes.split(","); if(disconnectionSqlCodes!=null&&disconnectionSqlCodes.length>0) p.setDisconnectionSqlCodes(Arrays.asList(disconnectionSqlCodes)); } ds.close(); return p; } @Autowired private GenericObjectPoolConfig poolCfg; @Autowired private AbandonedConfig abandonedCfg; @Autowired private DBConnPoolParams dbConnPoolParams; public BasicDataSource createBasicDataSource(int ratio) throws SQLException { BasicDataSource ds = new BasicDataSource(); ds.setMaxTotal(poolCfg.getMaxTotal()>0?poolCfg.getMaxTotal()*ratio:poolCfg.getMaxTotal()); ds.setMaxIdle(poolCfg.getMaxIdle()>0?poolCfg.getMaxIdle()*ratio:poolCfg.getMaxIdle()); ds.setMinIdle(poolCfg.getMinIdle()>0?poolCfg.getMinIdle()*ratio:poolCfg.getMinIdle()); ds.setMaxWaitMillis(poolCfg.getMaxWaitMillis()); ds.setMinEvictableIdleTimeMillis(poolCfg.getMinEvictableIdleTimeMillis()); ds.setTimeBetweenEvictionRunsMillis(poolCfg.getTimeBetweenEvictionRunsMillis()); ds.setNumTestsPerEvictionRun(poolCfg.getNumTestsPerEvictionRun()>0?poolCfg.getNumTestsPerEvictionRun()*ratio:poolCfg.getNumTestsPerEvictionRun()); ds.setTestOnBorrow(poolCfg.getTestOnBorrow()); ds.setTestOnCreate(poolCfg.getTestOnCreate()); ds.setTestOnReturn(poolCfg.getTestOnReturn()); ds.setTestWhileIdle(poolCfg.getTestWhileIdle()); ds.setLifo(poolCfg.getLifo()); ds.setEvictionPolicyClassName(poolCfg.getEvictionPolicyClassName()); ds.setSoftMinEvictableIdleTimeMillis(poolCfg.getSoftMinEvictableIdleTimeMillis()); ds.setJmxName(poolCfg.getJmxNameBase()); ds.setRemoveAbandonedOnMaintenance(abandonedCfg.getRemoveAbandonedOnMaintenance()); ds.setRemoveAbandonedOnBorrow(abandonedCfg.getRemoveAbandonedOnBorrow()); ds.setRemoveAbandonedTimeout(abandonedCfg.getRemoveAbandonedTimeout()); ds.setLogAbandoned(abandonedCfg.getLogAbandoned()); ds.setAbandonedUsageTracking(abandonedCfg.getUseUsageTracking()); ds.setInitialSize(dbConnPoolParams.getInitialSize()>0?dbConnPoolParams.getInitialSize()*ratio:dbConnPoolParams.getInitialSize()); ds.setMaxOpenPreparedStatements(dbConnPoolParams.getMaxOpenPreparedStatements()>0?dbConnPoolParams.getMaxOpenPreparedStatements()*ratio:dbConnPoolParams.getMaxOpenPreparedStatements()); ds.setPoolPreparedStatements(dbConnPoolParams.isPoolingStatements()); ds.setDefaultQueryTimeout(dbConnPoolParams.getDefaultQueryTimeoutSeconds()); ds.setValidationQuery(dbConnPoolParams.getValidationQuery()); ds.setValidationQueryTimeout(dbConnPoolParams.getValidationQueryTimeoutSeconds()); ds.setMaxConnLifetimeMillis(dbConnPoolParams.getMaxConnLifetimeMillis()); ds.setConnectionInitSqls(dbConnPoolParams.getConnectionInitSqls()); ds.setLogExpiredConnections(dbConnPoolParams.isLogExpiredConnections()); ds.setCacheState(dbConnPoolParams.isCacheState()); ds.setDefaultTransactionIsolation(dbConnPoolParams.getDefaultTransactionIsolation()); ds.setFastFailValidation(dbConnPoolParams.isFastFailValidation()); ds.setDisconnectionSqlCodes(dbConnPoolParams.getDisconnectionSqlCodes()); ds.setDefaultCatalog(dbConnPoolParams.getDefaultCatalog()); if(dbConnPoolParams.getConnectionProperties()!=null) ds.setConnectionProperties(dbConnPoolParams.getConnectionProperties()); ds.setAccessToUnderlyingConnectionAllowed(dbConnPoolParams.isAccessToUnderlyingConnectionAllowed());//PoolGuard是否可以获取底层连接 //Deprecated // ds.setEnableAutoCommitOnReturn(autoCommitOnReturn); return ds; } /* @Bean(name = "dataSourceMaster") public DataSource masterDataSource() { BasicDataSource db = new BasicDataSource(); db.setDriverClassName(driverClassName); db.setUrl(masterUrl); db.setUsername(masterUserName); db.setPassword(<PASSWORD>); db.setDefaultAutoCommit(defaultAutoCommit); db.setMaxIdle(maxIdle); db.setMinIdle(minIdle); db.setPoolPreparedStatements(poolPreparedStatements); db.setMaxOpenPreparedStatements(maxOpenPreparedStatements); db.setRemoveAbandonedTimeout(removeAbandonedTimeout); db.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); db.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); db.setTestOnBorrow(testOnBorrow); db.setTestWhileIdle(testWhileIdle); db.setTestOnReturn(testOnReturn); return db; } @Bean(name = "dataSourceSlave") public DataSource slaveDataSource() { BasicDataSource db = new BasicDataSource(); db.setDriverClassName(driverClassName); db.setUrl(masterUrl); db.setUsername(masterUserName); db.setPassword(<PASSWORD>); db.setDefaultAutoCommit(defaultAutoCommit); db.setMaxIdle(maxIdle); db.setMinIdle(minIdle); db.setPoolPreparedStatements(poolPreparedStatements); db.setMaxOpenPreparedStatements(maxOpenPreparedStatements); db.setRemoveAbandonedTimeout(removeAbandonedTimeout); db.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); db.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); db.setTestOnBorrow(testOnBorrow); db.setTestWhileIdle(testWhileIdle); db.setTestOnReturn(testOnReturn); return db; } @Autowired @Qualifier("dataSourceMaster") private DataSource masterDB; @Autowired @Qualifier("dataSourceSlave") private DataSource slaveDB; @Bean(name = "routingDataSource") public DataSource routingDataSource() { Map<Object, Object> targetDataSources = new HashMap<Object, Object>(2); targetDataSources.put(DataSourceHolder.MASTER, masterDB); targetDataSources.put(DataSourceHolder.SLAVE, slaveDB); RoutingDataSource db = new RoutingDataSource(); db.setTargetDataSources(targetDataSources); db.setDefaultTargetDataSource(null); return db; } @Bean public PlatformTransactionManager txManager(@Qualifier("routingDataSource")DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Autowired private PlatformTransactionManager platformTransactionManager; @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return platformTransactionManager; } */ //**************mybatis********************// /* @Value("${mybatis.mapper-locations}") private String mybatisMapperLocations; @Bean(name="sqlSessionFactory")//name被设置在@MapperScan属性sqlSessionFactoryRef中 public SqlSessionFactory sessionFactory(@Qualifier("routingDataSource")DataSource dataSource) throws Exception{ SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean(); sessionFactoryBean.setDataSource(dataSource); sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mybatisMapperLocations)); return sessionFactoryBean.getObject(); } @Bean public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory")SqlSessionFactory sqlSessionFactory) throws Exception { SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory); return template; } */ //**************/mybatis********************// }<file_sep>package com.quincy.auth.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.quincy.auth.AuthConstants; @Documented @Retention(value = RetentionPolicy.RUNTIME) @Target(value = {ElementType.METHOD}) public @interface VCodeRequired { public String clientTokenName() default ""; public boolean ignoreCase() default true; public String timeoutForwardTo() default "/auth"+AuthConstants.URI_VCODE_FAILURE; }<file_sep>package com.quincy.core.zookeeper; import java.io.IOException; import org.apache.commons.pool2.ObjectPool; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import lombok.extern.slf4j.Slf4j; @Slf4j public class PoolableZooKeeper extends ZooKeeper { private volatile ObjectPool<PoolableZooKeeper> pool; public PoolableZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long sessionId, byte[] sessionPasswd, boolean canBeReadOnly, ObjectPool<PoolableZooKeeper> pool) throws IOException { super(connectString, sessionTimeout, watcher, sessionId, sessionPasswd, canBeReadOnly); this.pool = pool; } public PoolableZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long sessionId, byte[] sessionPasswd, ObjectPool<PoolableZooKeeper> pool) throws IOException { super(connectString, sessionTimeout, watcher, sessionId, sessionPasswd); this.pool = pool; } public PoolableZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly, ObjectPool<PoolableZooKeeper> pool) throws IOException { super(connectString, sessionTimeout, watcher, canBeReadOnly); this.pool = pool; } public PoolableZooKeeper(String connectString, int sessionTimeout, Watcher watcher, ObjectPool<PoolableZooKeeper> pool) throws IOException { super(connectString, sessionTimeout, watcher); this.pool = pool; } public void close() { try { this.pool.returnObject(this); } catch (Exception e) { log.error("SFTP_POOL======================", e); } } public void reallyClose() throws InterruptedException { this.close(); } }<file_sep>package com.quincy.auth.controller; public interface PwdRestEmailInfo { public String getSubject(); public String getContent(String uri); }<file_sep>auth.timeout.broker=\u4F1A\u8BDD\u8D85\u65F6\uFF0C\u6B63\u5728\u8DF3\u8F6C... auth.success=\u767B\u5F55\u6210\u529F auth.null.username=\u<PASSWORD>\u53F7\u4E0D\u80FD\u4E3A\u<PASSWORD> auth.null.password=\<PASSWORD> auth.account.no=\u65E0\u6548\u8D26\u53F7 auth.account.pwd_incorrect=\<PASSWORD> title.login=\u767B\u5F55 title.error=\u9519\u8bef\u9875 <file_sep>package com.quincy.sdk; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.web.method.support.HandlerMethodReturnValueHandler; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor; import com.quincy.core.web.GlobalHandlerMethodReturnValueHandler; import com.quincy.core.web.GlobalLocaleResolver; import com.quincy.core.web.GeneralInterceptor; import com.quincy.core.web.StaticInterceptor; import com.quincy.core.web.freemarker.AttributeTemplateDirectiveModelBean; import com.quincy.core.web.freemarker.I18NTemplateDirectiveModelBean; import com.quincy.core.web.freemarker.LocaleTemplateDirectiveModelBean; import com.quincy.core.web.freemarker.PropertiesTemplateDirectiveModelBean; import freemarker.template.Configuration; public class WebMvcConfiguration extends WebMvcConfigurationSupport implements InitializingBean { @Autowired private RequestMappingHandlerAdapter adapter; @Autowired private ApplicationContext applicationContext; @Value("${env}") private String env; @Value("${impl.auth.interceptor:#{null}}") private String interceptorImpl; @Value("${server.port}") private String serverPort; @Override protected void addInterceptors(InterceptorRegistry registry) { if(Constants.ENV_DEV.equals(env)) registry.addInterceptor(new StaticInterceptor()).addPathPatterns("/static/**"); registry.addInterceptor(new GeneralInterceptor()).addPathPatterns("/**"); if(interceptorImpl!=null) { HandlerInterceptorAdapter handlerInterceptorAdapter = applicationContext.getBean(interceptorImpl, HandlerInterceptorAdapter.class); registry.addInterceptor(handlerInterceptorAdapter).addPathPatterns("/**"); } } @Override public void afterPropertiesSet() throws Exception { List<HandlerMethodReturnValueHandler> returnValueHandlers = adapter.getReturnValueHandlers(); List<HandlerMethodReturnValueHandler> handlers = new ArrayList<HandlerMethodReturnValueHandler>(returnValueHandlers); decorateHandlers(handlers); adapter.setReturnValueHandlers(handlers); } private void decorateHandlers(List<HandlerMethodReturnValueHandler> handlers) { for(HandlerMethodReturnValueHandler handler:handlers) { if(handler instanceof RequestResponseBodyMethodProcessor) { HandlerMethodReturnValueHandler decorator = new GlobalHandlerMethodReturnValueHandler(handler, applicationContext, serverPort); int index = handlers.indexOf(handler); handlers.set(index, decorator); break; } } } @Bean public LocaleResolver localeResolver() { return new GlobalLocaleResolver(); } @Autowired private Configuration freemarkerCfg; @PostConstruct public void freeMarkerConfigurer() { freemarkerCfg.setSharedVariable("attr", new AttributeTemplateDirectiveModelBean()); freemarkerCfg.setSharedVariable("i18n", new I18NTemplateDirectiveModelBean(applicationContext.getEnvironment())); freemarkerCfg.setSharedVariable("property", new PropertiesTemplateDirectiveModelBean(applicationContext.getEnvironment())); freemarkerCfg.setSharedVariable("locale", new LocaleTemplateDirectiveModelBean()); } /*@Bean public ViewResolver viewResolver() { FreeMarkerViewResolver resolver = new FreeMarkerViewResolver(); resolver.setCache(true); resolver.setSuffix(".ftl"); resolver.setContentType("text/html; charset=UTF-8"); resolver.setAllowSessionOverride(true); return resolver; }*/ /*@Bean public FreeMarkerConfigurer freeMarkerConfigurer() { String path = null; if("dev".equals(env)) { path = this.getClass().getResource("/").getPath(); path = path.substring(0, path.indexOf("springboot/target/classes"))+"springboot/src/main/view/page/"; } else { path = ftlLocation; } path = "file:"+path; log.info("VIEW_LOCATION====================="+path); Map<String, Object> variables = new HashMap<String, Object>(3); variables.put("attr", new AttributeTemplateDirectiveModelBean()); variables.put("i18n", new I18NTemplateDirectiveModelBean(properties)); variables.put("property", new PropertiesTemplateDirectiveModelBean(properties)); configuration.setSharedVariable("attr", new AttributeTemplateDirectiveModelBean()); configuration.setSharedVariable("i18n", new I18NTemplateDirectiveModelBean(properties)); configuration.setSharedVariable("property", new PropertiesTemplateDirectiveModelBean(properties)); FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer.setTemplateLoaderPaths(path); configurer.setDefaultEncoding("UTF-8"); configurer.setFreemarkerVariables(variables); return configurer; }*/ }<file_sep>package com.quincy.auth.freemarker; import java.io.IOException; import java.util.Map; import freemarker.core.Environment; import freemarker.template.TemplateModel; public class ButtonTemplateDirectiveModelBean extends AbstractHtmlTemplateDirectiveModel { @Override protected String reallyExecute(Environment env, Map params, TemplateModel[] loopVars) throws IOException { Object id = params.get("id"); Object name = params.get("name"); Object clazz = params.get("class"); Object dataToggle = params.get("dataToggle"); Object dataTarget = params.get("dataTarget"); StringBuilder html = new StringBuilder(200).append("<button"); if(id!=null) html.append(" id=\"").append(id.toString()).append("\""); if(name!=null) html.append(" name=\"").append(name.toString()).append("\""); if(clazz!=null) html.append(" class=\"").append(clazz.toString()).append("\""); if(dataToggle!=null) html.append(" data-toggle=\"").append(dataToggle.toString()).append("\""); if(dataTarget!=null) html.append(" data-target=\"").append(dataTarget.toString()).append("\""); return html.append("></button>").toString(); } }<file_sep>auth.timeout.ajax=Timeout <file_sep>package com.quincy.core; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import com.quincy.sdk.annotation.Column; import com.quincy.sdk.annotation.DTO; import jakarta.annotation.PostConstruct; @Configuration public class JdbcPostConstruction { @Autowired private DataSource dataSource; @Autowired private JdbcDaoConfiguration jdbcDaoConfiguration; private Map<Class<?>, Map<String, Method>> classMethodMap; @PostConstruct public void init() throws NoSuchMethodException, SecurityException { Set<Class<?>> classes = ReflectionsHolder.get().getTypesAnnotatedWith(DTO.class); this.classMethodMap = new HashMap<Class<?>, Map<String, Method>>(); for(Class<?> clazz:classes) { Map<String, Method> subMap = new HashMap<String, Method>(); Field[] fields = clazz.getDeclaredFields(); for(Field field:fields) { Column column = field.getAnnotation(Column.class); if(column!=null) { String setterName = "set"+String.valueOf(field.getName().charAt(0)).toUpperCase()+field.getName().substring(1); subMap.put(column.value(), clazz.getMethod(setterName, field.getType())); } } this.classMethodMap.put(clazz, subMap); } jdbcDaoConfiguration.setClassMethodMap(this.classMethodMap); jdbcDaoConfiguration.setDataSource(dataSource); } public Map<Class<?>, Map<String, Method>> getClassMethodMap() { return classMethodMap; } }
1ecd6c95428452500862cb543ec2b299aa2b8925
[ "Java", "Maven POM", "INI" ]
64
Java
mq7253180/sdk
032c52b606004780a0f9f01c01268ae4fdaca3aa
5b2b12188db44c22ec5d294e8b41c09b6c31c7fc
refs/heads/master
<file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; public class SnakeGame : MonoBehaviour { [Header("Board Setting")] public SpriteRenderer board01; public SpriteRenderer board02; public Vector2 boardSize; public GameObject boardCenterAnchor; [Header("Snake Setting")] public SpriteRenderer snake; public int snakeStartLength = 4; public float snakeSize = 0.5f; public Transform snakeAnchor; [Header("Game Setting")] public float refreshRate = 0.2f; // private float _mTimer = 0; private Snake _mSnake; private void Start() { // Create board float _halfX = boardSize.x * 0.5f; float _halfY = boardSize.y * 0.5f; for (int i = 0; i < boardSize.x; ++i) { for ( int j = 0; j < boardSize.y; ++j) { var _boardPrefab = ((i + j) % 2 == 0) ? board01 : board02; var _boardInst = Instantiate(_boardPrefab, boardCenterAnchor.transform); var _boardTrans = _boardInst.transform; _boardTrans.localPosition = new Vector3(i - _halfX, j - _halfY, 0); _boardTrans.localScale = Vector3.one * (100 / 32f); } } // Create snake _mSnake = new Snake(snakeStartLength, snakeSize, snake, snakeAnchor); } private void Update() { _mTimer -= Time.deltaTime; if (_mTimer <= 0) { _mTimer = refreshRate; _mSnake.Move(); } if (Input.GetKeyDown(KeyCode.LeftArrow)) { _mSnake.ChangeDirection(MoveDirection.Left); } if (Input.GetKeyDown(KeyCode.RightArrow)) { _mSnake.ChangeDirection(MoveDirection.Right); } if (Input.GetKeyDown(KeyCode.UpArrow)) { _mSnake.ChangeDirection(MoveDirection.Up); } if (Input.GetKeyDown(KeyCode.DownArrow)) { _mSnake.ChangeDirection(MoveDirection.Down); } } public enum MoveDirection { Left, Right, Up, Down } public class SnakePart { private SnakePart _mChild; private SpriteRenderer _mSprite; private Vector3 _mPosition; public SnakePart(SnakePart child, SpriteRenderer sprite, Vector3 position) { _mChild = child; _mSprite = sprite; _mPosition = position; } public void Move(Vector3 direction) { SetPosition(_mPosition + direction); } private void SetPosition(Vector3 position) { var _lastPosition = _mPosition; _mPosition = position; _mSprite.transform.localPosition = _mPosition; if (_mChild != null) _mChild.SetPosition(_lastPosition); } } public class Snake { private SnakePart[] _mParts; private MoveDirection _mMoveDir = MoveDirection.Right; public Snake(int startLength, float size, SpriteRenderer spritePrefab, Transform anchor) { _mParts = new SnakePart[startLength]; SnakePart _child = null; for (int i = startLength - 1; i >= 0; --i) { var _position = new Vector3(-i, 0, 0); var _snakeInst = Instantiate(spritePrefab, anchor); _snakeInst.transform.localPosition = new Vector3(-i, 0, 0); _snakeInst.transform.localScale = Vector3.one * (100 / 32f) * size; _mParts[i] = new SnakePart(_child, _snakeInst, _position); _child = _mParts[i]; } } public void ChangeDirection(MoveDirection dir) { _mMoveDir = dir; } public void Move() { _mParts[0].Move(GetMovingDirection()); } private Vector3 GetMovingDirection() { switch (_mMoveDir) { case MoveDirection.Left: return Vector3.left; case MoveDirection.Right: return Vector3.right; case MoveDirection.Up: return Vector3.up; case MoveDirection.Down: return Vector3.down; } return Vector3.zero; } } }
e4977b04f7a8fb594995aa581c053af0eb6e0321
[ "C#" ]
1
C#
kegaskn/snake
528c6471a93a622cf0f0d4057a25e72d63afc4ef
34d19e0a44cc4e1ca6703b71d772c5cfe4015d8e
refs/heads/master
<file_sep><?php namespace Sciice\Foundation; trait ServiceResponse { public function response() { return response()->json(['message' => __('操作成功')]); } } <file_sep><?php namespace Sciice\Tests; class RoleControllerTest extends TestCase { protected $user; public function setUp() { parent::setUp(); $this->user = $this->authenticate(); } public function test_get_role_index_data() { $response = $this->get_data(); $response->assertOk(); $this->assertEquals(1, count($response->original)); } public function test_post_role_store_data() { $response = $this->post_data(); $response->assertOk(); $res = $this->get_data(); $this->assertEquals(2, count($res->original)); $this->assertEquals('test_role', $res->original[1]['name']); } public function test_update_role_data() { $this->post_data(); $response = $this->putJson('/sciice/role/2', $this->arr_data('test_update_role')); $response->assertStatus(200); $res = $this->get_data(); $this->assertEquals(2, count($res->original)); $this->assertEquals('test_update_role', $res->original[1]['name']); } public function test_delete_role_data() { $this->post_data(); $delete = $this->deleteJson('/sciice/role/1'); $delete->assertStatus(403); $response = $this->deleteJson('/sciice/role/2'); $response->assertStatus(200); $res = $this->get_data(); $this->assertEquals(1, count($res->original)); } protected function get_data() { return $this->getJson('/sciice/role'); } protected function post_data() { return $this->postJson('/sciice/role', $this->arr_data()); } protected function arr_data($name = 'test_role') { return [ 'name' => $name, 'title' => 'test_role_title', 'guard_name' => 'sciice', ]; } } <file_sep><?php namespace Sciice\Provider; use Illuminate\Support\Facades\Blade; use Illuminate\Support\ServiceProvider; class BladeServiceProvider extends ServiceProvider { public function boot() { Blade::directive('resource', function ($action) { return "<?php foreach(Sciice::{$action}() as \$name => \$path): ;?>".$this->if($action).$this->else($action).$this->endIf().'<?php endforeach; ?>'; }); } public function register() { // } private function if($action) { if ($action === 'style') { return "<?php if(starts_with(\$path, ['http://', 'https://'])): ?><link rel=\"stylesheet\" href=\"<?php echo \$path; ?>\">\n"; } else { return "<?php if(starts_with(\$path, ['http://', 'https://'])): ?><script src=\"<?php echo \$path; ?>\"></script>\n"; } } private function else($action) { $path = config('sciice.path'); if ($action == 'style') { return "<?php else: ?><link rel=\"stylesheet\" href=\"<?php echo e(url('/{$path}/{$action}', ['name' => \$name]))?>\">\n"; } else { return "<?php else: ?><script src=\"<?php echo e(url('/{$path}/{$action}', ['name' => \$name]))?>\"></script>\n"; } } private function endIf() { return '<?php endif; ?>'; } } <file_sep><?php namespace Sciice\Http\Request; use Illuminate\Validation\Rule; use Sciice\Foundation\Form\Request; class AuthorizeRequest extends Request { /** * @return array */ public function rules() { return [ 'name' => ['required', 'string', Rule::unique('permissions')], 'title' => 'required|string', 'grouping' => 'required|string', 'parent' => 'required', ]; } /** * @return array */ public function update() { return [ 'name' => ['required', 'string', Rule::unique('permissions')->ignore($this->route('authorize'))], 'title' => 'required|string', 'grouping' => 'required|string', 'parent' => 'required', ]; } } <file_sep><?php namespace Sciice\Http\Service; use Illuminate\Http\Request; use Sciice\Contract\Service; use Spatie\Permission\Models\Role; use Sciice\Foundation\ServiceResponse; use Spatie\Permission\Models\Permission; use Sciice\Http\Resource\AuthorizeResource; class AuthorizeService implements Service { use ServiceResponse; /** * @var \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model */ private $authorize; /** * AuthorizeService constructor. * * @param \Illuminate\Database\Eloquent\Builder|Permission $authorize */ public function __construct(Permission $authorize) { $this->authorize = $authorize->getModel(); } /** * @return mixed */ public function resources() { return AuthorizeResource::collection($this->authorize->whereGuardName('sciice')->get()); } /** * @param int $id * * @return mixed */ public function resource(int $id) { return new AuthorizeResource($this->authorize->findOrFail($id)); } /** * @param Request $request * * @return $this */ public function storeAs(Request $request) { $role = Role::findOrFail(1); $this->authorize->create(array_merge($request->all(), ['guard_name' => 'sciice']))->assignRole($role); return $this; } /** * @param Request $request * @param int $id * * @return $this */ public function updateAs(Request $request, int $id) { $this->authorize->findOrFail($id)->update($request->all()); return $this; } /** * @param int $id * * @return $this * @throws \Exception */ public function deleteAs(int $id) { $query = $this->authorize->findOrFail($id); abort_if($this->authorize->whereParent((int) $query->id)->get()->isNotEmpty(), 403, __('请先删除子权限')); $query->delete(); return $this; } } <file_sep><?php namespace Sciice\Http\Resource; use Illuminate\Http\Resources\Json\JsonResource; /** * @property mixed id * @property mixed parent * @property mixed name * @property mixed title * @property mixed grouping * @property mixed created_at * @property mixed updated_at */ class AuthorizeResource extends JsonResource { public function toArray($request) { $arr = array_except(explode('.', $this->name), 0); return [ 'id' => $this->id, 'parent' => $this->parent, 'name' => $this->name, 'controller' => head($arr), 'action' => last($arr), 'title' => $this->title, 'grouping' => $this->grouping, 'created_at' => (string) $this->created_at, 'updated_at' => (string) $this->updated_at, ]; } } <file_sep><?php namespace Sciice\Tests; class SciiceControllerTest extends TestCase { protected $user; protected function setUp() { parent::setUp(); $this->user = $this->authenticate(); } public function test_get_sciice_index() { $response = $this->get_data(); $response->assertJsonCount(3); $this->assertEquals(1, count($response->original)); $response->assertStatus(200); $this->assertEquals($this->user->username, $response->original[0]['username']); $this->assertEquals($this->user->roles[0]['id'], $response->original[0]['roles'][0]['id']); } public function test_post_sciice_store_data() { $response = $this->post_data(); $response->assertStatus(200); $res = $this->get_data(); $res->assertJsonCount(3); $this->assertEquals(2, count($res->original)); $this->assertEquals('post_test', $res->original[1]['username']); $this->assertEquals(1, $res->original[1]['roles'][0]['id']); } public function test_path_sciice_update_data() { $this->post_data(); $response = $this->putJson('/sciice/user/2', $this->arr_data('test_update')); $response->assertStatus(200); $res = $this->get_data(); $this->assertEquals('test_update', $res->original[1]['name']); $this->assertEquals(1, $res->original[1]['roles'][0]['id']); } public function test_delete_sciice_delete_data() { $this->post_data(); $delete = $this->deleteJson('/sciice/user/1'); $delete->assertStatus(403); $response = $this->deleteJson('/sciice/user/2'); $response->assertStatus(200); $res = $this->get_data(); $this->assertEquals(1, count($res->original)); } protected function get_data() { return $this->getJson('/sciice/user'); } protected function post_data() { return $this->postJson('/sciice/user', $this->arr_data()); } protected function arr_data($name = 'post_test') { return [ 'name' => $name, 'username' => 'post_test', 'email' => '<EMAIL>', 'mobile' => 13000033333, 'password' => '<PASSWORD>', 'role' => 1, ]; } } <file_sep><?php namespace Sciice\Tests; class AuthorizeControllerTest extends TestCase { protected $user; public function setUp() { parent::setUp(); $this->user = $this->authenticate(); } public function test_get_authorize_index_data() { $response = $this->get_data(); $response->assertOk(); $this->assertEquals(12, count($response->original)); } public function test_post_authorize_store_data() { $response = $this->post_data(); $response->assertOk(); $res = $this->get_data(); $res->assertOk(); $this->assertEquals(13, count($res->original)); $this->assertEquals('test_authorize', $res->original[12]['name']); } public function test_update_authorize_data() { $this->post_data(); $response = $this->putJson('/sciice/authorize/13', $this->arr_data('test_update_authorize')); $response->assertStatus(200); $res = $this->get_data(); $this->assertEquals(13, count($res->original)); $this->assertEquals('test_update_authorize', $res->original[12]['name']); } public function test_delete_authorize_fail_data() { $data = $this->postJson('/sciice/authorize', $this->arr_data('test_authorize', 1)); $data->assertOk(); $res = $this->get_data(); $this->assertEquals(13, count($res->original)); $response = $this->deleteJson('/sciice/authorize/1'); $response->assertStatus(403); } public function test_delete_authorize_data() { $this->post_data(); $response = $this->deleteJson('/sciice/authorize/13'); $response->assertStatus(200); $res = $this->get_data(); $this->assertEquals(12, count($res->original)); } protected function get_data() { return $this->getJson('/sciice/authorize'); } protected function post_data() { return $this->postJson('/sciice/authorize', $this->arr_data()); } protected function arr_data($name = 'test_authorize', $parent = 0) { return [ 'name' => $name, 'title' => 'test_authorize_title', 'grouping' => 'sciice', 'parent' => $parent, ]; } } <file_sep><?php namespace Sciice\Http\Controller; use Illuminate\Http\Request; use Sciice\Foundation\Sciice; use Sciice\Http\Service\RoleService; use Sciice\Http\Service\SciiceService; use Sciice\Http\Service\AuthorizeService; class HomeController extends Controller { /** * @var \Sciice\Contract\Service|SciiceService */ private $sciiceService; /** * @var \Sciice\Contract\Service|RoleService */ private $roleService; /** * @var \Sciice\Contract\Service|AuthorizeService */ private $authorizeService; /** * @var Sciice */ private $sciice; /** * HomeController constructor. * * @param \Sciice\Contract\Service|SciiceService $sciiceService * @param \Sciice\Contract\Service|RoleService $roleService * @param \Sciice\Contract\Service|AuthorizeService $authorizeService * @param Sciice $sciice */ public function __construct( SciiceService $sciiceService, RoleService $roleService, AuthorizeService $authorizeService, Sciice $sciice ) { $this->sciiceService = $sciiceService; $this->roleService = $roleService; $this->authorizeService = $authorizeService; $this->sciice = $sciice; $this->middleware('sciice.auth:sciice'); } /** * @param Request $request * * @return \Illuminate\Http\JsonResponse */ public function index(Request $request) { $authorize = $request->user('sciice')->getAllPermissions()->pluck('name')->toArray(); return response()->json([ 'user' => $this->sciiceService->resource($request->user('sciice')->id), 'menu' => $this->sciice->menu()->filterMenu($authorize)->formatMenu()->toArray(), 'auth' => $this->authorizeService->resources(), 'role' => $this->roleService->resources(), 'authorize' => $authorize, ]); } /** * @param Request $request * * @return mixed */ public function avatar(Request $request) { return $this->sciiceService ->avatarImageUpload($request) ->resource($request->user('sciice')->id); } /** * @param Request $request * * @return mixed */ public function user(Request $request) { return $this->sciiceService ->updateUserInfo($request) ->resource($request->user('sciice')->id); } } <file_sep><?php namespace Sciice\Http\Resource; use Illuminate\Http\Resources\Json\JsonResource; /** * @property mixed id * @property mixed name * @property mixed username * @property mixed email * @property mixed mobile * @property mixed avatar * @property mixed roles * @property mixed state * @property mixed created_at * @property mixed updated_at * @method imageUrl(string $string) */ class SciiceResource extends JsonResource { public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, 'username' => $this->username, 'email' => $this->email, 'mobile' => $this->mobile, 'avatar' => $this->when($this->avatar, $this->imageUrl('avatar')), $this->mergeWhen($this->whenLoaded('roles'), [ 'role_id' => optional($this->roles->first())->id, 'role_name' => optional($this->roles->first())->title, ]), 'state' => $this->state, 'created_at' => (string) $this->created_at, 'updated_at' => (string) $this->updated_at, ]; } } <file_sep><?php use Illuminate\Support\Facades\Route; Route::view('/', 'sciice::base'); Route::get('script/{name}', 'ResourcesController@script'); Route::get('style/{name}', 'ResourcesController@style'); Route::get('component/{name}', 'ResourcesController@component'); Route::post('login', 'LoginController@login'); Route::post('logout', 'LoginController@logout'); Route::get('initialize', 'HomeController@index'); Route::post('update', 'HomeController@user'); Route::post('avatar', 'HomeController@avatar'); Route::middleware(['sciice.auth:sciice', 'authorize:sciice'])->group(function () { Route::apiResources([ 'user' => 'SciiceController', 'role' => 'RoleController', 'authorize' => 'AuthorizeController', ]); }); <file_sep><?php namespace Sciice\Http\Controller; use Sciice\Http\Request\RoleRequest; use Sciice\Http\Service\RoleService; use Sciice\Foundation\ServiceController; class RoleController extends Controller { use ServiceController; /** * @var \Sciice\Contract\Service|RoleService */ private $service; /** * RoleController constructor. * * @param \Sciice\Contract\Service|RoleService $service */ public function __construct(RoleService $service) { $this->service = $service; } /** * @param RoleRequest $request * * @return mixed */ public function store(RoleRequest $request) { return $this->service()->storeAs($request)->response(); } /** * @param RoleRequest $request * @param int $id * * @return mixed */ public function update(RoleRequest $request, int $id) { return $this->service()->updateAs($request, $id)->response(); } /** * @return mixed */ protected function service() { return $this->service; } } <file_sep><?php namespace Sciice\Http\Service; use Sciice\Model\Sciice; use Illuminate\Http\Request; use Sciice\Contract\Service; use Sciice\Foundation\ServiceResponse; use Sciice\Http\Resource\SciiceResource; class SciiceService implements Service { use ServiceResponse; /** * @var \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model */ private $sciice; /** * SciiceService constructor. * * @param \Illuminate\Database\Eloquent\Builder|Sciice $sciice */ public function __construct(Sciice $sciice) { $this->sciice = $sciice->getModel(); } /** * @return mixed */ public function resources() { return SciiceResource::collection($this->sciice->with('roles')->paginate()); } /** * @param int $id * * @return mixed */ public function resource(int $id) { return new SciiceResource($this->sciice->with('roles')->findOrFail($id)); } /** * @param Request $request * * @return $this */ public function storeAs(Request $request) { $this->sciice->create($request->except('role')) ->assignRole($request->input('role')); return $this; } /** * @param Request $request * @param int $id * * @return $this */ public function updateAs(Request $request, int $id) { abort_if($id === 1, 403, __('该账号不允许编辑')); $query = $this->sciice->findOrFail($id); $query->update($request->except(['username', 'role'])); $query->syncRoles($request->input('role')); return $this; } /** * @param int $id * * @return $this|Service * @throws \Exception */ public function deleteAs(int $id) { abort_if($id === 1, 403, __('该账号不允许删除')); $this->sciice->findOrFail($id)->delete(); return $this; } /** * @param Request $request * * @return $this */ public function updateUserInfo(Request $request) { $this->sciice->findOrFail($request->user('sciice')->id) ->update($request->except('username')); return $this; } /** * @param Request $request * * @return $this */ public function avatarImageUpload(Request $request) { $this->sciice->findOrFail($request->user('sciice')->id) ->uploadImage($request->file('avatar'), 'avatar'); return $this; } } <file_sep><?php namespace Sciice\Model; use QCod\ImageUp\HasImageUploads; use Illuminate\Foundation\Auth\User; use Illuminate\Support\Facades\Hash; use Spatie\Permission\Traits\HasRoles; use Illuminate\Notifications\Notifiable; class Sciice extends User { use Notifiable, HasRoles, HasImageUploads; /** * @var array */ protected static $imageFields = [ 'avatar' => [ 'width' => 200, 'height' => '200', 'path' => 'avatar', 'rules' => 'image|mimes:jpeg,jpg,png|max:2000', ], ]; /** * @var string */ protected $table = 'sciice'; /** * @var string */ protected $guard_name = 'sciice'; /** * @var array */ protected $guarded = ['id']; /** * @var array */ protected $hidden = ['password']; /** * @param $value */ public function setPasswordAttribute($value) { $this->attributes['password'] = <PASSWORD>($<PASSWORD>); } } <file_sep><?php namespace Sciice\Http\Request; use Illuminate\Validation\Rule; use Sciice\Foundation\Form\Request; class RoleRequest extends Request { /** * @return array */ public function rules() { return [ 'name' => ['required', 'string', Rule::unique('roles')], 'title' => 'required|string', ]; } /** * @return array */ public function update() { return [ 'name' => ['required', 'string', Rule::unique('roles')->ignore($this->route('role'))], 'title' => 'required|string', ]; } } <file_sep><?php namespace Sciice\Foundation; use BadMethodCallException; class Sciice { /** * @var array */ public static $script = []; /** * @var array */ public static $style = []; /** * @var array */ public static $menu = []; /** * @var array */ public static $component = []; /** * 注册脚本资源. * * @param $name * @param $path * * @return Sciice */ public static function registerScript($name, $path) { static::$script[$name] = $path; return new static; } /** * 注册模块资源. * * @param $name * @param $path * * @return Sciice */ public static function registerComponent($name, $path) { static::$component[$name] = $path; return new static; } /** * 注册样式资源. * * @param $name * @param $path * * @return Sciice */ public static function registerStyle($name, $path) { static::$style[$name] = $path; return new static; } /** * 注册菜单数据. * * @param array $menu * * @return Sciice */ public static function registerMenu(array $menu) { static::$menu = array_merge(static::$menu, $menu); return new static; } /** * 获取脚本资源. * * @return array */ public static function script() { return array_merge(static::$script, ['component' => __DIR__.'/../../dist/index.js']); } /** * 获取样式资源. * * @return array */ public static function style() { return array_merge(static::$style, [ 'component' => __DIR__.'/../../dist/index.css', 'umi' => __DIR__.'/../../dist/umi.css', ]); } /** * 获取模块资源. * * @return array */ public static function component() { return array_merge(static::$component, ['umi' => __DIR__.'/../../dist/umi.js']); } /** * 获取菜单数据. * * @return \Illuminate\Support\Collection */ public static function menu() { return collect(static::$menu)->sortBy('sort')->values(); } /** * 合并配置项. * * @param $path * @param $key */ public static function mergeConfigFrom($path, $key) { $config = config($key, []); app('config')->set($key, array_merge_recursive(require $path, $config)); } /** * @param $method * @param $parameters * * @return mixed */ public static function __callStatic($method, $parameters) { if (! property_exists(get_called_class(), $method)) { throw new BadMethodCallException("Method {$method} does not exist."); } return static::${$method}; } } <file_sep><?php namespace Sciice\Foundation; use Illuminate\Http\Request; trait ServiceController { /** * @return mixed */ public function index() { return $this->service()->resources(); } /** * @param int $id * * @return mixed */ public function show(int $id) { return $this->service()->resource($id); } /** * @param int $id * * @return mixed */ public function destroy(int $id) { return $this->service()->deleteAs($id)->response(); } /** * @param Request $request * * @return mixed */ abstract public function store(Request $request); /** * @param Request $request * @param int $id * * @return mixed */ abstract public function update(Request $request, int $id); /** * @return mixed */ abstract protected function service(); } <file_sep><?php namespace Sciice\Http\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Foundation\Auth\AuthenticatesUsers; class LoginController extends Controller { use AuthenticatesUsers; /** * LoginController constructor. */ public function __construct() { $this->middleware('sciice.auth:sciice')->except('login'); } /** * {@inheritdoc} */ protected function validateLogin(Request $request) { $request->validate([ $this->username() => 'required|string|min:4', 'password' => 'required|string|min:5', ]); } /** * @param Request $request * * @return bool */ protected function attemptLogin(Request $request) { if (config('sciice.many')) { return collect(['username', 'email', 'mobile'])->contains(function ($value) use ($request) { return $this->guard()->attempt([ $value => $request->input($this->username()), 'password' => $request->input('password'), ], ! blank($request->input('remember'))); }); } return $this->guard()->attempt($this->credentials($request), ! blank($request->input('remember'))); } /** * @param Request $request * @param $user * * @return \Illuminate\Http\JsonResponse */ protected function authenticated(Request $request, $user) { return $this->json(__('登录成功')); } /** * @param Request $request * * @return \Illuminate\Http\JsonResponse */ public function logout(Request $request) { $user = $this->guard()->user(); $this->guard()->logout(); $request->session()->invalidate(); return $this->json(__('退出成功')); } /** * @return string */ public function username() { return 'username'; } /** * @return mixed */ protected function guard() { return Auth::guard('sciice'); } } <file_sep><?php namespace Sciice\Tests; use Sciice\Model\Sciice; class LoginTest extends TestCase { public function test_login_successful() { factory(Sciice::class)->create(); $list = $this->json('POST', '/sciice/login', [ 'username' => 'test', 'password' => '<PASSWORD>', ]); $list->assertOk(); } public function test_login_validate_rule() { factory(Sciice::class)->create(); $list = $this->json('POST', '/sciice/login', [ 'username' => 'test', 'password' => '123', ]); $list->assertStatus(422); } } <file_sep><?php namespace Sciice\Http\Service; use Illuminate\Http\Request; use Sciice\Contract\Service; use Spatie\Permission\Models\Role; use Sciice\Foundation\ServiceResponse; use Sciice\Http\Resource\RoleResource; class RoleService implements Service { use ServiceResponse; /** * @var \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model */ private $role; /** * RoleService constructor. * * @param \Illuminate\Database\Eloquent\Builder|Role $role */ public function __construct(Role $role) { $this->role = $role->getModel(); } /** * @return mixed */ public function resources() { return RoleResource::collection($this->role->whereGuardName('sciice')->get()); } /** * @param int $id * * @return mixed */ public function resource(int $id) { $query = $this->role->findOrFail($id); $authorize = $query->permissions()->pluck('id'); return (new RoleResource($query)) ->additional(['authorize' => $authorize]); } /** * @param Request $request * * @return $this */ public function storeAs(Request $request) { $this->role->create(array_merge($request->except('authorize'), ['guard_name' => 'sciice'])) ->syncPermissions($request->input('authorize')); return $this; } /** * @param Request $request * @param int $id * * @return $this */ public function updateAs(Request $request, int $id) { $query = $this->role->findOrFail($id); $query->update($request->except('authorize')); if ($id !== 1) { $query->syncPermissions($request->input('authorize')); } return $this; } /** * @param int $id * * @return $this * @throws \Exception */ public function deleteAs(int $id) { abort_if($id === 1, 403, '该角色组不允许删除'); $this->role->findOrFail($id)->delete(); return $this; } } <file_sep><?php namespace Sciice\Tests; use Sciice\Facades\Sciice; use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; use Sciice\Provider\SciiceServiceProvider; use Spatie\Permission\PermissionServiceProvider; class TestCase extends \Orchestra\Testbench\TestCase { protected $authenticatedAs; protected function setUp() { parent::setUp(); $this->loadMigrationsFrom(__DIR__.'/migrations'); $this->withFactories(__DIR__.'/factories'); $this->withHeader('X-Requested-With', 'XMLHttpRequest'); } protected function getPackageProviders($app) { return [ SciiceServiceProvider::class, PermissionServiceProvider::class, ]; } protected function getPackageAliases($app) { return [ 'Sciice' => Sciice::class, ]; } protected function resolveApplicationCore($app) { parent::resolveApplicationCore($app); $app->detectEnvironment(function () { return 'testing'; }); } protected function getEnvironmentSetUp($app) { $config = $app->get('config'); $config->set('app.key', '<KEY>'); $config->set('database.default', 'testing'); $config->set('database.connections.testing', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); } protected function getApplicationTimezone($app) { return 'Asia/Shanghai'; } protected function authenticate() { $user = factory(\Sciice\Model\Sciice::class)->create(); $role = Role::create(['name' => 'test', 'title' => 'test', 'guard_name' => 'sciice']); $arrController = ['user', 'role', 'authorize']; $arrAction = ['index', 'store', 'update', 'destroy']; foreach ($arrController as $item) { foreach ($arrAction as $value) { Permission::create([ 'name' => 'sciice.'.$item.'.'.$value, 'title' => $item.'.'.$value, 'guard_name' => 'sciice', 'grouping' => 'sciice', ])->assignRole($role); } } $user->assignRole($role); $this->actingAs($user, 'sciice'); return $user; } } <file_sep><?php namespace Sciice\Command; use Illuminate\Console\Command; class Install extends Command { /** * @var string */ protected $signature = 'sciice:install'; /** * @var string */ protected $description = 'Install all of the Sciice resources.'; /** * Execute the console command. * * @throws \Exception */ public function handle() { $this->comment('Publishing Sciice Resources...'); $this->callSilent('vendor:publish', [ '--tag' => 'sciice-config', '--force' => true, ]); $this->registerSciiceServiceProvider(); $this->info('Sciice installed successfully.'); } /** * @return void */ protected function registerSciiceServiceProvider() { file_put_contents(config_path('app.php'), str_replace( "App\Providers\EventServiceProvider::class,".PHP_EOL, "App\Providers\EventServiceProvider::class,".PHP_EOL." Sciice\Provider\SciiceServiceProvider::class,".PHP_EOL, file_get_contents(config_path('app.php')) )); } } <file_sep><?php namespace Sciice\Provider; use Sciice\Rule\Mobile; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Validator; class ValidationServiceProvider extends ServiceProvider { public function boot() { foreach ($this->registerRule() as $item) { $rules = $item['class']; Validator::replacer($item['name'], function ($message, $attribute, $rule, $parameters) use ($rules) { return $rules->message(); }); Validator::extend($item['name'], function ($attribute, $value, $parameters, $validator) use ($rules) { return $rules->passes($attribute, $value); }); } } protected function registerRule() { return [ [ 'name' => 'mobile', 'class' => new Mobile(), ], ]; } } <file_sep><?php namespace Sciice\Provider; use Sciice\Command\Install; use Sciice\Foundation\Sciice; use Illuminate\Support\Facades\Route; use Sciice\Http\Middleware\Authorize; use Illuminate\Support\ServiceProvider; use Illuminate\Auth\Middleware\Authenticate; class SciiceServiceProvider extends ServiceProvider { public function boot() { if ($this->app->runningInConsole()) { $this->registerPublishing(); } $this->registerResources(); $this->registerServiceMenu(); $this->registerProvider(); foreach (config('sciice.style') as $name => $path) { Sciice::registerStyle($name, $path); } foreach (config('sciice.script') as $name => $path) { Sciice::registerScript($name, $path); } } public function register() { $this->app->singleton('sciice', function () { return new Sciice(); }); $this->registerMiddleware(); $this->registerConsole(); } /** * 发布资源. */ private function registerPublishing() { $this->publishes([ __DIR__.'/../../config/config.php' => config_path('sciice.php'), ], 'sciice-config'); $this->publishes([ __DIR__.'/../../resources/lang' => resource_path('lang/vendor/sciice'), ], 'sciice-lang'); $this->publishes([ __DIR__.'/../../resources/views' => resource_path('views/vendor/sciice'), ], 'sciice-views'); $this->publishes([ __DIR__.'/../../database/migrations' => database_path('migrations'), ], 'sciice-migrations'); } /** * 注册资源. */ private function registerResources() { if (! $this->app->configurationIsCached()) { $this->mergeConfigFrom(__DIR__.'/../../config/config.php', 'sciice'); // 添加一个 guard. Sciice::mergeConfigFrom(__DIR__.'/../../config/auth.php', 'auth'); } $this->loadViewsFrom(__DIR__.'/../../resources/views', 'sciice'); $this->loadTranslationsFrom(__DIR__.'/../../resources/lang', 'sciice'); $this->loadJsonTranslationsFrom(resource_path('lang/vendor/sciice')); $this->loadMigrationsFrom(__DIR__.'/../../database/migrations'); $this->registerRouter(); } /** * 注册后台菜单配置. */ private function registerServiceMenu() { Sciice::registerMenu(require __DIR__.'/../../config/menu.php'); } /** * 注册路由. */ private function registerRouter() { Route::group($this->configurationRouter(), function () { $this->loadRoutesFrom(__DIR__.'/../../router/router.php'); }); } /** * 路由配置. * * @return array */ private function configurationRouter() { return [ 'namespace' => 'Sciice\Http\Controller', 'as' => 'sciice.', 'prefix' => config('sciice.path'), 'middleware' => config('sciice.middleware'), ]; } /** * 注册其他服务 */ private function registerProvider() { $this->app->register(ValidationServiceProvider::class); $this->app->register(MacroServiceProvider::class); $this->app->register(BladeServiceProvider::class); } /** * 注册中间件. */ private function registerMiddleware() { $this->app['router']->aliasMiddleware('sciice.auth', Authenticate::class); $this->app['router']->aliasMiddleware('authorize', Authorize::class); } /** * 注册命令. */ private function registerConsole() { $this->commands([ Install::class, ]); } } <file_sep><?php namespace Sciice\Http\Request; use Illuminate\Validation\Rule; use Sciice\Foundation\Form\Request; use Sciice\Foundation\Form\ValidatorSometime; class SciiceRequest extends Request { /** * @return array */ public function rules() { return [ 'name' => 'required|string', 'username' => 'required|min:4|string|unique:sciice', 'email' => 'required|email|unique:sciice', 'mobile' => 'required|mobile|unique:sciice', 'role' => 'required', 'password' => '<PASSWORD>', ]; } /** * @return array */ public function update() { return [ 'name' => 'required|string', 'username' => ['required', 'min:4', 'string', Rule::unique('sciice')->ignore($this->route('user'))], 'email' => ['required', 'email', Rule::unique('sciice')->ignore($this->route('user'))], 'mobile' => ['required', 'mobile', Rule::unique('sciice')->ignore($this->route('user'))], 'role' => 'required', ]; } /** * @param $validator * * @return ValidatorSometime * @throws \Illuminate\Validation\ValidationException */ public function updateWithValidator($validator) { return ValidatorSometime::make($validator)->rule('password', '<PASSWORD>')->validate(); } /** * @return array */ public function messages() { return [ 'role.required' => '角色组不允许为空', ]; } } <file_sep><?php namespace Sciice\Http\Middleware; use Closure; use Illuminate\Support\Facades\Route; class Authorize { /** * @var array */ private $abilities = [ 'show' => 'update', ]; /** * @param $request * @param Closure $next * @param null $guard * * @return mixed */ public function handle($request, Closure $next, $guard = null) { $method = str_after(Route::currentRouteAction(), '@'); $name = Route::currentRouteName(); if (array_get($this->abilities, $method)) { $name = str_before($name, $method).array_get($this->abilities, $method); } if (auth($guard)->user()->can($name)) { return $next($request); } return abort(403, '无权限访问!'); } } <file_sep><?php namespace Sciice\Http\Controller; use Illuminate\Http\Request; use Sciice\Foundation\Sciice; class ResourcesController extends Controller { /** * @param Request $request * @param $name * * @return \Illuminate\Http\Response */ public function script(Request $request, $name) { return response( file_get_contents(Sciice::script()[$name]), 200, ['Content-Type' => 'application/javascript'] ); } /** * @param Request $request * @param $name * * @return \Illuminate\Http\Response */ public function component(Request $request, $name) { return response( file_get_contents(Sciice::component()[$name]), 200, ['Content-Type' => 'application/javascript'] ); } /** * @param Request $request * @param $name * * @return \Illuminate\Http\Response */ public function style(Request $request, $name) { return response( file_get_contents(Sciice::style()[$name]), 200, ['Content-Type' => 'text/css'] ); } } <file_sep><?php namespace Sciice\Http\Controller; use Sciice\Http\Request\SciiceRequest; use Sciice\Http\Service\SciiceService; use Sciice\Foundation\ServiceController; class SciiceController extends Controller { use ServiceController; /** * @var \Sciice\Contract\Service|SciiceService */ private $service; /** * SciiceController constructor. * * @param \Sciice\Contract\Service|SciiceService $service */ public function __construct(SciiceService $service) { $this->service = $service; } /** * @param $request * * @return mixed */ public function store(SciiceRequest $request) { return $this->service()->storeAs($request)->response(); } /** * @param SciiceRequest $request * @param int $id * * @return mixed */ public function update(SciiceRequest $request, int $id) { return $this->service()->updateAs($request, $id)->response(); } /** * @return mixed */ protected function service() { return $this->service; } } <file_sep><?php return [ // 后台路径 'path' => 'sciice', // 中间件 'middleware' => ['web'], // 是否开启多字段登录 'many' => false, // 样式 'style' => [ 'antd' => 'https://unpkg.com/[email protected]/dist/antd.min.css', //'umi' => 'http://localhost:8000/umi.css', ], // 脚本 'script' => [ 'react' => 'https://unpkg.com/[email protected]/umd/react.development.js', 'react-dom' => 'https://unpkg.com/[email protected]/umd/react-dom.development.js', 'dva' => 'https://unpkg.com/[email protected]/dist/dva.js', 'moment' => 'https://unpkg.com/[email protected]/min/moment.min.js', 'antd' => 'https://unpkg.com/[email protected]/dist/antd.min.js', //'umi' => 'http://localhost:8000/umi.js', ], ]; <file_sep># 管理模块 [![Build Status](https://travis-ci.com/sciice/sciice.svg?branch=master)](https://travis-ci.com/sciice/sciice) [![StyleCI](https://github.styleci.io/repos/163223362/shield?branch=master)](https://github.styleci.io/repos/163223362) --- 开发中. <file_sep><?php namespace Sciice\Http\Controller; use Sciice\Foundation\ServiceController; use Sciice\Http\Request\AuthorizeRequest; use Sciice\Http\Service\AuthorizeService; class AuthorizeController extends Controller { use ServiceController; /** * @var \Sciice\Contract\Service|AuthorizeService */ private $service; /** * AuthorizeController constructor. * * @param \Sciice\Contract\Service|AuthorizeService $service */ public function __construct(AuthorizeService $service) { $this->service = $service; } /** * @param AuthorizeRequest $request * * @return mixed */ public function store(AuthorizeRequest $request) { return $this->service()->storeAs($request)->response(); } /** * @param AuthorizeRequest $request * @param int $id * * @return mixed */ public function update(AuthorizeRequest $request, int $id) { return $this->service()->updateAs($request, $id)->response(); } /** * @return AuthorizeService */ protected function service() { return $this->service; } } <file_sep><?php namespace Sciice\Contract; use Illuminate\Http\Request; interface Service { /** * @return mixed */ public function response(); /** * @return mixed */ public function resources(); /** * @param int $id * * @return mixed */ public function resource(int $id); /** * @param Request $request * * @return $this */ public function storeAs(Request $request); /** * @param Request $request * @param int $id * * @return $this */ public function updateAs(Request $request, int $id); /** * @param int $id * * @return $this * @throws \Exception */ public function deleteAs(int $id); }
446a6e8c1e8e263baad936b6ffdb325f28a7d112
[ "Markdown", "PHP" ]
32
PHP
sciice/sciice
77b95fd0f3603e673590bf7bd5e755b23614027e
cc8878e97483b6d5094a0ca806a316362632c7ab
refs/heads/master
<repo_name>CaosZero/Exam-70-480<file_sep>/JS/typeof.js /* Type Result undefined "undefined" null "object" Boolean "boolean" Number "number" NaN "number" String "string" function" "function" Array "object" Any Obj. "object" */ (function () { })(); <file_sep>/JS/Arrays.js (function () { var sports = new Array('football', 'cricket', 'rugby', 'tennis', 'badminto'); //The length property // sport.length; //The concat method var moreSports = new Array('soccer', 'basketball', 'hockey'); var combinedSports = sports.concat(moreSports); //The indexOf and lastIndexOf Method /** * The indexOf method accepts two parameters: what to search for and the index at which to * begin searching. This example searches the entire array, so the search starts at index 0. * To search in descending order—that is, * to search from the end of the array to the beginning—use the lastIndexOf method, which * accepts the same parameters. */ var index = sports.indexOf('football', 0); /** TIP! : * The indexOf method uses the identity operator to check for equality, which means that * if an array contains strings such as ‘1’, ‘2’, and ‘3’ and you’re searching for the integer 3, the * result is –1 because the equality operation returns false for all elements in the array. */ /**The join method * join method accepts a string as a parameter, which is the string used as a delimiter * to separate the values in the array. The result is a string of all the elements separated by the * string passed into the join method. */ var joined = sports.join(','); /** The reverse method reverses the sequence of all elements in the array. */ var reversed = sports.reverse(); /** The slice method * The slice method takes out one or more items in an array and moves them to a new array. * The slice method takes two parameters: the indexes where the slice operation should * begin and end. The ending index isn’t included in the slice. */ var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(1, 3); /* *The splice method returns an array containing the items that are spliced out of the source * array. The first parameter is the index in the array where the splice operation should start. * The second parameter is the number of items to splice, starting from the index specified in * the first parameter. The optional last parameter lists items that are to replace the items being * spliced out. The list doesn’t have to be the same length as the items being spliced out. * */ var otherFruits = ["Banana", "Orange", "Apple", "Mango"]; otherFruits.splice(2, 0, "Lemon", "Kiwi"); console.log(otherFruits); /* * The push method appends the specified items to the end of the array. * The pop method removes the last item from the array. * */ var otherSport = new Array('football'); otherSport.push('basketball'); otherSport.pop(); /* * The shift method removes and returns the first element of the array. * The unshift method inserts new elements at the beginning of the array * */ var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.shift(); // => "Orange", "Apple", "Mango"]; var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.unshift("Lemon", "Pineapple"); // => Lemon,Pineapple,Banana,Orange,Apple,Mango /**The sort method sequences the items in the array in ascending order. */ var sports = new Array('soccer', 'basketball', 'hockey', 'football', 'cricket', 'rugby', 'tennis', 'badminton'); })();<file_sep>/JS/Comparision.js (function () { console.log(21 == "21"); //true console.log(undefined == null); //true console.log(undefined === null); //false console.log(21 === 21); //true console.log({} === {}); //false console.log(NaN === NaN); //false console.log(true == { valueOf: function () { return "1" } }); //true /** * Equality (===) * Is only true if the operands are of the same type and the contents match. * */ /* === with primitives */ var str1 = "hi"; var str2 = "hi"; console.log(str1 === str2); //true /* === with object */ // --> Check by reference, check by adress. Are 2 object with different adress var obj1 = {}; var obj2 = {}; console.log(obj1 === obj2); //false; /** * Abstract comparison (==) * Converts the operands to the same type before making the comparison. * Abstract comparisons (e.g., <=), the operands are first converted to primitives, then to the same type, before comparison. */ })(); <file_sep>/JS/Window Object.js (function () { function ShowMessage(mes) { document.getElementById("message").innerHTML += "<p>" + msg + "</p>"; } ShowMessage("window.name" + window.name); ShowMessage("window.innerWidth" + window.innerWidth); ShowMessage("window.innerHeight" + window.innerHeight); ShowMessage("window.innerHeight" + window.innerHeight); ShowMessage("window.innerHeight" + window.innerHeight); ShowMessage("window.screenX" + window.screenX); ShowMessage("window.screenY" + window.screenY); ShowMessage("window.pageXOffset" + window.pageXOffset); ShowMessage("window.pageYOffset" + window.pageYOffset); ShowMessage("window.location" + window.location); ShowMessage("window.location" + window.location); ShowMessage("window.location.protocol" + window.location.protocol); ShowMessage("window.location.hostname" + window.location.hostname); ShowMessage("window.location.port" + window.location.port); ShowMessage("window.location.search" + window.location.search); ShowMessage("window.location.hash" + window.location.hash); //window.scrollTo(0, 100); //window.alert("Hello World"); //window.prompt("What is your name"); //window.print(); //window.open("", "Window", "widht=300,height=300"); })();<file_sep>/JS/WebWorker.js var started = false; self.onmessage = function(event) { if(event.data == "START") { startWork(); } else { sendMessage(event.data); } function startWork() { started = true; self.postMessage("Worked started"); } function sendMessage(message) { if(started) setTimeout(function() { self.postMessage(message); }, 8000); } }<file_sep>/JS/Object Create.js (function () { Animal = { init: function (name) { this.name = name; }, eats: function () { return this.name + "is eating" } } /**Extends Chordate from Animal */ Chordate = Object.create(Animal, { has_spine: { value: true } }); /**Extends Chordate from Chordate */ Mammal = Object.create(Chordate, { has_hair: { value: true } }); var mam = Object.create(Mammal); m.init('dog'); })()<file_sep>/JS/DOMEvent_Focus.js (function () { var focus = document.getElementById("focusText"); var keyboard = document.getElementById("keyboardText"); focus.addEventListener("focus", function () { this.style.background = "yellow"; console.log("Focus on element"); }); focus.addEventListener("blur", function () { this.style.background = "white"; console.log("Blur on element"); }); /** * Keydown: * Raised when a key is pusdhed down */ keyboard.addEventListener("keydown", function () { var li = document.createElement("li"); li.innerText = window.event.keyCode; document.getElementById("outputText").appendChild(li); }); /** * Keyup: * Raised when a key is released */ keyboard.addEventListener("keyup", function () { var li = document.createElement("li"); li.innerText = "Keyup" + window.event.keyCode; document.getElementById("outputText").appendChild(li); }); /** * Other Events : * altKey : return a boolean value to indicate when the Alt Key was pressed -> window.event.altKey * ctrlKey: return a boolean value to indicate when the Ctrl Key was pressed -> window.event.ctrlKey * shifKey: return a boolean value to indicate when the Shift Key was pressed -> window.event.shifKey * keyCode: return numer code for the key that was pressed */ })();<file_sep>/JS/Delete.js (function () { var me = { name: { first: 'Ruslan' } }, name = me.name; name = { first: 'Alexis' }; delete me.name; console.log(me.name); //undefined console.log(name.first); //Alexis })(); <file_sep>/JS/Context.js (function () { var dog = { barkCount: 0, bark: function (barks) { this.barkCount++; } }, cat = { barkCount: 0 } var bark = dog.bark; // -> In this case 'this' will point to dog object dog.bark.call(cat, 1); // -> In this casa this is cat Person = function (name) { this.name = name; } var p1 = new Person("Ruslan"); // In this case point to p this.name var p2 = Person("Vasyunin"); // In this case will point to window object /** * SEE PROTO CHAIN * Foo has inheritance from 'Base Object'' that have two properties: * __proto__ = null * toString : function() * This is how we find toString() function */ var foo = {}; foo.toString(); /** * Search property inside PROTO CHAIN */ DOT = function (obj, prop) { if (obj.hasOwnProperty(prop)) { return obj[prop]; } else { return DOT(obj.__proto__, prop); } } })();
298964a502d4c5d57b555f3b13a831b79a3ef66b
[ "JavaScript" ]
9
JavaScript
CaosZero/Exam-70-480
8dd4cd8b818cb951334f510ca857f4038b4e92f2
b933e97dfb1418059f10a14de7f359676d02b28b
refs/heads/master
<file_sep># Creating-w-data-T2 Weekly and assignment posts <file_sep>let style; let video; let resultImg; function setup() { createCanvas(320, 240).parent('canvasContainer'); video = createCapture(VIDEO); video.hide(); // The results image from the style transfer resultImg = createImg(''); resultImg.hide(); // Create a new Style Transfer method with a defined style. style = ml5.styleTransfer('models/fuchun', video, modelLoaded); } function draw(){ image(resultImg, 0, 0, 320, 240); } // A function to call when the model has been loaded. function modelLoaded() { select('#status').html('Model Loaded'); style.transfer(gotResult); } // When we get the results, update the result image src function gotResult(err, img) { resultImg.attribute('src', img.src); style.transfer(gotResult); }
5a506993ad140efed3ca48cb35a92c996b43cfed
[ "Markdown", "JavaScript" ]
2
Markdown
akaparallel/Creating-w-data-T2
d2026cdcd4be17e0349f836aab94e300df25444b
68a8eca89881743c3ba56e4fb3e582c3f1e9a132
refs/heads/main
<repo_name>Johnlky/DC-Boxjelly<file_sep>/data/jobs/CAL00003/NE 2571 3661/meta.ini [DEFAULT] model = NE 2571 serial = 3661 <file_sep>/app/gui/main.py from os import error, name from typing import Counter from PyQt5 import QtWidgets, QtGui from PyQt5 import QtCore from PyQt5.QtWidgets import QApplication, QErrorMessage, QMainWindow, QHeaderView, QTableView, QItemDelegate, QGraphicsScene, QFileDialog, QDialog, QProgressBar, QPushButton from PyQt5.QtCore import QObject, QRunnable, QThreadPool, Qt, QSortFilterProxyModel, QAbstractTableModel, QThread, pyqtSignal, pyqtSlot import sys from numpy import clongdouble, empty from pandas.io.pytables import Selection, SeriesFixed import pandas as pd import pyqtgraph as pg import os from pathlib import Path import logging import numpy as np import time import tempfile import shutil import dateutil.parser from app.gui.utils import loadUI, getHomeTableData, getEquipmentsTableData, getRunsTableData, getResultData, converTimeFormat, getConstantsTableData from app.core.models import Job, Equipment, MexRawFile, ConstantFile, MexRun, constant_file_config from app.core.resolvers import HeaderError, calculator, result_data, summary, extractionHeader, Header_data, pdf_visualization from app.gui import resources from app.export.pdf import get_pdf from datetime import datetime from copy import deepcopy from shutil import copyfile from app.core.definition import DATA_FOLDER, OPS_MANUAL logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) ''' #Run UI main file under root dir py -m app.gui.main ''' ''' Alter Python identifier to custom one for the purpose of icon placement ''' try: # Include in try/except block if you're also targeting Mac/Linux from PyQt5.QtWinExtras import QtWin myappid = 'com.unimelb.software.dc' QtWin.setCurrentProcessExplicitAppUserModelID(myappid) except ImportError: pass class MainWindow(QMainWindow): JOB_LIST_WINDOW_TITLE = 'Job List' CLIENT_INFO_WINDOW_TITLE = 'Client Info' EQUIPMENT_INFO_WINDOW_TITLE = 'Equipment Info' def __init__(self): QMainWindow.__init__(self) # load main window ui window = loadUI(':/ui/main_window.ui', self) #window = loadUI("./app/gui/main_window.ui", self) self.ui = window self.setWindowTitle(self.JOB_LIST_WINDOW_TITLE) # load other windows self.addClientWindow = AddClientWindow(self) self.constantsWindow = ConstantsWindow(self) self.importWindow = ImportWindow(self) self.homeImportWindow = HomeImportWindow(self) self.analysisWindow = AnalyseWindow(self) self.addEquipmentWindow = AddEquipmentWindow(self) self.reuploadWindow = ReuploadWindow(self) # Home Page self.ui.homeButton.clicked.connect(lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.homePage)) self.ui.homeButton.clicked.connect(lambda: self.setWindowTitle(self.JOB_LIST_WINDOW_TITLE)) # Support Button self.ui.supportButton.clicked.connect(self.openSupport) # View/Edit Client Info self.ui.chooseClientButton.clicked.connect(self.chooseClient) self.ui.addClientButton.clicked.connect(lambda: self.ui.homeTable.clearSelection()) self.ui.updateClientButton.clicked.connect(self.updateClientInfo) self.ui.clientNamelineEdit.textChanged.connect(lambda: self.ui.updateClientButton.setEnabled(True)) self.ui.address1lineEdit.textChanged.connect(lambda: self.ui.updateClientButton.setEnabled(True)) self.ui.address2lineEdit.textChanged.connect(lambda: self.ui.updateClientButton.setEnabled(True)) #compare page self.ui.chooseEquipmentButton.clicked.connect(self.chooseEquipment) # Return to Home Page self.ui.returnButton.clicked.connect(lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.homePage)) self.ui.returnButton.clicked.connect(lambda: self.ui.equipmentsTable.clearSelection()) self.ui.returnButton.clicked.connect(lambda: self.ui.updateClientButton.setEnabled(False)) self.ui.returnButton.clicked.connect(lambda: self.setWindowTitle(self.JOB_LIST_WINDOW_TITLE)) # Return to Client Info Page self.ui.returnButton_2.clicked.connect(lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.clientInfoPage)) self.ui.returnButton_2.clicked.connect(lambda: self.ui.runsTable.clearSelection()) self.ui.returnButton_2.clicked.connect(lambda: self.setWindowTitle(self.CLIENT_INFO_WINDOW_TITLE)) # Delete client self.ui.deleteClientButton.clicked.connect(self.deleteClient) # Add equipment self.ui.addEquipmentButton.clicked.connect(lambda: self.ui.equipmentsTable.clearSelection()) # Delete equipment self.ui.deleteEquipmentButton.clicked.connect(self.deleteEquipment) # Add and delete run self.ui.importButton.clicked.connect(lambda: self.ui.runsTable.clearSelection()) self.ui.deleteRunButton.clicked.connect(self.deleteRun) #Dynamic search self.ui.homeTable.horizontalHeader().setStyleSheet("QHeaderView { font-size: 12pt; font-family: Verdana; font-weight: bold; }") self.clientModel = TableModel(data=getHomeTableData()) self.proxy_model = QSortFilterProxyModel(self) self.proxy_model.setFilterKeyColumn(-1) # Search all columns. self.proxy_model.setSourceModel(self.clientModel) self.proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive) self.ui.searchBar.textChanged.connect(self.proxy_model.setFilterFixedString) self.ui.searchBar.textEdited.connect(self.ui.homeTable.clearSelection) self.ui.homeTable.setModel(self.proxy_model) self.ui.homeTable.setSortingEnabled(True) self.ui.homeTable.sortByColumn(0, Qt.AscendingOrder) self.ui.homeTable.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) #column stretch to window size self.ui.homeTable.setItemDelegate(AlignDelegate()) # text alignment self.ui.homeTable.doubleClicked.connect(self.chooseClient) # double click for choose client ## Table insertion # Equipment Table self.ui.equipmentsTable.horizontalHeader().setStyleSheet("QHeaderView { font-size: 12pt; font-family: Verdana; font-weight: bold; }") self.equipmentModel = TableModel(data=pd.DataFrame([])) self.equip_sortermodel = QSortFilterProxyModel() self.equip_sortermodel.setSourceModel(self.equipmentModel) self.ui.equipmentsTable.setModel(self.equip_sortermodel) self.ui.equipmentsTable.setSortingEnabled(True) self.ui.equipmentsTable.sortByColumn(0, Qt.AscendingOrder) self.ui.equipmentsTable.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) self.ui.equipmentsTable.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection) self.ui.equipmentsTable.selectionModel().selectionChanged.connect(lambda: self.selection_changed('equipmentsTable')) self.ui.equipmentsTable.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.ui.equipmentsTable.setItemDelegate(AlignDelegate()) self.ui.equipmentsTable.doubleClicked.connect(self.chooseEquipment) # double click for choose equipment self._selectedEquipID = "" # Run Table self.ui.runsTable.horizontalHeader().setStyleSheet("QHeaderView { font-size: 12pt; font-family: Verdana; font-weight: bold; }") self.runModel = TableModel(data=pd.DataFrame([])) self.run_sortermodel = QSortFilterProxyModel() self.run_sortermodel.setSourceModel(self.runModel) self.ui.runsTable.setModel(self.run_sortermodel) self.ui.runsTable.setSortingEnabled(True) self.ui.runsTable.sortByColumn(0, Qt.AscendingOrder) self.ui.runsTable.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) self.ui.runsTable.selectionModel().selectionChanged.connect(lambda: self.selection_changed('runsTable')) self.ui.runsTable.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.ui.runsTable.customContextMenuRequested.connect(self.showContextMenu) self.ui.runsTable.setItemDelegate(AlignDelegate()) self.ui.runsTable.doubleClicked.connect(self.openAnalysisWindow) # double click for analyze # Support Icon self.ui.supportButton.setIcon(QtGui.QIcon(':/img/qsmark.png')) # Change selection behaviour. User can only select rows rather than cells. Single selection self.ui.homeTable.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) self.ui.homeTable.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection) self.ui.homeTable.selectionModel().selectionChanged.connect(lambda: self.selection_changed('homeTable')) self._selectedRows = [] self._selectedCalNum = "" self._selectedRuns = [] self._sourceIndex = {} def openSupport(self): """ Open manual file. """ try: os.startfile(os.path.join(OPS_MANUAL)) except FileNotFoundError: QtWidgets.QMessageBox.about(self, "Warning", "Operation Manual not found.") def chooseClient(self): """ Choose one client and goes into client info page. When not choosing any of the client, pop up a warning window """ if self._selectedRows: self.ui.updateClientButton.setEnabled(False) self.ui.stackedWidget.setCurrentWidget(self.ui.clientInfoPage) self.ui.homeTable.clearSelection() self.setWindowTitle(self.CLIENT_INFO_WINDOW_TITLE) else: QtWidgets.QMessageBox.about(self, "Warning", "Please choose a Client!") def deleteClient(self): """ Delete chosen client on the Home Page by clicking 'delete client' button. When not choosing any of the client, pop up a warning window """ if self._selectedRows: self.clientModel.layoutAboutToBeChanged.emit() self._selectedCalNum = self.clientModel._data.loc[self._sourceIndex["homeTable"], 'CAL Number'].to_list()[0] reply = QtWidgets.QMessageBox.question(self, u'Warning', u'Do you want delete this client?', QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: del Job[self._selectedCalNum] self.clientModel.initialiseTable(data=getHomeTableData()) self.clientModel.layoutChanged.emit() self.ui.homeTable.clearSelection() if self.clientModel.isTableEmpty: self._selectedRows = [] else: QtWidgets.QMessageBox.about(self, "Warning", "Please choose a client to delete.") def updateClientInfo(self): """ Update client info on the Client Info Page by clicking 'update' button. """ self.clientModel.layoutAboutToBeChanged.emit() self.ui.updateClientButton.setEnabled(False) newClientName = self.ui.clientNamelineEdit.text() newFstAddress = self.ui.address1lineEdit.text() newSndAddress = self.ui.address2lineEdit.text() try: Job[self._selectedCalNum].client_name = newClientName Job[self._selectedCalNum].client_address_1 = newFstAddress Job[self._selectedCalNum].client_address_2 = newSndAddress QtWidgets.QMessageBox.about(self, ' ', "Successfully updated user information.") except AttributeError: raise error("Job ID is not found!") # Update client info on the Home Page self.clientModel.initialiseTable(data=getHomeTableData()) self.clientModel.layoutChanged.emit() def chooseEquipment(self): """ Choose one equipment and goes into Equipment info page. When not choosing any of the equipments, pop up a warning window. """ if self._selectedRows: self.ui.stackedWidget.setCurrentWidget(self.ui.equipmentInfoPage) self._selectedRows = [] self.setWindowTitle(self.EQUIPMENT_INFO_WINDOW_TITLE) # Display the equipment info self.ui.label_eqCAL.setText(self._selectedCalNum) self.ui.label_eqCN.setText(Job[self._selectedCalNum].client_name) self.ui.label_eqSN.setText(Job[self._selectedCalNum][self._selectedEquipID].serial) self.ui.label_eqMN.setText(Job[self._selectedCalNum][self._selectedEquipID].model) self.ui.equipmentsTable.clearSelection() else: QtWidgets.QMessageBox.about(self, "Warning", "Please choose an Equipment!") def deleteEquipment(self): """ Delete chosen equipment on the Client Info Page by clicking 'delete equipment' button. When not choosing any of the equipment, pop up a warning window. """ if self._selectedRows: self.equipmentModel.layoutAboutToBeChanged.emit() self._selectedEquipID = self.equipmentModel._data.loc[self._sourceIndex["equipmentsTable"], 'ID'].to_list()[0] reply = QtWidgets.QMessageBox.question(self, u'Warning', u'Do you want delete this Equipment?', QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: del Job[self._selectedCalNum][self._selectedEquipID] self.equipmentModel.initialiseTable(data=getEquipmentsTableData(Job[self._selectedCalNum])) self.equipmentModel.layoutChanged.emit() self.ui.equipmentsTable.clearSelection() else: QtWidgets.QMessageBox.about(self, "Warning", "Please choose an equipment to delete.") def deleteRun(self): """ Delete chosen run on the Client Info Page by clicking 'delete run' button. When not choosing any of the equipment, pop up a warning window. """ if self._selectedRows: self.runModel.layoutAboutToBeChanged.emit() selectedRun = self.runModel._data.loc[self._sourceIndex["runsTable"], 'ID'].to_list() # logger.debug(selectedRun) reply = QtWidgets.QMessageBox.question(self, u'Warning', u'Do you want delete selected run or runs?', QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: for runId in selectedRun: try: del Job[self._selectedCalNum][self._selectedEquipID].mex[runId] except PermissionError: QtWidgets.QMessageBox.about(self, "Warning", "Please close the raw file first.") return self.runModel.initialiseTable(data=getRunsTableData(Job[self._selectedCalNum][self._selectedEquipID])) self.runModel.layoutChanged.emit() self.ui.runsTable.clearSelection() else: QtWidgets.QMessageBox.about(self, "Warning", "Please choose a run to delete.") def selection_changed(self, tableName): """ Return the index of selected rows in an array. """ try: # TODO Order is based on the selection. Need to sort first? modelIndex = getattr(self, tableName).selectionModel().selectedRows() # QModelIndexList self._selectedRows = [idx.row() for idx in modelIndex] self._sourceIndex = {} self.ui.runsTable.setContextMenuPolicy(Qt.PreventContextMenu) logger.debug(self._selectedRows) if tableName == "homeTable" and self._selectedRows != []: self.equipmentModel.layoutAboutToBeChanged.emit() source_selectedIndex = [self.proxy_model.mapToSource(modelIndex[0]).row()] self._sourceIndex.setdefault("homeTable", source_selectedIndex) logger.debug(source_selectedIndex) self._selectedCalNum = self.clientModel._data.loc[source_selectedIndex, 'CAL Number'].to_list()[0] logger.debug(self._selectedCalNum) self.ui.label_CALNum.setText(self._selectedCalNum) self.ui.clientNamelineEdit.setText(Job[self._selectedCalNum].client_name) self.ui.address1lineEdit.setText(Job[self._selectedCalNum].client_address_1) self.ui.address2lineEdit.setText(Job[self._selectedCalNum].client_address_2) self.equipmentModel.initialiseTable(data=getEquipmentsTableData(Job[self._selectedCalNum])) self.equipmentModel.layoutChanged.emit() self.ui.equipmentsTable.setColumnHidden(2, True) elif tableName == "equipmentsTable" and self._selectedRows != []: self.runModel.layoutAboutToBeChanged.emit() source_selectedIndex = [self.equip_sortermodel.mapToSource(modelIndex[0]).row()] self._sourceIndex.setdefault("equipmentsTable", source_selectedIndex) logger.debug(source_selectedIndex) self._selectedEquipID = self.equipmentModel._data.loc[source_selectedIndex, 'ID'].to_list()[0] self.runModel.initialiseTable(data=getRunsTableData(Job[self._selectedCalNum][self._selectedEquipID])) self.runModel.layoutChanged.emit() # self.ui.runsTable.setColumnHidden(2, True) elif tableName == "runsTable" and self._selectedRows != []: self.ui.runsTable.setContextMenuPolicy(Qt.CustomContextMenu) source_selectedIndex = [] for idx in modelIndex: source_selectedIndex.append(self.run_sortermodel.mapToSource(idx).row()) self._sourceIndex.setdefault("runsTable", source_selectedIndex) logger.debug(source_selectedIndex) selectedRuns = self.runModel._data.loc[sorted(source_selectedIndex), 'ID'].to_list() runs = list(map(lambda runId:Job[self._selectedCalNum][self._selectedEquipID].mex[runId], selectedRuns)) self._selectedRuns = runs logger.debug(self._selectedRuns) except AttributeError: raise AttributeError("Attribute does not exist! Table name may be altered!") def openConstantsWindow(self): """ Open constant file instead of open constant window. """ self.addClientWindow.setFixedSize(750, 500) self.constantsWindow.show() def openAddClientWindow(self): self.addClientWindow.setFixedSize(850, 320) self.addClientWindow.setWindowModality(Qt.ApplicationModal) self.addClientWindow.show() def openAddEquipmentWindow(self): self.addEquipmentWindow.setFixedSize(850, 320) self.addEquipmentWindow.setWindowModality(Qt.ApplicationModal) self.addEquipmentWindow.show() self.addEquipmentWindow.job = Job[self._selectedCalNum] def openImportWindow(self): self.importWindow.setFixedSize(850, 320) self.importWindow.setWindowModality(Qt.ApplicationModal) self.importWindow.show() self.importWindow.equip = Job[self._selectedCalNum][self._selectedEquipID] def openHomeImportWindow(self): self.homeImportWindow.setFixedSize(850, 320) self.homeImportWindow.setWindowModality(Qt.ApplicationModal) self.homeImportWindow.show() def openReuploadWindow(self): self.reuploadWindow.setFixedSize(850, 320) self.reuploadWindow.setWindowModality(Qt.ApplicationModal) self.reuploadWindow.show() def openAnalysisWindow(self): """ Choose runs and goes into the analysis page. When not choosing any of runs, pop up a warning window """ if self._selectedRows: try: self.analysisWindow.setRuns(self._selectedRuns) # initailize constants label if constant_file_config.default_id: if ConstantFile[constant_file_config.default_id].note: self.analysisWindow.ui.constantsLabel.setText("Current Constants File: %s (%s)" % (constant_file_config.default_id, ConstantFile[constant_file_config.default_id].note)) else: self.analysisWindow.ui.constantsLabel.setText("Current Constants File: %s " % constant_file_config.default_id) else: self.analysisWindow.ui.constantsLabel.setText("Current Constants File: Template Constants ") self.analysisWindow.setWindowModality(Qt.ApplicationModal) self.analysisWindow.show() self.ui.runsTable.clearSelection() except Exception as e: logger.error("Can't resolve raw data file!", exc_info=e) QtWidgets.QMessageBox.about(self, "Warning", "Can not resolve raw files. Please check the data.") else: QtWidgets.QMessageBox.about(self, "Warning", "Please choose at least one run to analyze.") def showContextMenu(self): self.ui.runsTable.contextMenu = QtWidgets.QMenu(self) self.ui.runsTable.contextMenu.setStyleSheet(""" QMenu:selected {background-color: #ddf; color: #000;} """ ) def add_action(name, handler): action = self.ui.runsTable.contextMenu.addAction(name) action.triggered.connect(lambda: self.actionHandler(handler)) add_action('Open raw client file', 'OpenClientFile') add_action('Open raw lab file', 'OpenLabFile') add_action('Re-upload', "Reupload") add_action('Export raw client to..', 'export_client') add_action('Export raw lab to..', 'export_lab') self.ui.runsTable.contextMenu.popup(QtGui.QCursor.pos()) # Menu position based on cursor self.ui.runsTable.contextMenu.show() def actionHandler(self, action): logger.debug("Open menu") # If multiple runs are chosen, only the first run is processed selectedRun = self.runModel._data.loc[sorted(self._sourceIndex["runsTable"]), 'ID'].to_list()[0] run = Job[self._selectedCalNum][self._selectedEquipID].mex[selectedRun] if action == "OpenClientFile": os.startfile(run.raw_client.path) elif action == "OpenLabFile": os.startfile(run.raw_lab.path) elif action == "Reupload": self.openReuploadWindow() self.reuploadWindow.setRuns(selectedRun, run) elif action == 'export_lab': self.export_raw_file(run.raw_lab, 'lab') elif action == 'export_client': self.export_raw_file(run.raw_client, 'client') def export_raw_file(self, raw: MexRawFile, type: str): if not raw.exists: QtWidgets.QErrorMessage().showMessage(f'The {type} file does not exist!') return path, _ = QFileDialog.getSaveFileName(self, f'Save {type} file to', raw.export_file_name, 'CSV Files (*.csv)') if path: raw.export_to(Path(path)) class ImportWindow(QMainWindow): def __init__(self, parent = None): super(ImportWindow, self).__init__(parent) self.parent = parent # load import page ui # window = loadUI(".\\app\\gui\\import_page.ui", self) #window = loadUI("./app/gui/import_page.ui", self) window = loadUI(':/ui/import_page.ui', self) self.ui = window self.equip: Equipment = None self.clientPath = self.ui.clientFilePathLine.text() self.labPath = self.ui.labFilePathLine.text() self.ui.clientFilePathLine.textChanged.connect(self.sync_clientLineEdit) self.ui.labFilePathLine.textChanged.connect(self.sync_labLineEdit) # link buttons to actions self.importClientFilebutton.clicked.connect(self.chooseRawClient) self.importLabFileButton.clicked.connect(self.chooseRawLab) self.importSubmitButton.clicked.connect(self.addNewRun) self.clientOpenFile.clicked.connect(self.openClientFile) self.labOpenFile.clicked.connect(self.openLabFile) def sync_clientLineEdit(self): self.clientPath = self.ui.clientFilePathLine.text() def sync_labLineEdit(self): self.labPath = self.ui.labFilePathLine.text() def chooseRawClient(self): file_filter = 'Raw Data File (*.csv)' self.clientPath = QFileDialog.getOpenFileName( parent = self, caption = 'Please Select Client Raw File', directory = os.getcwd(), filter = file_filter, initialFilter = 'Raw Data File (*.csv)' )[0] logger.debug("Client raw file: %s", self.clientPath) self.ui.clientFilePathLine.setText(self.clientPath) def chooseRawLab(self): file_filter = 'Raw Data File (*.csv)' self.labPath = QFileDialog.getOpenFileName( parent = self, caption = 'Please Select Lab Raw File', directory = os.getcwd(), filter = file_filter, initialFilter = 'Raw Data File (*.csv)' )[0] logger.debug("Lab raw file: %s", self.labPath) self.ui.labFilePathLine.setText(self.labPath) def addNewRun(self): self.parent.runModel.layoutAboutToBeChanged.emit() self.parent.ui.runsTable.clearSelection() if len(self.clientPath) == 0 or len(self.labPath) == 0: QtWidgets.QMessageBox.about(self, "Warning", "Please fill in both Client file and Lab file path.") return if (not os.path.isfile(self.clientPath)) or (not os.path.isfile(self.labPath)): QtWidgets.QMessageBox.about(self, "Warning", "File not found, Please check your file path.") return run: MexRun = self.equip.mex.add() run.raw_client.upload_from(Path(self.clientPath)) run.raw_lab.upload_from(Path(self.labPath)) error = self.equip.check_consistency() if error: run.delete() QErrorMessage(self).showMessage(error) return data = { 'ID': run.id, # 'Added Time': converTimeFormat(run.added_at), 'Edited Time': converTimeFormat(run.edited_at), 'Measurement Date': converTimeFormat(run.measured_at).split()[0], 'Operator': run.operator, } self.parent.runModel.addData(pd.DataFrame(data, index=[0])) self.parent.runModel.layoutChanged.emit() # Finish add new run and quit self.hide() self.equip = None self.clientPath = "" self.labPath = "" self.ui.clientFilePathLine.clear() self.ui.labFilePathLine.clear() # TODO: Display another window to confirm information def openClientFile(self): if not os.path.isfile(self.clientPath): QtWidgets.QMessageBox.about(self, "Warning", "Client file not found, Please check your file path.") return if self.clientPath != "": try: os.startfile(self.clientPath) except FileNotFoundError: QtWidgets.QMessageBox.about(self, "Warning", "File not found, Please check your path.") def openLabFile(self): if not os.path.isfile(self.labPath): QtWidgets.QMessageBox.about(self, "Warning", "Lab file not found, Please check your file path.") return if self.labPath != "": try: os.startfile(self.labPath) except FileNotFoundError: QtWidgets.QMessageBox.about(self, "Warning", "File not found, Please check your path.") def closeEvent(self, event): if len(self.ui.clientFilePathLine.text()) != 0 or len(self.ui.labFilePathLine.text()) != 0: reply = QtWidgets.QMessageBox.question(self, u'Warning', u'Close window? \nAll inputs will be clear.', QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: self.ui.clientFilePathLine.clear() self.ui.labFilePathLine.clear() event.accept() else: event.ignore() else: event.accept() class ReuploadWindow(ImportWindow): def __init__(self, parent=None): super().__init__(parent=parent) self.parent = parent self.selectedRun = None self.run = None def addNewRun(self): self.parent.runModel.layoutAboutToBeChanged.emit() self.parent.ui.runsTable.clearSelection() if len(self.clientPath) == 0 or len(self.labPath) == 0: QtWidgets.QMessageBox.about(self, "Warning", "Please choose or fill in both Client file and Lab file path.") return if (not os.path.isfile(self.clientPath)) or (not os.path.isfile(self.labPath)): QtWidgets.QMessageBox.about(self, "Warning", "File not found, Please check your file path.") return try: self.run.raw_client.upload_from(Path(self.clientPath)) self.run.raw_lab.upload_from(Path(self.labPath)) self.parent.runModel.initialiseTable(data=getRunsTableData(Job[self.parent._selectedCalNum][self.parent._selectedEquipID])) self.parent.runModel.layoutChanged.emit() # Finish add new run and quit self.hide() self.equip = None self.clientPath = "" self.labPath = "" self.ui.clientFilePathLine.clear() self.ui.labFilePathLine.clear() except PermissionError: QtWidgets.QMessageBox.about(self, "Warning", "Cannot re-upload files. Please close correpsonding file windows!") def setRuns(self, selectedRun, run): logger.debug("Selected RunID: %s", selectedRun) self.selectedRun = selectedRun self.run = run class HomeImportWindow(QMainWindow): def __init__(self, parent = None): super(HomeImportWindow, self).__init__(parent) self.parent = parent # load import page ui # window = loadUI(".\\app\\gui\\import_page.ui", self) #window = loadUI("./app/gui/import_page.ui", self) window = loadUI(':/ui/import_page.ui', self) self.ui = window self.confirmWindow = ConfirmWindow(self) self.data = Header_data() self.clientPath = self.ui.clientFilePathLine.text() self.labPath = self.ui.labFilePathLine.text() self.ui.clientFilePathLine.textChanged.connect(self.sync_clientLineEdit) self.ui.labFilePathLine.textChanged.connect(self.sync_labLineEdit) # link buttons to actions self.importClientFilebutton.clicked.connect(self.chooseRawClient) self.importLabFileButton.clicked.connect(self.chooseRawLab) self.importSubmitButton.clicked.connect(self.submit) self.clientOpenFile.clicked.connect(self.openClientFile) self.labOpenFile.clicked.connect(self.openLabFile) self.confirmWindow.confirmButton.clicked.connect(self.addNewRun) self.confirmWindow.quitButton.clicked.connect(self.confirmWindow.close) def sync_clientLineEdit(self): self.clientPath = self.ui.clientFilePathLine.text() def sync_labLineEdit(self): self.labPath = self.ui.labFilePathLine.text() def chooseRawClient(self): file_filter = 'Raw Data File (*.csv)' self.clientPath = QFileDialog.getOpenFileName( parent = self, caption = 'Please Select Client Raw File', directory = os.getcwd(), filter = file_filter, initialFilter = 'Raw Data File (*.csv)' )[0] logger.debug("Client raw file: %s", self.clientPath) self.ui.clientFilePathLine.setText(self.clientPath) def chooseRawLab(self): file_filter = 'Raw Data File (*.csv)' self.labPath = QFileDialog.getOpenFileName( parent = self, caption = 'Please Select Lab Raw File', directory = os.getcwd(), filter = file_filter, initialFilter = 'Raw Data File (*.csv)' )[0] logger.debug("Lab raw file: %s", self.labPath) self.ui.labFilePathLine.setText(self.labPath) def submit(self): # file path check if self.clientPath.strip() == "" or self.labPath.strip() == "": QtWidgets.QMessageBox.about(self, "Warning", "Please fill in both client file and lab file path.") return if (not os.path.isfile(self.clientPath)) or (not os.path.isfile(self.labPath)): QtWidgets.QMessageBox.about(self, "Warning", "File not found, Please check your file path.") return # resolve header data from file try: self.data = extractionHeader(self.clientPath, self.labPath) except HeaderError as e: QtWidgets.QMessageBox.about(self, "Warning", "".join(list(e.args))) return # pop up confirm page self.confirmWindow.calNumLine.setText(self.data.CAL_num) self.confirmWindow.clientNameLine.setText(self.data.Client_name) self.confirmWindow.clientAddress1Line.setText(self.data.address_1) self.confirmWindow.clientAddress2Line.setText(self.data.address_2) self.confirmWindow.chamberLine.setText(self.data.model+" "+self.data.serial) self.confirmWindow.operatorLine.setText(self.data.operator) self.confirmWindow.measurementLine.setText(self.data.date) self.confirmWindow.setFixedSize(800, 560) # self.confirmWindow.setWindowModality(Qt.ApplicationModal) self.confirmWindow.show() def addNewRun(self): # prepare update tables self.parent.clientModel.layoutAboutToBeChanged.emit() self.parent.equipmentModel.layoutAboutToBeChanged.emit() self.parent.runModel.layoutAboutToBeChanged.emit() jobsID = [] for job in Job: jobsID.append(job.id) if not self.data.CAL_num in jobsID: # if job not exsited, create job, equip and add one run job = Job.make(self.data.CAL_num, client_name = self.data.Client_name, client_address_1 = self.data.address_1, client_address_2 = self.data.address_2) newClient = { 'CAL Number': self.data.CAL_num, 'Client Name': self.data.Client_name, } # TODO: fix ValueError bug try: self.parent.clientModel.addData(pd.DataFrame(newClient, index=[0]) ) except ValueError: pass self.parent.clientModel.layoutChanged.emit() equip = job.add_equipment(model = self.data.model, serial = self.data.serial) newEquip = { 'Make/Model': self.data.model, 'Serial Num': self.data.serial, 'ID': equip.id, } # TODO: fix ValueError bug try: self.parent.equipmentModel.addData(pd.DataFrame(newEquip, index=[0]) ) except ValueError: pass self.parent.equipmentModel.layoutChanged.emit() run = equip.mex.add() run.raw_client.upload_from(Path(self.clientPath)) run.raw_lab.upload_from(Path(self.labPath)) error = equip.check_consistency() if error: run.delete() QErrorMessage(self).showMessage(error) return data = { 'ID': run.id, # 'Added Time': converTimeFormat(run.added_at), 'Edited Time': converTimeFormat(run.edited_at), 'Measurement Date': converTimeFormat(run.measured_at).split()[0], 'Operator': run.operator, } # TODO: fix ValueError bug try: self.parent.runModel.addData(pd.DataFrame(data, index=[0])) except ValueError: pass self.parent.runModel.layoutChanged.emit() else: job = Job[self.data.CAL_num] equipsID = [] for equip in job: equipsID.append(equip.id) equipId = self.data.model+' '+self.data.serial if not equipId in equipsID: # if equip not existed, create equip then add run equip = job.add_equipment(model = self.data.model, serial = self.data.serial) newEquip = { 'Make/Model': self.data.model, 'Serial Num': self.data.serial, 'ID': equip.id, } # TODO: fix ValueError bug try: self.parent.equipmentModel.addData(pd.DataFrame(newEquip, index=[0]) ) except ValueError: pass self.parent.equipmentModel.layoutChanged.emit() run = equip.mex.add() run.raw_client.upload_from(Path(self.clientPath)) run.raw_lab.upload_from(Path(self.labPath)) error = equip.check_consistency() if error: run.delete() QErrorMessage(self).showMessage(error) return data = { 'ID': run.id, # 'Added Time': converTimeFormat(run.added_at), 'Edited Time': converTimeFormat(run.edited_at), 'Measurement Date': converTimeFormat(run.measured_at).split()[0], 'Operator': run.operator, } # TODO: fix ValueError bug try: self.parent.runModel.addData(pd.DataFrame(data, index=[0])) except ValueError: pass self.parent.runModel.layoutChanged.emit() else: # if both job and equip existed, add run to it equip = Job[self.data.CAL_num][equipId] run = equip.mex.add() run.raw_client.upload_from(Path(self.clientPath)) run.raw_lab.upload_from(Path(self.labPath)) error = equip.check_consistency() if error: run.delete() QErrorMessage(self).showMessage(error) return data = { 'ID': run.id, # 'Added Time': converTimeFormat(run.added_at), 'Edited Time': converTimeFormat(run.edited_at), 'Measurement Date': converTimeFormat(run.measured_at).split()[0], 'Operator': run.operator, } # TODO: fix ValueError bug try: self.parent.runModel.addData(pd.DataFrame(data, index=[0])) except ValueError: pass self.parent.runModel.layoutChanged.emit() # pop up message when import successfully QtWidgets.QMessageBox.about(self, "Notification", "File imported successfully!") # Finish add new run and quit self.hide() self.confirmWindow.close() self.clientPath = "" self.labPath = "" self.ui.clientFilePathLine.clear() self.ui.labFilePathLine.clear() def openClientFile(self): if not os.path.isfile(self.clientPath): QtWidgets.QMessageBox.about(self, "Warning", "Client file not found, Please check your file path.") return if self.clientPath != "": try: os.startfile(self.clientPath) except FileNotFoundError: QtWidgets.QMessageBox.about(self, "Warning", "File not found, Please check your path.") def openLabFile(self): if not os.path.isfile(self.labPath): QtWidgets.QMessageBox.about(self, "Warning", "Lab file not found, Please check your file path.") return if self.clientPath != "": try: os.startfile(self.labPath) except FileNotFoundError: QtWidgets.QMessageBox.about(self, "Warning", "File not found, Please check your path.") def closeEvent(self, event): if len(self.ui.clientFilePathLine.text()) != 0 or len(self.ui.labFilePathLine.text()) != 0: reply = QtWidgets.QMessageBox.question(self, u'Warning', u'Close window? \nAll inputs will be clear.', QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: self.ui.clientFilePathLine.clear() self.ui.labFilePathLine.clear() event.accept() else: event.ignore() else: event.accept() class ConfirmWindow(QMainWindow): def __init__(self, parent = None): super(ConfirmWindow, self).__init__(parent) # load constants page ui self.ui = loadUI(':/ui/run_info.ui', self) class ConstantsWindow(QMainWindow): def __init__(self, parent = None): super(ConstantsWindow, self).__init__(parent) self.parent = parent # load constants page ui self.ui = loadUI(':/ui/constants_page.ui', self) # initialize label if constant_file_config.default_id: self.ui.idLabel.setText(constant_file_config.default_id) else: self.ui.idLabel.setText("Template") # Templete constants file path try: base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") self.templete_path = os.path.join(base_path, 'constant.xlsx') # Table insertion self.ui.constantsTable.horizontalHeader().setStyleSheet("QHeaderView { font-size: 12pt; font-family: Verdana; font-weight: bold; }") self.constantModel = TableModel(data=pd.DataFrame([]), editable=True) self.constant_sortermodel = QSortFilterProxyModel() self.constant_sortermodel.setSourceModel(self.constantModel) self.ui.constantsTable.setModel(self.constant_sortermodel) self.ui.constantsTable.setSortingEnabled(True) self.ui.constantsTable.sortByColumn(1, Qt.AscendingOrder) self.ui.constantsTable.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) self.ui.constantsTable.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection) self.ui.constantsTable.selectionModel().selectionChanged.connect(lambda: self.selection_changed()) self.ui.constantsTable.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.ui.constantsTable.setItemDelegate(AlignDelegate()) self.ui.constantsTable.setColumnHidden(2, True) #?? self._selectedSourceIndex = None self._selectedConstantsID = "" # Context menu self.ui.constantsTable.customContextMenuRequested.connect(self.showContextMenu) # link buttons to function # self.openButton.clicked.connect(self.openDefaultConstantsFile) self.defaultButton.clicked.connect(self.setDefault) self.createButton.clicked.connect(self.create) self.deleteButton.clicked.connect(self.delete) # link table raw to double click # self.ui.constantsTable.doubleClicked.connect(self.openConstantsFile) # initiallize table self.constantModel.layoutAboutToBeChanged.emit() self.constantModel.initialiseTable(data=getConstantsTableData()) self.constantModel.layoutChanged.emit() self.constantModel.dataChanged.connect(self.onDescriptionChanged) def onDescriptionChanged(self, tLeft, bRight): if self._selectedConstantsID == "Template": return logger.debug(self.constantModel._data.iloc[tLeft.row(), tLeft.column()]) ConstantFile[self._selectedConstantsID].note = self.constantModel._data.iloc[tLeft.row(), tLeft.column()] def showContextMenu(self): self.ui.constantsTable.contextMenu = QtWidgets.QMenu(self) self.ui.constantsTable.contextMenu.setStyleSheet(""" QMenu:selected {background-color: #ddf; color: #000;} """ ) def add_action(name, handler): action = self.ui.constantsTable.contextMenu.addAction(name) action.triggered.connect(lambda: self.actionHandler(handler)) add_action('Open constant.xlsx', "OpenConstantFile") self.ui.constantsTable.contextMenu.popup(QtGui.QCursor.pos()) # Menu position based on cursor self.ui.constantsTable.contextMenu.show() def actionHandler(self, action): logger.debug("Open menu") if action == "OpenConstantFile": self.openConstantsFile() def openDefaultConstantsFile(self): try: os.startfile(constant_file_config.get_path()) except FileNotFoundError: QtWidgets.QMessageBox.about(self, "Warning", "No constants file, Please check your path.") def openConstantsFile(self): if self._selectedConstantsID == "Template": os.startfile(self.templete_path) else: try: os.startfile(ConstantFile[self._selectedConstantsID].path) except FileNotFoundError: QtWidgets.QMessageBox.about(self, "Warning", "No constants file, Please check your path.") def setDefault(self): # check if chose one row if self._selectedConstantsID == "": QtWidgets.QMessageBox.about(self, "Warning", "Please choose a constants.") return # check if choosing template row if self._selectedConstantsID == "Template": del constant_file_config.default_id self.ui.idLabel.setText("Template") return # set default constants file constant_file_config.default_id = ConstantFile[self._selectedConstantsID].id # refresh display self.ui.idLabel.setText(constant_file_config.default_id) def create(self): # create constants ConstantFile.make() # refresh table self.constantModel.layoutAboutToBeChanged.emit() self.constantModel.initialiseTable(data=getConstantsTableData()) self.constantModel.layoutChanged.emit() def delete(self): # check if chose one row if self._selectedConstantsID == "": QtWidgets.QMessageBox.about(self, "Warning", "Please choose a constants.") return # check if choosing template row if self._selectedConstantsID == "Template": QtWidgets.QMessageBox.about(self, "Warning", "Sorry, template constants can not be deleted.") return #pop up confirm window if str(self._selectedConstantsID) == constant_file_config.default_id: reply = QtWidgets.QMessageBox.question(self, u'Warning', u'You are deleting currently selected file. \nAre you sure you want to proceed? \nAfter deletion, selected file will be set as DEFAULT. ', QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) else: reply = QtWidgets.QMessageBox.question(self, u'Warning', u'Do you want delete this constants file?', QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: # delete chosen constants try: ConstantFile[self._selectedConstantsID].delete() except PermissionError: QtWidgets.QMessageBox.about(self, "Warning", "Please close the constants file first.") return # refresh table self.constantModel.layoutAboutToBeChanged.emit() self.constantModel.initialiseTable(data=getConstantsTableData()) self.constantModel.layoutChanged.emit() self.ui.constantsTable.clearSelection() # refresh display if constant_file_config.default_id: self.ui.idLabel.setText(constant_file_config.default_id) else: self.ui.idLabel.setText("DEFAULT") else: self.ui.constantsTable.clearSelection() return def selection_changed(self): """ Return the index of selected rows in an array. """ modelIndex =self.ui.constantsTable.selectionModel().selectedRows() # QModelIndexList self._selectedRows = [idx.row() for idx in modelIndex] self.ui.constantsTable.setContextMenuPolicy(Qt.PreventContextMenu) logger.debug(self._selectedRows) if len(self._selectedRows) > 0: self.ui.constantsTable.setContextMenuPolicy(Qt.CustomContextMenu) source_selectedIndex = [self.constant_sortermodel.mapToSource(modelIndex[0]).row()] logger.debug(source_selectedIndex) self._selectedConstantsID = self.constantModel._data.loc[source_selectedIndex, 'ID'].to_list()[0] self._selectedSourceIndex = source_selectedIndex elif len(self._selectedRows) == 0: self._selectedConstantsID = "" class AnalyseWindow(QMainWindow): def __init__(self, parent = None): super(AnalyseWindow, self).__init__(parent) # load analyse page ui # window = loadUI(".\\app\\gui\\analyse_page.ui", self) #window = loadUI("./app/gui/analyse_page.ui", self) window = loadUI(':/ui/analyse_page.ui', self) self.ui = window self._selectedRows = [] self.runs = [] self.tabTables = [] self.lastClicked = [] self.color = ['b', 'c', 'r', 'm', 'k', 'y'] self.summay = None self.constant = None self.parent = parent ## Table and Graph insertion # self.ui.resultGraph # self.ui.run1Table # self.ui.run2Table (This should be dynamic) # self.ui.resultTable # Result Table self.ui.resultTable.horizontalHeader().setStyleSheet("QHeaderView { font-size: 12pt; font-family: Verdana; font-weight: bold; }") self.resultModel = TableModel(pd.DataFrame()) self.ui.resultTable.setModel(self.resultModel) self.ui.resultTable.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection) # self.ui.resultTable.selectionModel().selectionChanged.connect(lambda: self.selection_changed('resultTable')) self.ui.resultTable.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) self.ui.resultTable.setItemDelegate(AlignDelegate()) # text alignment # Graph self.ui.resultGraph.setBackground(background=None) self.plot_item = self.ui.resultGraph.addPlot() self.plot_item.setLabel('bottom', "Effective Energy (keV)") self.plot_item.setLabel('left', "Calibration Factor (mGy/nc)") self.plot_item.addLegend(offset=(-30, 30)) self.plot_item.showGrid(y=True) self.plot_item.setMenuEnabled(False) # logger.debug(self.ui.tabWidget.count()) self.ui.generatePdfButton.clicked.connect(self.generate_pdf) def setRuns(self, runs): self.runs = runs result_list = [] name_list = [] self.resultModel.layoutAboutToBeChanged.emit() for run in runs: # get Leakage Current Data of each run # get data from resolver result = calculator(run.raw_client.path, run.raw_lab.path) result_list.append(result) self.tabTables.append(result.df_leakage) self.leakageCurrentModel = TableModel(result.df_leakage, set_bg=True, bg_index=result.highlight) self.tabTable = QTableView() self.tabTable.horizontalHeader().setStyleSheet("QHeaderView { font-size: 8pt; font-family: Verdana; font-weight: bold; }") self.tabTable.setModel(self.leakageCurrentModel) self.tabTable.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.ui.tabWidget.addTab(self.tabTable, "Run "+str(run.id)) name_list.append("Run "+str(run.id)) self.tabTable.setItemDelegate(AlignDelegate()) # text alignment # Draw graph self.plot_item.addItem(self.plot(result.X['E_eff'].tolist(), result.df_NK['NK'].tolist(), color=self.color[run.id % len(self.color) - 1], runId=run.id)) self.constant = result_list[0].df_otherConstant self.summay = summary(name_list, result_list) self.resultModel.initialiseTable(data=self.summay) self.resultModel.layoutChanged.emit() def plot(self, x, y, color, runId): scatter_item = pg.ScatterPlotItem( size=8, pen=pg.mkPen(None), brush=pg.mkBrush(color), symbol='s', hoverable=True, hoverSymbol='s', hoverSize=12, hoverPen=pg.mkPen('r', width=2), hoverBrush=pg.mkBrush('g'), name="Run " + str(runId), # tip='This is a test'.format tip='x: {x:.3g}\ny: {y:.3g}'.format ) scatter_item.addPoints( x=np.array(x), y=np.array(y) # size=(np.random.random(n) * 20.).astype(int), # brush=[pg.mkBrush(x) for x in np.random.randint(0, 256, (n, 3))], # data=np.arange(n) ) # scatter_item.sigClicked.connect(self.clicked) # scatter_item.sigHovered.connect(self.hovered) return scatter_item # def clicked(self, plot, points): # for p in self.lastClicked: # p.resetPen() # print("clicked points", points) # for point in points: # print(33333333) # point.setPen(pg.mkPen('b', width=2)) # self.lastClicked = points # def hovered(self, plot, points): # if points: # print(points[0].viewPos()) def generate_pdf(self): # QtWidgets.QMessageBox.about(self, "Generating PDF...") try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") # dir_path = os.path.dirname(os.path.realpath(__file__)) info_dict = self.gather_info() file_name, _ = QFileDialog.getSaveFileName(self, 'Save PDF Report', info_dict["cal_num"] + " MEX " + info_dict["model"] + " sn " + info_dict["serial"], "PDF file (*.pdf)") logger.debug(file_name) if file_name: pool = QThreadPool.globalInstance() workerSignals = ProgressWorkerSignals() worker = PdfWorker(file_name, info_dict, workerSignals, self.summay, self.constant) ticker = ProgressBarCounter(workerSignals) progressBar = ProgressBar(self, workerSignals) pool.start(worker) pool.start(ticker) # QtWidgets.QMessageBox.about(self, "Finish!") # workerSignals.finished.connect(lambda: self.export_pdf(temp_folder)) def gather_info(self): date_list = [] ic_hv = [] equipmentID = self.parent._selectedEquipID cal_num = self.parent._selectedCalNum client_name = Job[cal_num].client_name first_address = Job[cal_num].client_address_1 second_address = Job[cal_num].client_address_2 serial = Job[cal_num][equipmentID].serial model = Job[cal_num][equipmentID].model # Only first operator is considered operator = self.runs[0].operator for run in self.runs: date_list.append(dateutil.parser.isoparse(run.measured_at)) ic_hv.append(run.IC_HV) earliest_date = min(date_list).strftime("%d %b %Y") latest_date = max(date_list).strftime("%d %b %Y") period = earliest_date + " to " + latest_date report_date = datetime.today().strftime("%d %b %Y") ichv = ic_hv[0] if int(ichv) < 0: flag = "Positive " + "(Central Electrode Negative)" else: flag = "Negative " + "(Central Electrode Positive)" return deepcopy({"cal_num": cal_num, "client_name": client_name, "address1": first_address, "address2": second_address, "model": model, "serial": serial, "operator": operator, "period": period, "report_date": report_date, "ic_hv": str(ichv) + ' V' + " on the guard electrode", "polarity": flag }) def closeEvent(self, event): self.__init__(self.parent) event.accept() class AddClientWindow(QMainWindow): def __init__(self, parent = None): super(AddClientWindow, self).__init__(parent) self.parent = parent # load add client page ui # window = loadUI(".\\app\\gui\\add_client_page.ui", self) #window = loadUI("./app/gui/add_client_page.ui", self) window = loadUI(':/ui/add_client_page.ui', self) self.ui = window self.clientName = "" self.clientAddress1 = "" self.clientAddress2 = "" self.calNumber = "" self.clientSubmitButton.clicked.connect(self.addNewClient) def closeEvent(self, event): if len(self.ui.calNumLine.text()) != 0 or len(self.ui.clientNameLine.text()) != 0 or len(self.ui.clientAddress1Line.text()) != 0 or len(self.ui.clientAddress2Line.text()) != 0: reply = QtWidgets.QMessageBox.question(self, u'Warning', u'Close window? \nAll inputs will be clear.', QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: self.ui.calNumLine.clear() self.ui.clientNameLine.clear() self.ui.clientAddress1Line.clear() self.ui.clientAddress2Line.clear() event.accept() else: event.ignore() else: event.accept() def getNewClientInfo(self): newClient = { 'CAL Number': self.calNumber, 'Client Name': self.clientName } return pd.DataFrame(newClient, index=[0]) def addNewClient(self): self.parent.clientModel.layoutAboutToBeChanged.emit() self.parent.ui.homeTable.clearSelection() self.calNumber = self.ui.calNumLine.text() self.clientName = self.ui.clientNameLine.text() self.clientAddress1 = self.ui.clientAddress1Line.text() self.clientAddress2 = self.ui.clientAddress2Line.text() # Check duplicated ID # IDs = getHomeTableData()['CAL Number'].values.tolist() # if self.calNumber in IDs: # QtWidgets.QMessageBox.about(self, "Warning", "CAL number already existed in file system!") # return # Check calNumber and clientName are not empty if len(self.calNumber)==0 or len(self.clientName)==0: QtWidgets.QMessageBox.about(self, "Warning", "Please fill in CAL Number and Client Name!") return try: Job.make(self.calNumber, client_name = self.clientName, client_address_1 = self.clientAddress1, client_address_2 = self.clientAddress2) except ValueError: QtWidgets.QMessageBox.about(self, "Warning", "CAL number already existed in file system!") return self.parent.clientModel.addData(self.getNewClientInfo()) self.parent.clientModel.layoutChanged.emit() # Finish add new client and quit self.hide() self.clientName = "" self.clientAddress1 = "" self.clientAddress2 = "" self.calNumber = "" self.ui.calNumLine.clear() self.ui.clientNameLine.clear() self.ui.clientAddress1Line.clear() self.ui.clientAddress2Line.clear() # TODO: Display another window to confirm information class AddEquipmentWindow(QMainWindow): def __init__(self, parent = None): super(AddEquipmentWindow, self).__init__(parent) self.parent = parent # load add equipment page ui # window = loadUI(".\\app\\gui\\add_equipment_page.ui", self) #window = loadUI("./app/gui/add_equipment_page.ui", self) window = loadUI(':/ui/add_equipment_page.ui', self) self.ui = window self.model = "" self.serial = "" self.id = "" self.job = None self.equipmentSubmitButton.clicked.connect(self.addNewEquip) def getNewEquipInfo(self): newEquip = { 'Make/Model': self.model, 'Serial Num': self.serial, 'ID': self.id, } return pd.DataFrame(newEquip, index=[0]) def addNewEquip(self): self.parent.equipmentModel.layoutAboutToBeChanged.emit() self.model = self.ui.modelLine.text() self.serial = self.ui.serialLine.text() # TODO: Check duplicated ID if len(self.model)==0 or len(self.serial)==0: QtWidgets.QMessageBox.about(self, "Warning", "Please fill in Make/Model and Serial!") return try: equip = self.job.add_equipment(model = self.model, serial = self.serial) except ValueError: QtWidgets.QMessageBox.about(self, "Warning", "Equipment already existed in the Job!") return self.id = equip.id self.parent.equipmentModel.addData(self.getNewEquipInfo()) self.parent.equipmentModel.layoutChanged.emit() # Finish add new equipment and quit self.hide() self.model = "" self.serial = "" self.id = "" self.job = None self.ui.modelLine.clear() self.ui.serialLine.clear() # TODO: Display another window to confirm information def closeEvent(self, event): if len(self.ui.modelLine.text()) != 0 or len(self.ui.serialLine.text()) != 0: reply = QtWidgets.QMessageBox.question(self, u'Warning', u'Close window? \nAll inputs will be clear.', QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: self.ui.modelLine.clear() self.ui.serialLine.clear() event.accept() else: event.ignore() else: event.accept() class TableModel(QAbstractTableModel): def __init__(self, data, set_bg = False, bg_index=None, editable=False): super(TableModel, self).__init__() self._data = data # May be required to change logic # if data.empty is False: # self._display = data.drop(labels=['Address'], axis=1) self._bg = set_bg self._bgCellIdx = bg_index self._editable = editable def data(self, index, role): if role == Qt.DisplayRole or role == Qt.EditRole: # Address is at the end of columns # if index.column() != self.columnNum - 1: value = self._data.iloc[index.row(), index.column()] return str(value) if role == Qt.BackgroundRole: if self._bg and (index.row(), index.column()) in self._bgCellIdx: return QtGui.QColor('yellow') def rowCount(self, index=None): return self._data.shape[0] def columnCount(self, index=None): return self._data.shape[1] def headerData(self, section, orientation, role): # section is the index of the column/row. if role == Qt.DisplayRole: if orientation == Qt.Horizontal: return str(self._data.columns[section]) if orientation == Qt.Vertical: return str(self._data.index[section]) def addData(self, newData): if newData.empty is False: self._data = self._data.convert_dtypes() self._data = self._data.append(newData, ignore_index=True) else: pass def delData(self, idx): if idx: self._data = self._data.drop(idx) self._data.reset_index(drop=True, inplace=True) logger.debug(self._data) else: pass def setData(self, index, value, role): if role == Qt.EditRole and self._editable: self._data.iloc[index.row(), index.column()] = value self.dataChanged.emit(index, index, (Qt.DisplayRole, )) return True return False def initialiseTable(self, data): self._data = data def setHeaderData(self, section, orientation, data, role=Qt.EditRole): if orientation == Qt.Horizontal and role in (Qt.DisplayRole, Qt.EditRole): try: self.horizontalHeaders[section] = data return True except: return False return super().setHeaderData(section, orientation, data, role) def isTableEmpty(self): return self._data.empty def flags(self, index): if self._editable and index.column() == 2: return Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable else: return Qt.ItemIsSelectable | Qt.ItemIsEnabled # def removeRows(self, position, rows=1, index=QModelIndex()): # self.beginRemoveRows(QModelIndex(), position, position + rows - 1) # # logger.debug("Drop") # # logger.debug(self._data.drop(position)) # self._data = self._data.drop(position) # self._data.reset_index(drop=True, inplace=True) # self.endRemoveRows() # return True ''' https://stackoverflow.com/questions/28218882/how-to-insert-and-remove-row-from-model-linked-to-qtablevie ''' # def insertRows(self, position, rows=1, index=QModelIndex()): # indexSelected=self.index(position, 0) # itemSelected=indexSelected.data().toPyObject() # self.beginInsertRows(QModelIndex(), position, position + rows - 1) # for row in range(rows): # self.items.insert(position + row, "%s_%s"% (itemSelected, self.added)) # self.added+=1 # self.endInsertRows() # return True class AlignDelegate(QItemDelegate): def paint(self, painter, option, index): option.displayAlignment = Qt.AlignCenter QItemDelegate.paint(self, painter, option, index) class ProgressWorkerSignals(QObject): progress = pyqtSignal(int) finished = pyqtSignal() class ProgressBarCounter(QRunnable): """ Runs a counter thread. """ def __init__(self, signals: ProgressWorkerSignals): super().__init__() self._signals = signals self._stop = False signals.finished.connect(self.stop) def run(self): count = 0 while count < 100 and not self._stop: count += 5 time.sleep(1) self._signals.progress.emit(count) def stop(self): self._stop = True class PdfWorker(QRunnable): """ A thread to handle pdf generation """ def __init__(self, path, info_dict, signals: ProgressWorkerSignals, summary, constant) -> None: super().__init__() self._info_dict = info_dict self._signals = signals self._path = path self.summary = summary self.constant = constant def run(self): temp_folder = tempfile.mkdtemp(dir=DATA_FOLDER.absolute()) logger.debug(temp_folder) pdf_visualization(temp_folder, self.summary, self.constant) pdf = get_pdf(temp_folder, **self._info_dict) shutil.copyfile(pdf, self._path) try: logger.debug('Cleaning temporary folder...') shutil.rmtree(temp_folder) except OSError as e: print ("Error: %s - %s." % (e.filename, e.strerror)) self._signals.finished.emit() class ProgressBar(QDialog): """ Simple dialog that consists of a Progress Bar. """ def __init__(self, parent, signals: ProgressWorkerSignals): super().__init__(parent) self.setWindowTitle('Generating PDF...') self.progress = QProgressBar(self) self.progress.setGeometry(0, 0, 300, 25) self.progress.setMaximum(100) # self.button = QPushButton('Finish', self) # self.button.move(0, 30) # self.button.clicked.connect(self.onFinishButtonClick) # self.button.setVisible(False) signals.finished.connect(self.onProgressFinish) signals.progress.connect(self.onProgressChanged) self.setWindowModality(Qt.ApplicationModal) self.setWindowFlag(QtCore.Qt.WindowCloseButtonHint, False) # self.setWindowFlag(QtCore.Qt.WindowTitleHint, False) # self.setWindowFlag(QtCore.Qt.WindowSystemMenuHint, False) self.setWindowFlag(QtCore.Qt.WindowContextHelpButtonHint, False) self.show() def onProgressChanged(self, value): self.progress.setValue(value) def onProgressFinish(self): self.accept() def start_event_loop(): # os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1" # sys.argv += ['--style', 'fusion'] app = QApplication(sys.argv) app.setWindowIcon(QtGui.QIcon(':/icons/app.ico')) mainWindow = MainWindow() mainWindow.show() return app.exec_() if __name__ == '__main__': ret = start_event_loop() sys.exit(ret)<file_sep>/gui_testing/utils.py """ The class is a supplementary tool to the PYAutoGUI to automate the GUI testing. The purpose is to move the mouse to the UI element location based on its text. PyAutoGUI currently can be used only on the main screen, where the start point is set to be the top-left corner as (0,0). Note that the application window might scale to different size PyAutoGUI: https://pyautogui.readthedocs.io/en/latest/ """ import pandas as pd import ast import easyocr import pyautogui as pq import os # the parameters could be various depends on the device # adjust the value to fit the screen # (left, top), start point APP_START_X = 471 APP_START_Y = 108 ANA_START_X = 296 ANA_START_Y = 43 SAVE_START_X = 306 SAVE_START_Y = 85 # use the current directory, where the script exists CWD = os.path.dirname(os.path.realpath(__file__)) class UI: """ The UI class parse the CSV file to turn the data into a dictionary. The data is generated using the libaray easy_ocr to scrape the texts on the image. Please see the README.md in the scrape folder. """ def __init__(self, data, index): """ The class takes the CSV file and the desired column as index """ self.df = pd.DataFrame(pd.read_csv(data, index_col=index)) # change the string to a list self.df['pos'] = self.df['pos'].apply(lambda s: list(ast.literal_eval((s)))) self.dict = self.df.to_dict() self.__APP_START_X = APP_START_X self.__APP_START_Y = APP_START_Y self.__ANA_START_X = ANA_START_X self.__ANA_START_Y = ANA_START_Y self.__SAVE_START_X = SAVE_START_X self.__SAVE_START_Y = SAVE_START_Y def get_pos(self, button_name, window): """ The function generates the start point of the UI element. The button_name is in the data folder. :param: str button_name: The UI element text :param: str window: app, analysis, save """ # the position is based on the screenshots # the bounding box of the easyocr: (tl, tr, br, bl) ui_start_x = self.dict['pos'][button_name][0][0] ui_start_y = self.dict['pos'][button_name][0][1] if window == "app": # adjust the position to the actual position on the screen ui_start_x_real = ui_start_x + self.__APP_START_X ui_start_y_real = ui_start_y + self.__APP_START_Y return ui_start_x_real, ui_start_y_real elif window == "analysis": ui_start_x_real = ui_start_x + self.__ANA_START_X ui_start_y_real = ui_start_y + self.__ANA_START_Y return ui_start_x_real, ui_start_y_real elif window == "save": ui_start_x_real = ui_start_x + self.__SAVE_START_X ui_start_y_real = ui_start_y + self.__SAVE_START_Y return ui_start_x_real, ui_start_y_real def get_text(image): """ Get the image text from the temp_screenshots folder and save the CSV information in the temp_data. """ reader = easyocr.Reader(['en']) # be able to use CUDA, much faster than CPU allow_list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ' result = reader.readtext(f'../temp_screenshots/{image}.png', detail=1, allowlist = allow_list) df = pd.DataFrame(result) df.columns = ['pos', 'string', 'confidence'] df.to_csv(f'../temp_data/{image}.csv', index=False) def get_string_list(ui_obj): """ Return the screenshot text into a list. """ return pd.Series(ui_obj.df.index.values).tolist() def screenshot_app_window(name, start_x=APP_START_X, start_y=APP_START_Y, end_x=1446, end_y=888): """ Default to screenshot the homepage. """ pq.screenshot( os.path.join(CWD,'temp_screenshots', f'{name}.png'), region=(start_x, start_y, (end_x-start_x), (end_y-start_y)) )<file_sep>/data/jobs/CAL00001/PTW 30013 5122/MEX/1/meta.ini [DEFAULT] added_at = 2021-10-05T20:51:21+08:00 edited_at = 2021-10-05T20:51:21+08:00 measured_at = 2021-02-12 ic_hv = -250 operator = <NAME> <file_sep>/data/jobs/CAL00004/PTW 30013 6533/MEX/2/meta.ini [DEFAULT] added_at = 2021-10-05T20:54:44+08:00 edited_at = 2021-10-05T20:54:44+08:00 measured_at = 2020-12-09 ic_hv = -360 <file_sep>/app/export/pdf.py import logging import os import xlwings as xw import sys import pandas as pd import numpy as np import pythoncom import win32com.client from pywintypes import com_error import shutil logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) figure_width = 450 figure_height = 450 def get_pdf(temp_folder, **kwgs): pythoncom.CoInitialize() try: base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") templateFilePath = os.path.join(base_path, 'app', 'export', 'pdf_template.xlsx') tablePath = os.path.join(temp_folder, 'pdf_table.xlsx') hvl_al_fig = os.path.join(temp_folder, 'HVL_Al.png') hvl_cu_fig = os.path.join(temp_folder, 'HVL_Cu.png') kvp_fig = os.path.join(temp_folder, 'kVp.png') doc_path = os.path.join(temp_folder, 'document.xlsx') shutil.copy(templateFilePath, doc_path) try: subtable_df = pd.read_excel(tablePath, sheet_name='subset', engine='openpyxl') total1_df = pd.read_excel(tablePath, sheet_name='total-1', engine='openpyxl') total2_df = pd.read_excel(tablePath, sheet_name='total-2', engine='openpyxl') except: logger.debug("Cannot read table file properly!") logger.debug(kwgs) app = xw.App(visible = False) wb = xw.Book(doc_path) #excel template file path sheet = wb.sheets['MEXReport'] sheet.range('T12').value = kwgs["cal_num"] #CAL NUMBER sheet.range('G19').value = kwgs["client_name"] #Client Name sheet.range('G111').value = kwgs["client_name"] #Client Name sheet.range('L145').value = "Calibrated by: " + kwgs["client_name"] #Client Name ##### sheet.range('G20').value = kwgs["address1"] # Address 1 sheet.range('G21').value = kwgs["address2"] # Address 2 sheet.range('G24').value = kwgs["model"] + ' ' + kwgs["serial"] # Chamber Information sheet.range('G112').value = kwgs["model"] + ' ' + kwgs["serial"] # Chamber Information sheet.range('G26').value = kwgs["period"] #Date of Measurement: Option -> 2-6 July 2021 or Option 2-> 2 July 2021 to 6 July 2021 sheet.range('G124').value = kwgs["period"] #Date of Measurement: Option -> 2-6 July 2021 or Option 2-> 2 July 2021 to 6 July 2021 sheet.range('G30').value = kwgs["operator"] #Name of Operator of latest run sheet.range('G31').value = kwgs["operator"] #Name of Operator of latest run sheet.range('G32').value = kwgs["report_date"] + ' ' #Report generation date/current sheet.range('G113').value = kwgs["ic_hv"] #Client RAW File, IC HV Value sheet.range('G114').value = kwgs["polarity"] #if above is negative, then here is positive #insert table 1 @ Cell A122 or Replace NK value from Q124 to Q134 # sheet.range('Q124:Q134').value = subtable_df["NK [2]"].to_list() sheet.range('A130').options(transpose=True).value = subtable_df["Beam code"].to_list() sheet.range('C130').options(transpose=True).value = subtable_df["Tube voltage"].to_list() sheet.range('E130').options(transpose=True).value = subtable_df["Added filter(mm Al)"].to_list() sheet.range('G130').options(transpose=True).value = subtable_df["Added filter(mm Cu)"].to_list() sheet.range('I130').options(transpose=True).value = subtable_df["HVL(mm Al)"].to_list() sheet.range('K130').options(transpose=True).value = subtable_df["HVL(mm Cu)"].to_list() sheet.range('M130').options(transpose=True).value = subtable_df["Nominal effective energy [1]"].to_list() sheet.range('O130').options(transpose=True).value = subtable_df["Nominal air kerma rate"].to_list() sheet.range('Q130').options(transpose=True).value = subtable_df["NK [2]"].to_list() sheet.range('S130').options(transpose=True).value = subtable_df["U %"].to_list() #insert table 2 @ Cell A145 or Replace NK value from Q147 to Q186 # sheet.range('Q147:Q186').value = total1_df["NK [2]"].to_list() sheet.range('A151').options(transpose=True).value = total1_df["Beam code"].to_list() sheet.range('C151').options(transpose=True).value = total1_df["Tube voltage"].to_list() sheet.range('E151').options(transpose=True).value = total1_df["Added filter(mm Al)"].to_list() sheet.range('G151').options(transpose=True).value = total1_df["Added filter(mm Cu)"].to_list() sheet.range('I151').options(transpose=True).value = total1_df["HVL(mm Al)"].to_list() sheet.range('K151').options(transpose=True).value = total1_df["HVL(mm Cu)"].to_list() sheet.range('M151').options(transpose=True).value = total1_df["Nominal effective energy [1]"].to_list() sheet.range('O151').options(transpose=True).value = total1_df["Nominal air kerma rate"].to_list() sheet.range('Q151').options(transpose=True).value = total1_df["NK [2]"].to_list() sheet.range('S151').options(transpose=True).value = total1_df["U %"].to_list() #insert table 2-A @ Cell A192 or Replace NK value from Q194 to Q215 # sheet.range('Q194:Q215').value = total2_df["NK [2]"].to_list() sheet.range('A199').options(transpose=True).value = total2_df["Beam code"].to_list() sheet.range('C199').options(transpose=True).value = total2_df["Tube voltage"].to_list() sheet.range('E199').options(transpose=True).value = total2_df["Added filter(mm Al)"].to_list() sheet.range('G199').options(transpose=True).value = total2_df["Added filter(mm Cu)"].to_list() sheet.range('I199').options(transpose=True).value = total2_df["HVL(mm Al)"].to_list() sheet.range('K199').options(transpose=True).value = total2_df["HVL(mm Cu)"].to_list() sheet.range('M199').options(transpose=True).value = total2_df["Nominal effective energy [1]"].to_list() sheet.range('O199').options(transpose=True).value = total2_df["Nominal air kerma rate"].to_list() sheet.range('Q199').options(transpose=True).value = total2_df["NK [2]"].to_list() sheet.range('S199').options(transpose=True).value = total2_df["U %"].to_list() #Chart 1: N vs KvP Chart @ Cell A220 sheet.pictures.add(kvp_fig, top=sheet.range('A225').top, left=sheet.range('A220').left, name='kVp', update=True, width=figure_width, height=figure_height) #Chart 1 Title sheet.range('C243').value = "Figure 1: Calibration coefficients for " + kwgs["model"] +" serial number " + kwgs["serial"] + " grouped by kVp" #Chart 2: N vs HVL Chart (mm Al) @ Cell A245 sheet.pictures.add(hvl_al_fig, top=sheet.range('A251').top, left=sheet.range('A245').left, name='Al', update=True, width=figure_width, height=figure_height) #Chart 2 Title sheet.range('C273').value = "Figure 2: Calibration coefficients for " + kwgs["model"] + " serial number " + kwgs["serial"] + " versus HVL (mm Al)" #Chart 3: N vs HVL Chart (mm Cu) @ Cell A272 sheet.pictures.add(hvl_cu_fig, top=sheet.range('A278').top, left=sheet.range('A272').left, name='Cu', update=True, width=figure_width, height=figure_height) #Chart 3 Title sheet.range('C300').value = "Figure 3: Calibration coefficients for " + kwgs["model"] + " serial number " + kwgs["serial"] +" versus HVL (mm Cu)" #Footer Values sheet.range('A59').value = "Calibration No: " + kwgs["cal_num"] #CAL Number sheet.range('I59').value = "Report Date: " + kwgs["report_date"] #CAL Number wb.save(doc_path) wb.close() doc_pdf = os.path.join(temp_folder, 'document.pdf') excel = win32com.client.Dispatch("Excel.Application") try: print('Start conversion to PDF') wb = excel.Workbooks.Open(doc_path) wb_list = [1] wb.Worksheets(wb_list).Select() wb.ActiveSheet.ExportAsFixedFormat(0, doc_pdf) except com_error as e: logger.error('Failed', exc_info=e) finally: wb.Close() return doc_pdf # MacOS doesn't support win32com. # if you're going to test the PDF generation, please use the code below # note that the quality of pictures would get blurred # import comtypes.client # app = comtypes.client.CreateObject('Excel.Application') # app.Visible = False # infile = os.path.join(templateFilePath) # outfile = os.path.join(path, 'ClientReport.pdf') # doc = app.Workbooks.Open(infile) # doc.ExportAsFixedFormat(0, outfile, 1, 0) # doc.Close() # app.Quit() <file_sep>/app/repl.py """ The entry point of repl. You can use this script to directely import models from `core.models` and exporing available apis. The file adds /app as the module search directory, so you can use `import core.models` rather than `import app.core.models` Simple usage guide: # Run the following command through command line prompt under project root to start repl. pipenv run repl # import classes from core.models >>> from core.models import Job # Add `?` after class or methods to view documents >>> Job? Init signature: Job(id: str) -> None Docstring: A model that represents a job. ... # Directely run methods >>> list(Job) [Job(CAL00001), Job(CAL00002), Job(CAL00003), Job(CAL00004), Job(CAL0001)] >>> job = Job['CAL0001'] >>> job.delete? Signature: job.delete() Docstring: Remove the model, this process cannot be undone. ... ``` """ from traitlets.config import Config import sys import os import IPython dir_path = os.path.dirname(os.path.realpath(__file__)) sys.path.append(dir_path) if __name__ == '__main__': c = Config() c.InteractiveShellApp.extensions = [ 'autoreload', ] c.InteractiveShellApp.exec_lines = [ r'%autoreload 2', ] IPython.start_ipython(config=c) <file_sep>/gui_testing/test_US02.py """ The test file need to be run inside the gui_testing directory, with application centered on the (1920,1080) resolution main screen. The test cases are for the system testing, with the tests visulized. The test cases are testing the user story 2, mainly with the functionalities regarding: 1. Checking the information typed by the client 2. Search the CAL_num and client name functionality Note that the opencv is limited to access the information within the text field, which means the tests aren't 100 percent assured. The current way is to screenshot the user input and the equipment page for comparison. """ import unittest import os import shutil from time import sleep import pyautogui as pg import test_US01 # W0311: bad indentation; E1101:no-member; C0325: Unnecessary parens # pylint: disable=W0311, E1101, C0325 # use the current directory, where the script exists CWD = os.path.dirname(os.path.realpath(__file__)) class TestUserStory2(unittest.TestCase): """The user story 2 related system testing Args: unittest ([type]): [The default testing module from Python] """ @classmethod def setUpClass(self): try: folder = os.getcwd() + "\\US02 Fail" shutil.rmtree(folder) except: print("[There's no such directory]") try: folder = os.getcwd() + "\\US02 Success" shutil.rmtree(folder) except: print("[There's no such directory]") try: folder = os.getcwd() + "\\US02" shutil.rmtree(folder) except: print("[There's no such directory]") try: self.cwd = os.getcwd() # for printing the current directory # print(self.cwd) os.mkdir("US02") os.chdir("US02") # cd to the directory for saving screenshots self.storage = '%s/' % os.getcwd() # escape the cwd string except: print("[Something is wrong when creating the directory]") @classmethod def tearDownClass(self): file_list = os.listdir() # print(file_list) # iterate through the filename string, if there's a keyword "fail", rename the folder for filename in file_list: if "fail" in filename: # print("Some tests failed") os.chdir("..") os.rename("US02", "US02 Fail") return os.chdir("..") os.rename("US02", "US02 Success") def test_a_information_correct(self): """Add a client, and check the info on the next page """ try: # The pyautogui doesn't recognize the pop up window -> use the coordination btn_add_new_client = pg.locateOnScreen( os.path.join(CWD, 'screenshot' ,'main_win' ,'add_new_client.png'), grayscale=False, confidence=.9) pg.moveTo(btn_add_new_client) pg.click() except: print("[There's no such button matching the picture]") raise # add a new client try: pg.moveTo(942, 464, 0.5) # cal number pg.click() pg.write("CAL00005") pg.moveTo(942, 502, 0.5) # client name pg.click() pg.write("Alex") pg.moveTo(942, 540, 0.5) # address 1 pg.click() pg.write("Sky island") pg.moveTo(942, 577, 0.5) # address 2 pg.click() pg.write("The treasure cruise") # screenshot client information for checking # client number pg.screenshot( os.path.join(CWD,'screenshot', 'main_win' , 'cal_num.png'), region=(844, 454, (1279-844), (476-454)) ) # client name pg.screenshot( os.path.join(CWD,'screenshot', 'main_win' , 'client_name.png'), region=(844, 493, (1279-844), (512-493)) ) # client address1 pg.screenshot( os.path.join(CWD,'screenshot', 'main_win' , 'cal_address1.png'), region=(844, 527, (1279-844), (548-527)) ) # client address2 pg.screenshot( os.path.join(CWD,'screenshot', 'main_win' , 'cal_address2.png'), region=(844, 563, (1279-844), (584-563)) ) pg.screenshot( os.path.join(CWD,'US02', 'user information for comparison .png'), region=(520, 127, (1405-520), (870-127)) ) pg.moveTo(942, 634, 0.5) # submit pg.click() except: print("[There's somthing wrong]") # choose a client and go to equip page try: pg.moveTo(632, 487, 0.7) pg.click() btn_choose_client = pg.locateOnScreen( os.path.join(CWD, 'screenshot' ,'main_win' ,'choose_client.png'), grayscale=False, confidence=.9) pg.moveTo(btn_choose_client) pg.click() except: print("[Fail to find the picture or choose function fails]") raise # check information # check cal_num try: cal_num = pg.locateOnScreen( os.path.join(CWD, 'screenshot' ,'main_win' ,'cal_num.png'), grayscale=False, confidence=.45) print(f"The client number position: {cal_num}") except: print("[Fail to locate the cilent number, or information incorrect]") raise # check client name try: cal_name = pg.locateOnScreen( os.path.join(CWD, 'screenshot' ,'main_win' ,'client_name.png'), grayscale=False, confidence=.9) print(f"The client name position: {cal_name}") except: print("[Fail to locate the cilent name, or information incorrect]") raise # check client address1 try: cal_address1 = pg.locateOnScreen( os.path.join(CWD, 'screenshot' ,'main_win' ,'cal_address1.png'), grayscale=False, confidence=.9) print(f"The client address1 position: {cal_address1}") except: print("[Fail to locate the cilent address1, or information incorrect]") raise # check client address2 try: cal_address2 = pg.locateOnScreen( os.path.join(CWD, 'screenshot' ,'main_win' ,'cal_address2.png'), grayscale=False, confidence=.9) print(f"The client address2 position: {cal_address2}") except: print("[Fail to locate the cilent address2, or information incorrect]") raise pg.screenshot( os.path.join(CWD,'US02', 'test_a_information_correct success .png'), region=(520, 127, (1405-520), (870-127)) ) # back to homepage for next testcase try: btn_home = pg.locateOnScreen( os.path.join(CWD, 'screenshot', 'main_win_info', 'info_home.png'), grayscale=False, confidence = .8 ) pg.moveTo(btn_home) pg.click() sleep(1) except: raise("[Fail to find the picture or home function fails]") def test_b_search_bar(self): """Continue from test a, and another user to test the search bar The main page information shows the matching results; otherwise, blank """ # the client "CAL0005 Alex sky island treasure cruise" has been added # by the previous testcase # create another user for testing search bar test_US01.TestUserStory1.test_a_add_new_client(self) pg.moveTo(645, 337, 0.7) # the search bar pg.click() pg.write("CAL00005") # data pg.screenshot( os.path.join(CWD,'screenshot', 'main_win' , 'search_CAL00005.png'), region=(544, 469, (955-544), (496-469)) ) try: search_CAL00005 = pg.locateOnScreen( os.path.join(CWD, 'screenshot' ,'main_win' ,'search_CAL00005.png'), grayscale=False, confidence=.9) print(f"The search CAL number result position: {search_CAL00005}") pg.screenshot( os.path.join(CWD,'US02', 'search CAL number success .png'), region=(520, 127, (1405-520), (870-127)) ) except: pg.screenshot( os.path.join(CWD,'US02', 'search CAL number fail .png'), region=(520, 127, (1405-520), (870-127)) ) print("[Fail to locate the picture, or information incorrect]") sleep(3) # stay for a while to be seen pg.click() # hotkey to delete the search text pg.hotkey('ctrl','a') pg.hotkey('delete') # search the client name pg.click() pg.write("Alex") # should see the search result sleep(3) # client name data pg.screenshot( os.path.join(CWD,'screenshot', 'main_win' , 'search_Alex.png'), region=(963, 469, (1364-963), (496-469)) ) sleep(1) try: search_Alex = pg.locateOnScreen( os.path.join(CWD, 'screenshot' ,'main_win' ,'search_Alex.png'), grayscale=False, confidence=.9) print(f"The search client name result position: {search_Alex}") pg.screenshot( os.path.join(CWD,'US02', 'search client name success .png'), region=(520, 127, (1405-520), (870-127)) ) except: pg.screenshot( os.path.join(CWD,'US02', 'search client name fail .png'), region=(520, 127, (1405-520), (870-127)) ) print("[Fail to locate the picture, or information incorrect]") sleep(1) pg.click() # hotkey to delete the search text pg.hotkey('ctrl','a') pg.hotkey('delete') # the case that the client information not in the list pg.click() pg.write("CAL00001") sleep(3) # hotkey to delete the search text pg.click() pg.hotkey('ctrl','a') pg.hotkey('delete') pg.screenshot( os.path.join(CWD,'US02', 'all information success .png'), region=(520, 127, (1405-520), (870-127)) ) # all the information should be back # delete two clients test_US01.TestUserStory1.test_e_del_client(self) test_US01.TestUserStory1.test_e_del_client(self) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestUserStory2) unittest.TextTestRunner(verbosity=2).run(suite) <file_sep>/tools/fake_jobs.py #!/usr/bin/python """ Generate fake jobs For test purpose. """ import os import shutil from os.path import join JOB_COUNT = 3000 JOB_PREFIX = 'GEN' _DIR_PATH = os.path.dirname(os.path.realpath(__file__)) JOBS = os.path.abspath(join(_DIR_PATH, '..', 'data', 'jobs')) TEMPLATE_JOB = join(JOBS, 'CAL00001') def main(): max_digit_len = len(str(JOB_COUNT)) for i in range(1, JOB_COUNT + 1): target = join(JOBS, JOB_PREFIX + str(i).zfill(max_digit_len)) shutil.copytree(TEMPLATE_JOB, target) if __name__ == '__main__': main() <file_sep>/data/jobs/CAL00002/NE 2571 3460/MEX/2/meta.ini [DEFAULT] added_at = 2021-10-05T20:52:01+08:00 edited_at = 2021-10-05T20:52:01+08:00 measured_at = 2021-02-09 ic_hv = -250 operator = <NAME> <file_sep>/data/jobs/CAL00003/meta.ini [DEFAULT] client_name = ClientC_Name client_address_1 = 555 Street Name client_address_2 = Suburb ACT 1020 <file_sep>/app/core/utils.py """ Utility functions """ from pathlib import Path from datetime import datetime from typing import Iterator import itertools from collections import deque def ensure_folder(path: Path) -> bool: """ Ensure the folder in path exists. If it does not exist, create the folder Return whether the folder exists. """ if not path.exists(): path.mkdir() return False else: assert path.is_dir(), 'The path should be a folder' return True def datetime_to_iso(time: datetime) -> str: """ Converts a datetime object into ISO8601 format with current timezone, without microsecond """ return time.astimezone().replace(microsecond=0).isoformat() def iter_subfolders(folder: Path) -> Iterator[Path]: """ Iterate through the folder, yield each subfolders """ for file in folder.iterdir(): if not file.is_dir(): continue yield file def count_iter_items(iterable): # from https://stackoverflow.com/a/15112059 """ Consume an iterable not reading it into memory; return the number of items. """ counter = itertools.count() deque(zip(iterable, counter), maxlen=0) # (consume at C speed) return next(counter) <file_sep>/gui_testing/scrape/get_text_pos.py import easyocr import pandas as pd # setting, use English and enable the combination of characters and numbers reader = easyocr.Reader(['en']) # be able to use CUDA, much faster than CPU allow_list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ' screenshot_list = ['analysis', 'client_info', 'equipment_info', 'homepage', 'save'] for image in screenshot_list: result = reader.readtext(f'page_screenshots/{image}.png', detail=1, allowlist = allow_list) df = pd.DataFrame(result) # convert to df.columns = ['pos', 'string', 'confidence'] df.to_csv(f'data/{image}.csv', index=False) <file_sep>/data/jobs/CAL00004/PTW 30013 6533/MEX/1/meta.ini [DEFAULT] added_at = 2021-10-05T20:54:35+08:00 edited_at = 2021-10-05T20:54:35+08:00 measured_at = 2020-10-29 ic_hv = -360 <file_sep>/INSTALL.md # Installation manual ## Introduction This installation manual aims to help deploy and install our Digital Calibration application in the Windows10 environment based on our development experience. The main contents cover the essentials for development and runtime environment, troubleshooting etc. ## Pre-Installation Requirements * Windows10 * Python >= 3.6. The download link: [https://www.python.org/downloads/](https://www.python.org/downloads/) * To develop the program using Pipenv, the version needs to be exactly `3.6`. * Excel: Our product uses Excel to generate intermediate template files. * PDF viewers such as Adobe Acrobat Reader DC are required to open the final report * pip: pip is the package installer for Python. * Pipenv: Not necessary, but it is essential for development. Pipenv is a tool that can manage virtual environments and packages for development. It can be installed simply as: pip install --user pipenv * Git or Github: The source code can be cloned or downloaded directly from our repo. Link: [https://github.com/Johnlky/DC-Boxjelly](https://github.com/Johnlky/DC-Boxjelly) ## Installation Steps 1. Specify a location and open the command prompt. Then type: git clone https://github.com/Johnlky/DC-Boxjelly.git If the condition is not met, you can simply download the ZIP file from our Github homepage as the following figure shows (downloading zip file in the main branch is fine): ![Download Zip](docs/images/download-zip.png "image_tooltip") 2. When the clone or unzipping is done, run install.bat in the root folder by double clicking the file or typing ‘install.bat’ in the command line and run. 3. When all packages are installed successfully, you can simply run run.bat file to launch the program. **Note: If the required packages are installed, there is no need to run the install.bat.** ## Troubleshooting * What if I come across “ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied...” That means the installation process is not under admin mode. In this case, please right-click the install.bat and click “Run as administrator” <file_sep>/app/main.py """ The entry point of main program. """ from portalocker.exceptions import AlreadyLocked import portalocker from PyQt5.QtWidgets import QMessageBox, QApplication import sys import logging from logging.handlers import RotatingFileHandler from app.core.definition import JOBS_LOCK_PATH from app.gui.main import start_event_loop logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) def handle_exception(exc_type, exc_value, exc_traceback): if issubclass(exc_type, KeyboardInterrupt): sys.__excepthook__(exc_type, exc_value, exc_traceback) return logger.critical("Uncaught exception", exc_info=( exc_type, exc_value, exc_traceback)) sys.excepthook = handle_exception def main(): std_out_log = logging.StreamHandler() std_out_log.setLevel(logging.DEBUG) file_log = RotatingFileHandler('dc.log') file_log.setLevel(logging.INFO) logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[ std_out_log, file_log, ]) logger.info('Starting application') try: with portalocker.Lock(JOBS_LOCK_PATH, fail_when_locked=True): logger.info('Data lock acquired, starting event loop') ret = start_event_loop() except AlreadyLocked: logger.error('Multiple instance detected') app = QApplication(sys.argv) msg = QMessageBox(QMessageBox.Icon.Critical, 'Error: Multiple instance detected!', 'This program is already running on this device or other devices in the' ' network that are accessing the same data folder. Please ensure other ' 'instances are closed. If you are sure that this is an false alert and all ' f'instances are closed, please delete the file {JOBS_LOCK_PATH.absolute()}' ) msg.show() app.exec() ret = 1 sys.exit(ret) if __name__ == '__main__': main() <file_sep>/gui_testing/screenshot/grab_main_win.py """ The screen resolution is (1920,1080). The script aims for cropping the images from the application main window. The reason using the pyautogui instead of creenshot using Windows 10 bulit-in snip & sketch tools is that the image might not be recognized by opencv. """ import os import pyautogui as pg # W0311: bad indentation; E1101:no-member; C0325: Unnecessary parens; C0103: upper case naming # pylint: disable=W0311, E1101, C0325, C0103 try: os.mkdir('main_win') except OSError: print("[The directory already existed]") # button add_new_client btn_add_new_client_x = 820 btn_add_new_client_y = 368 pg.screenshot( 'main_win/add_new_client.png', region=( btn_add_new_client_x, btn_add_new_client_y, (1098-btn_add_new_client_x), (416-btn_add_new_client_y) ) ) # button choose client btn_choose_client_x = 540 btn_choose_client_y = 368 pg.screenshot( 'main_win/choose_client.png', region=( btn_choose_client_x, btn_choose_client_y, (817-btn_choose_client_x), (416-btn_choose_client_y) ) ) # button delete client btn_delete_client_x = 1101 btn_delete_client_y = 368 pg.screenshot( 'main_win/delete_client.png', region=( btn_delete_client_x, btn_delete_client_y, (1383-btn_delete_client_x), (416-btn_delete_client_y) ) ) # fake data for checking function field_cal_number_x = 542 field_cal_number_y = 465 pg.screenshot( 'main_win/cal_CAL0004.png', region=( field_cal_number_x, field_cal_number_y, (957 - field_cal_number_x), (499 - field_cal_number_y) ) ) <file_sep>/data/jobs/CAL00003/NE 2571 3661/MEX/2/meta.ini [DEFAULT] added_at = 2021-10-05T20:52:29+08:00 edited_at = 2021-10-05T20:52:29+08:00 measured_at = 2021-02-16 ic_hv = -300 operator = <NAME> <file_sep>/data/jobs/CAL00003/NE 2571 3661/MEX/1/meta.ini [DEFAULT] added_at = 2021-10-05T20:52:17+08:00 edited_at = 2021-10-05T20:52:17+08:00 measured_at = 2021-02-15 ic_hv = -300 operator = <NAME> <file_sep>/gui_testing/screenshot/grab_main_win_info.py """ The screen resolution is (1920,1080). The script aims for cropping the images from the application main window, equipment information page. The reason using the pyautogui instead of creenshot using Windows 10 bulit-in snip & sketch tools is that the image might not be recognized by opencv. """ import os import pyautogui as pg # W0311: bad indentation; E1101:no-member; C0325: Unnecessary parens; C0103: upper case naming # pylint: disable=W0311, E1101, C0325, C0103 try: os.mkdir('main_win_info') except OSError: print("[The directory already existed]") # cal num cal_num_x = 922 cal_num_y = 335 pg.screenshot( 'main_win_info/info_client_cal_num.png', region=( cal_num_x, cal_num_y, (1066-cal_num_x), (361-cal_num_y) ) ) start_x = 692 end_x = 1289 # client name client_name_x = start_x client_name_y = 364 pg.screenshot( 'main_win_info/info_client_name.png', region=( client_name_x, client_name_y, (end_x - client_name_x), (403 - client_name_y) ) ) # client address1 client_address_1_x = start_x client_address_1_y = 403 pg.screenshot( 'main_win_info/info_client_address1.png', region=( client_address_1_x, client_address_1_y, (end_x - client_address_1_x), (439 - client_address_1_y) ) ) # client address2 client_address_2_x = start_x client_address_2_y = 439 pg.screenshot( 'main_win_info/info_client_address2.png', region=( client_address_2_x, client_address_2_y, (end_x - client_address_2_x), (474 - client_address_2_y) ) ) # button choose equipment btn_choose_client_x = 536 btn_choose_client_y = 495 pg.screenshot( 'main_win_info/info_choose_equipment.png', region=( btn_choose_client_x, btn_choose_client_y, (748 - btn_choose_client_x), (548 - btn_choose_client_y) ) ) # button add new equipment btn_add_new_equip_x = 750 btn_add_new_equip_y = 500 pg.screenshot( 'main_win_info/info_add_new_equipment.png', region=( btn_add_new_equip_x, btn_add_new_equip_y, (958 - btn_add_new_equip_x), (543 - btn_add_new_equip_y) ) ) # button delete equipment btn_del_equip_x = 958 btn_del_equip_y = 495 pg.screenshot( 'main_win_info/info_del_equipment.png', region=( btn_del_equip_x, btn_del_equip_y, (1169 - btn_del_equip_x), (548 - btn_del_equip_y) ) ) # button return to main page btn_return_x = 1169 btn_return_y = 495 pg.screenshot( 'main_win_info/info_return.png', region=( btn_return_x, btn_return_y, (1382 - btn_return_x), (548 - btn_return_y) ) ) # button update btn_update_x = 1292 btn_update_y = 377 pg.screenshot( 'main_win_info/info_update.png', region=( btn_update_x, btn_update_y, (1368 - btn_update_x), (426 - btn_update_y) ) ) # home tab btn_home_x = 540 btn_home_y = 180 pg.screenshot( 'main_win_info/info_home.png', region=( btn_home_x, btn_home_y, (943 - btn_home_x), (753 - btn_home_y) ) ) # make/model field_make_x = 545 field_make_y = 597 pg.screenshot( 'main_win_info/info_make.png', region=( field_make_x, field_make_y, (817 - field_make_x), (624 - field_make_y) ) ) # serial num field_serial_x = 826 field_serial_y = 597 pg.screenshot( 'main_win_info/info_serial.png', region=( field_serial_x, field_serial_y, (1094 - field_serial_x), (624 - field_serial_y) ) ) <file_sep>/data/jobs/CAL00002/NE 2571 3460/meta.ini [DEFAULT] model = NE 2571 serial = 3460 <file_sep>/data/jobs/CAL00002/meta.ini [DEFAULT] client_name = ClientB_Name client_address_1 = 123 Street Name client_address_2 = Suburb QLD 6020 <file_sep>/data/jobs/CAL00001/meta.ini [DEFAULT] client_name = ClientA_Name client_address_1 = 200 Street Name client_address_2 = Suburb NSW 2020 <file_sep>/gui_testing/test_US04.py """ The test file need to be run inside the gui_testing directory, with application centered on the (1920,1080) resolution main screen. The test cases are for the system testing, with the tests visulized. The test cases are testing the user story 4, mainly with the functionalities regarding: 1. After client add an equipment and a run, the application could pop up the analysis. 2. The client could add two runs, select multiple runs to be analyzed. Note that the opencv is limited to access the information within the text field, which means the tests aren't 100 percent assured. The current way is to screenshot the user input and the equipment page for comparison. """ import unittest import os import shutil from time import sleep import pyautogui as pg import test_US01 # W0311: bad indentation; E1101:no-member; C0325: Unnecessary parens # pylint: disable=W0311, E1101, C0325 # use the current directory, where the script exists CWD = os.path.dirname(os.path.realpath(__file__)) class TestUserStory4(unittest.TestCase): """The user story 4 related system testing Args: unittest ([type]): [The default testing module from Python] """ @classmethod def setUpClass(self): """Create or replace previous folders """ try: folder = os.getcwd() + "\\US04 Fail" shutil.rmtree(folder) except: print("[There's no such directory]") try: folder = os.getcwd() + "\\US04 Success" shutil.rmtree(folder) except: print("[There's no such directory]") try: folder = os.getcwd() + "\\US04" shutil.rmtree(folder) except: print("[There's no such directory]") try: self.cwd = os.getcwd() # for printing the current directory # print(self.cwd) os.mkdir("US04") os.chdir("US04") # cd to the directory for saving screenshots self.storage = '%s/' % os.getcwd() # escape the cwd string except: print("[Something is wrong when creating the directory]") @classmethod def tearDownClass(self): file_list = os.listdir() # print(file_list) # iterate through the filename string, if there's a keyword "fail", rename the folder for filename in file_list: if "fail" in filename: # print("Some tests failed") os.chdir("..") os.rename("US02", "US04 Fail") return os.chdir("..") os.rename("US02", "US04 Success") def test_a_single_run(self): """A client add a equipment, add a set of data, then analyze """ # use the existing test cases, but would show up "[Fail to locate the folder]" # since the screenshots are presumed to be saved in the US01 folder test_US01.TestUserStory1.test_a_add_new_client(self) test_US01.TestUserStory1.test_b_add_equipment(self) test_US01.TestUserStory1.test_c_add_new_run(self) pg.moveTo(649, 575, 0.7) pg.click() btn_analyze = pg.locateOnScreen( os.path.join(CWD, 'screenshot', 'main_win_equip', 'equip_analyze.png'), grayscale=False, confidence = .7 ) pg.moveTo(btn_analyze) pg.click() sleep(3) # waiting the window to pop up pg.screenshot( os.path.join(CWD,'US02', 'test single analyze success .png'), region=(345, 36, (1569-520), (960-36)) ) pg.moveTo(1532, 60, 0.7) # cross tab pg.click() pg.moveTo(905, 534, 0.7) # yes pg.click() sleep(1) test_US01.TestUserStory1.test_e_del_client(self) def test_b_two_runs(self): """A client add a equipment, add two set of data, then analyze """ test_US01.TestUserStory1.test_a_add_new_client(self) test_US01.TestUserStory1.test_b_add_equipment(self) test_US01.TestUserStory1.test_c_add_new_run(self) # add another run try: btn_add_new_run = pg.locateOnScreen( os.path.join(CWD, 'screenshot', 'main_win_equip', 'equip_add_new_run.png'), grayscale=False, confidence = .9 ) pg.moveTo(btn_add_new_run) pg.click() except: raise("cannot locate the button add new run") # check the submit is successful try: pg.moveTo(674, 470, 0.7) # client file tab pg.click() pg.moveTo(910, 613, 0.7) # file pg.click() pg.moveTo(1281, 912, 0.7) # open pg.click() pg.moveTo(669, 539, 0.7) # lab file tab pg.click() pg.moveTo(910, 638, 0.7) # file pg.click() pg.moveTo(1281, 912, 0.7) # open pg.click() pg.moveTo(967, 601, 0.7) #submit pg.click() except: print("[Fail to locate the folder]") pg.moveTo(671, 717, 0.7) # empty space pg.click() # hotkey to select all runs pg.hotkey('ctrl','a') # locate the analyze button try: btn_analyze = pg.locateOnScreen( os.path.join(CWD, 'screenshot', 'main_win_equip', 'equip_analyze.png'), grayscale=False, confidence = .7 ) pg.moveTo(btn_analyze) pg.click() except: print("[Fail to locate the picture]") try: sleep(3) # waiting the window to pop up pg.screenshot( os.path.join(CWD,'US02', 'test two runs analyze success .png'), region=(345, 36, (1569-520), (960-36)) ) pg.moveTo(1532, 60, 0.7) # cross tab pg.click() pg.moveTo(905, 534, 0.7) # yes pg.click() except: print("[Fail to locate the folder]") sleep(1) test_US01.TestUserStory1.test_e_del_client(self) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestUserStory4) unittest.TextTestRunner(verbosity=2).run(suite) <file_sep>/data/jobs/CAL00004/meta.ini [DEFAULT] client_name = ClientD_Name client_address_1 = client_address_2 = <file_sep>/data/jobs/CAL00002/NE 2571 3460/MEX/1/meta.ini [DEFAULT] added_at = 2021-10-05T20:51:45+08:00 edited_at = 2021-10-05T20:51:45+08:00 measured_at = 2021-02-08 ic_hv = -250 operator = <NAME> <file_sep>/gui_testing/screenshot/README.md # Overview The script in the folder is for screenshot the elements on the application screen. The application opens in the (1920, 1080) resolution, the centered main screen. Note that the application might automatically be resized that the script could've cropped the wrong position. The screenshots are saved in the folders by using the same-named Python script. # Purpose The screenshots are used in the tests to locate the element by using OpenCV. It could be handy to assert if a component exists, such as button elements, without specifying element location. # Usage To crop a picture, the starting location (x, y) and the width, height is necessary with the PyAutoGUI library. Please see its documentation for more details ( https://pyautogui.readthedocs.io/en/latest/ ). <file_sep>/data/jobs/CAL00001/PTW 30013 5122/MEX/2/meta.ini [DEFAULT] added_at = 2021-10-05T20:51:30+08:00 edited_at = 2021-10-05T20:51:30+08:00 measured_at = 2021-03-01 ic_hv = -250 operator = <NAME> <file_sep>/app/core/models.py """ This file contains the models representing a job, an equipment and a run. Each model controls a folder in /data. Data consistency is not guaranteed if a folder is access by multiple instences (such as multiple devices accessing the same folder) at the same time. """ from pathlib import Path from typing import Dict, Iterable, Iterator, List, Optional, Tuple from datetime import datetime, date import shutil import os import errno import logging import csv import stat from .mixins import DeleteFolderMixin, WithMetaMixin, assign_properties, meta_property from .definition import CONSTANT_FILE_NAME, CONSTANT_FOLDER, RAW_DATA_SECTION_NAME, RAW_META_SECTION_NAME, JOB_FOLDER, MEX_FOLDER_NAME, MEX_RAW_CLIENT_FILE_NAME, MEX_RAW_FOLDER_NAME, MEX_RAW_LAB_FILE_NAME, RAW_MEASUREMENT_SECTION_NAME, TEMPLATE_CONSTANT_FILE from .utils import count_iter_items, datetime_to_iso, ensure_folder, iter_subfolders logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) class _JobMetaClass(type): def __iter__(cls) -> Iterator['Job']: """ Return an iterator of Job object in the job folder """ for file in iter_subfolders(JOB_FOLDER): yield cls(file.name) def __getitem__(cls, id) -> 'Job': """ Get a job by id, it is case insensitive on windows @id: The id of the job If the job does not exist, it raises a KeyError """ obj = cls(id) if not obj._folder.is_dir(): raise KeyError(f'Job with id={id} does not exist') return obj def __delitem__(cls, id): """ Delete a job by its id. If the job with id does not exist, it raises KeyError """ cls[id].delete() def __len__(self): """ Get the number of all jobs """ return count_iter_items(iter_subfolders(JOB_FOLDER)) def __contains__(self, id) -> bool: """ Return whether a job exists by id. The id is case insensitive on windows. """ folder = JOB_FOLDER / str(id) return folder.is_dir() def make(cls, id: str, **kwargs) -> 'Job': """ Create a new job with optional properties. If the job with given id exists, it raises an AssertionError """ if id in Job: raise ValueError(f'The Job with id={id} has already existed') obj = cls(id) assert not obj._ensure_folder_with_meta(), 'The job folder should not exist' assign_properties(obj, kwargs) return obj class Job(WithMetaMixin, DeleteFolderMixin, metaclass=_JobMetaClass): """ A model that represents a job. Use following methods to list, iterate, make, and get jobs: ``` # list jobs list(Job) # iterate through all jobs for job in Job: print(job) # get job number len(Job) # create new job Job.make(1, client_name="A client") # get job by id Job[1] # check job existence 1 in Job # => a boolean 'string_job_id_1' in Job # string works too ``` In additions to the given methods, it supports basic python operations like below: ``` job = Job[5] # iterate through each equipments for equipment in job: print(equipment) # get an equipment by its id job['AAA_123'] # delete an equipment del job['AAA_123'] # get the total number of equipments len(job) # check equipment existence 'AAA_123' in job # => a boolean ``` Read, write and delete meta data like below: ``` job = Job[5] print(job.client_name) # get client name job.client_name = 'Another client' # set client name del job.client_name # remove client name (next time, job.client_name is None) ``` """ def __init__(self, id: str) -> None: """ The private constructor of Job. **This is not meant to be used outside of `core.models`!** - If you want to create a new job, use `Job.make` - If you want to get an existing job, use `Job[_id_]` """ self._id = str(id) self._folder = JOB_FOLDER / self._id def __repr__(self) -> str: return f'Job({self._id})' __str__ = __repr__ def __iter__(self) -> Iterator['Equipment']: """ Get all equipments belongs to the job """ for file in iter_subfolders(self._folder): yield Equipment(self, id=file.name) def __contains__(self, id) -> bool: """ Return whether this job contains equipment identified by id """ folder = self._folder / str(id) return folder.is_dir() def __getitem__(self, id): """ Get one equipment by id. It verifies whether the folder exists. """ if id not in self: raise KeyError( f'The equipment identified by {id} is not a folder!') return Equipment(self, id=id) def __delitem__(self, id): """ Delete an equipment by the id provided """ equipment = self[id] equipment.delete() def __len__(self): """ Get the number of equipments in this job """ return count_iter_items(iter_subfolders(self._folder)) @property def id(self): return self._id # meta properties client_name = meta_property('client_name', 'Client identifier string') client_address_1 = meta_property( 'client_address_1', 'The first line of client address') client_address_2 = meta_property( 'client_address_2', 'The second line of client address') def add_equipment(self, model, serial) -> 'Equipment': """ Add an equipment with the given model and serial If equipment exists, raise ValueError """ return Equipment(self, model=model, serial=serial) @property def meta(self) -> Dict[str, str]: """ Export job meta data into a dict """ return { 'job_id': self.id, 'client_name': self.client_name, 'client_address_1': self.client_address_1, 'client_address_2': self.client_address_2, } class Equipment(WithMetaMixin, DeleteFolderMixin): """ A model that represents an equipment. Use `equipment.mex` to get the set of mex runs of this equipment """ def __init__(self, parent: Job, id: Optional[str] = None, model: Optional[str] = None, serial: Optional[str] = None) -> None: """ Init an equipment, either id or (model, serial) should be not None. **This constructor is not meant to be used outside of `core.models`!** - If you want to create a new equipment, use `job.add_equipment('AAA', '123')` - If you want to get an existing equipment by id, use `job['AAA_123']` @partent: which job this equipment belongs to. @id: a string representing the id of an equipment @model, serial: the model and serial of the equipment Create equipment like below: ``` # Create a reference to an existing equipment: Equipment(job, id='AAA_123') # Create a new equipment Equipment(job, model='AAA', serial='123') ``` """ self._parent = parent if id: assert (parent._folder / str(id) ).is_dir(), 'Equipment folder exists' self._id = id self._folder = parent._folder / self._id assert self._meta_exists() else: assert model, 'model should be provided' assert serial, 'serial should be provided' self._id = f'{model} {serial}' self._folder = parent._folder / self._id if self._folder.exists(): raise ValueError(f'The model ({model}) and serial {serial} in ' '{parent} should not exist at creation') self._ensure_folder_with_meta({ 'model': model, 'serial': serial, }) self.mex = MexMeasurements(self) def __repr__(self) -> str: return f'Equipment({self._id}, parent={self._parent})' def __str__(self): return f'Equipment({self._id})' @property def id(self): return self._id model = meta_property('model', 'The model of the equipment', readonly=True) serial = meta_property( 'serial', 'The serial of the equipment', readonly=True) @property def meta(self) -> Dict[str, str]: """ Export equipment meta data into a dict """ return { 'equipment_model': self.model, 'equipment_serial': self.serial, } def check_consistency(self) -> Optional[str]: """ Check consistency of this equipment. If they do not meet, return error message, otherwise, return None 1. IC_HV of all runs must be the same. """ if not self._check_ic_hv(): return 'IC_HV of all runs must be the same' def _check_ic_hv(self): iterator = iter(self.mex) try: first = next(iterator) except StopIteration: return True return all(first.IC_HV == x.IC_HV for x in iterator) class MexMeasurements: """ A mex measurement belongs to an equipment. In additions to the given methods, it supports basic python operations like below: ``` job = Job[5] e = job['AAA_123'] # a equipment # iterate through each MexRun's for run in e.mex: print(e) # get a mex run by its id e.mex[1] # delete a mex run del e.mex[1] # get the total number of mex runs len(e.mex) ``` """ def __init__(self, parent: Equipment) -> None: """ Init MexMeasurements. **This constructor is not meant to be used outside of `core.models`!** - You can use `equipment.mex` to access MEX measurements """ self._parent = parent self._folder = parent._folder / MEX_FOLDER_NAME ensure_folder(self._folder) def __str__(self) -> str: return f'MexAssessment({self._parent})' def __repr__(self) -> str: return f'MexAssessment({self._parent.__repr__()})' def __iter__(self) -> Iterator['MexRun']: """ Iterate through all MEX runs """ for file in iter_subfolders(self._folder): yield MexRun(self, int(file.name)) def __contains__(self, id) -> bool: """ Check if the equipment has the MEX run with given id """ folder = self._folder / str(id) return folder.is_dir() def __getitem__(self, id) -> 'MexRun': """ Get a mex run by id. If run does not exist, raise KeyError """ if id not in self: raise KeyError(f'{self} does not contains MEX run with id={id}') return MexRun(self, id) def __delitem__(self, id): """ Delete a mex run by id. If run does not exist, raise KeyError """ self[id].delete() def __len__(self): return count_iter_items(iter_subfolders(self._folder)) def add(self) -> 'MexRun': """ Add a new MEX run """ return MexRun(self) class MexRun(WithMetaMixin, DeleteFolderMixin): """ This model represents a run in mex analysis. """ def __init__(self, parent: MexMeasurements, id: Optional[int] = None) -> None: """ Initialize a MexRun instance. **This constructor is not meant to be used outside of `core.models`!** - If you want to create a new run, use `equipment.mex.add()` - If you want to get an existing run by id, use `equipment.mex[_id_]` If id exists, it reads the data from the existing run. If it does not exist, this process creates new run in the parent folder. """ self._parent = parent if not id: id = max(run.id for run in parent) + 1 \ if len(parent) > 0 else 1 else: assert (parent._folder / str(id)).is_dir(), 'MEX run folder exists' self._id = int(id) self._folder = parent._folder / str(id) self._raw = self._folder / MEX_RAW_FOLDER_NAME self._client = self._raw / MEX_RAW_CLIENT_FILE_NAME self._lab = self._raw / MEX_RAW_LAB_FILE_NAME self.raw_client = MexRawFile( self, self._client, update_meta=True, type='client') self.raw_lab = MexRawFile(self, self._lab, type='lab') self._ensure_folder_with_meta({ 'added_at': datetime_to_iso(datetime.now()), 'edited_at': datetime_to_iso(datetime.now()), }) ensure_folder(self._raw) def __repr__(self) -> str: return f'MexRun({self._id}, parent={self._parent})' __str__ = __repr__ @property def id(self) -> int: return self._id operator = meta_property('operator', 'Who did the measurement') added_at = meta_property( 'added_at', 'The datetime when this run is created', readonly=True) edited_at = meta_property('edited_at', 'The datetime when this run is edited (changing RAW data)', setter=lambda time: datetime_to_iso(time) if type(time) is datetime else str(time)) measured_at = meta_property('measured_at', 'The date when the measurement is created (measurement date).', setter=lambda date: date.isoformat() if type(date) is date else str(date)) IC_HV = meta_property( 'IC_HV', 'The IC HV in mex run. Although it is a number, the type of this property should be string') @property def meta(self) -> Dict[str, str]: """ Export run meta data into a dict """ return { 'run_id': str(self.id), 'operator': self.operator, 'run_added_at': self.added_at, 'run_edited_at': self.edited_at, 'run_measured_at': self.measured_at, 'IC_HV': self.IC_HV, } class MexRawFile: """ Representing a raw file """ def __init__(self, parent: MexRun, path: Path, update_meta=False, type: str = '') -> None: """ Create a raw file object. If update_meta is True, `upload_from` will update meta data from raw data. `type` is only used in `export_file_name`. Currently it can be `client`, `file` or empty. ** This constructor is not meant to be used outside of models.py! ** - Please access it through MexRun """ self._path = path self._parent = parent self._update_meta = update_meta self._type = type def __str__(self) -> str: file = self._path.name return f'RawMexFile({file}, parent={self._parent})' __repr__ = __str__ @property def path(self) -> Optional[Path]: """ Get the path to the raw file. If file does not exist, return None """ return self._path if self._path.exists() else None def upload_from(self, source: Path): """ Save the raw data from `source` path. It just copies the file into the run/raw folder. This method overwrites attributes in MexRun by some field in the file, such as IC_HV and measured_at. If the source file does not exist, it raises ValueError """ if not Path(source).is_file(): raise ValueError(f'Source path {source} is not a file') with source.open(encoding='ISO-8859-1') as f: lines = f.readlines() if lines[0].strip() == RAW_META_SECTION_NAME: beg = [i for i, line in enumerate(lines) if line.strip().startswith(RAW_MEASUREMENT_SECTION_NAME)] assert len(beg) == 1 lines = lines[beg[0]:] with self._path.open('w', encoding='ISO-8859-1') as f: f.writelines(lines) self._update_edit_time() if self._update_meta: self._extract_raw_meta(lines) def remove(self): """ Remove the raw data file. If the file does not exist, it does nothing. An OSError may be raised if errors such as no permission is encountered. """ if not self.exists: return try: os.remove(self._path) except OSError as e: if e.errno != errno.ENOENT: # no such file or directory raise self._update_edit_time() @property def export_file_name(self): """ return the preferred file name for exporting the file. """ run = self._parent equip = run._parent._parent job = equip._parent return f'{job.id},MexRaw,{equip.id},Run{run.id},{self._type}.csv' @property def exists(self): return self._path.exists() def export_to(self, path: Path): """ Export raw data into path. Please ensure the parent folder of path exists. """ assert path.parent.is_dir() if not self.exists: raise FileNotFoundError('The raw file does not exist!') with self._path.open() as f: lines = f.readlines() run = self._parent equipment = run._parent._parent job = equipment._parent meta_section = [ RAW_META_SECTION_NAME + '\n', *_meta_dict_to_csv_line(job), *_meta_dict_to_csv_line(equipment), *_meta_dict_to_csv_line(run), ] with path.open('w') as f: f.writelines(meta_section) f.writelines(lines) def _update_edit_time(self): self._parent.edited_at = datetime.now() def _extract_raw_meta(self, lines: List[str]): """ Extract some meta data from raw files into the MexRun meta data. If it is called multiple times, the previous meta data in MexRun will be overwritten. """ # extract meta section beg = None end = None logger.debug('raw file (first 20 lines): \n %s', lines[0:20]) for idx, line in enumerate(lines): if RAW_MEASUREMENT_SECTION_NAME in line: beg = idx + 1 continue if RAW_DATA_SECTION_NAME in line: end = idx break if not beg or not end: logger.warning('This file does not contains %s, obj: %s', RAW_MEASUREMENT_SECTION_NAME, self) return run = self._parent assert type(run) == MexRun # extract fields section = lines[beg:end] for row in csv.reader(section): name = row[0] value = row[2] if name == 'Date': try: [d, m, y] = value.split('/') run.measured_at = date(int(y), int(m), int(d)) except ValueError: logger.error( 'Cannot parse date, obj: %s, value: %s', self, value) elif name == 'IC HV': run.IC_HV = str(value) elif name == 'Operator': run.operator = value def _meta_dict_to_csv_line(obj): return ['{k},{v}\n'.format(k=k, v=v if v else '') for k, v in obj.meta.items()] class _ConstantFileMetaClass(type): def __iter__(self) -> Iterator['ConstantFile']: """ Return an iterator of ConstantFile object in the constants folder """ for file in iter_subfolders(CONSTANT_FOLDER): yield ConstantFile(int(file.name)) def __getitem__(self, id: int) -> 'ConstantFile': """ Get a constant file object by id, it is an integer. @id: The id of the constant file object If the constant file does not exist, it raises a KeyError """ if not (CONSTANT_FOLDER / str(id)).is_dir(): raise KeyError(f'Constant file with id={id} does not exist') return ConstantFile(id) def __delitem__(self, id: int): """ Delete a constant file by its id. If the constant file with id does not exist, it raises KeyError """ self[id].delete() def __len__(self): """ Get the number of all constant files """ return count_iter_items(iter_subfolders(CONSTANT_FOLDER)) def __contains__(self, id: int) -> bool: """ Return whether a constant file exists by id. The id is an integer. """ folder = CONSTANT_FOLDER / str(id) return folder.is_dir() def make(self) -> 'ConstantFile': """ Create a new constant file from the template constant. The new object have a new id that is bigger than the biggest existed constant file id. """ return ConstantFile() class ConstantFile(WithMetaMixin, metaclass=_ConstantFileMetaClass): """ Represent a constant file. It is a xlsx file that can be directly edited by MS Excel. Just like Job, use following code to interact with ConstantFile: ``` # Get constant file object by id c = ConstantFile[1] # read or write meta data print(c.note) c.note = 'The MEX constant files to be used in 2020-2030' del c.note print(c.added_at) # get file path c.path # => a Path object to the xlsx file # delete the file c.delete() ``` Use following code to do CRUDs: ``` # list constant files list(ConstantFile) # Add new constant file ConstantFile.make() # iterate for f in ConstantFile: print(f) # check existence 42 in ConstantFile # delete del ConstantFile[42] # length len(ConstantFile) ``` There are also configs for constant files, see _ConstantFileConfig below. """ def __init__(self, id: Optional[int] = None) -> None: """ The private constructor of ConstantFile. **This is not meant to be used outside of `core.models`!** - If you want to create a new constant file, use `ConstantFile.make` - If you want to get an existing constant file, use `ConstantFile[_id_]` """ if not id: id = max(int(run.name) for run in iter_subfolders(CONSTANT_FOLDER)) + 1 \ if len(list(iter_subfolders(CONSTANT_FOLDER))) > 0 else 1 else: assert (CONSTANT_FOLDER / str(id) ).is_dir(), 'Constant folder should exists' self._id = int(id) self._folder = CONSTANT_FOLDER / str(id) if not self._ensure_folder_with_meta({ 'added_at': datetime_to_iso(datetime.now()), }): shutil.copy(TEMPLATE_CONSTANT_FILE, self.path) self.path.chmod(stat.S_IWRITE) def __repr__(self) -> str: return f'ConstantFile({self._id})' __str__ = __repr__ @property def id(self) -> int: return self._id @property def path(self) -> Path: """ Get the path to the constant file """ return self._folder / CONSTANT_FILE_NAME added_at = meta_property( 'added_at', 'The datetime when this constant file is created', readonly=True) note = meta_property('title', 'Note of the constant file') def delete(self): """ Remove the model, this process cannot be undone. After calling this method, invoking other methods are invalid. """ shutil.rmtree(self._folder) if str(self._id) == constant_file_config.default_id: del constant_file_config.default_id class _ConstantFileConfig(WithMetaMixin): """ The config for constent files. Please use `constent_file_config` directly. """ _folder = CONSTANT_FOLDER default_id = meta_property( 'default', 'The id of the default constant file', setter=str) @property def default(self) -> Optional['ConstantFile']: """ The default constant file object. If there are not default constant file, it returns None. If the default_id in meta.ini does not exist in the folder, it returns None. """ if self.default_id and self.default_id in ConstantFile: return ConstantFile[self.default_id] else: return None def get_path(self) -> Path: """ If default constant file exists, returns its path. Else, return the path of the template file. Since the path can be the template file, please do not modify its content. """ if self.default: return self.default.path else: return TEMPLATE_CONSTANT_FILE constant_file_config = _ConstantFileConfig() <file_sep>/app/core/definition.py from pathlib import Path from stat import S_IREAD from .utils import ensure_folder ''' The path of the data folder ''' DATA_FOLDER = Path('data') ensure_folder(DATA_FOLDER) ''' The path of the job folder ''' JOB_FOLDER = DATA_FOLDER / 'jobs' ensure_folder(JOB_FOLDER) ''' The name of the folder that stores MEX analysis ''' MEX_FOLDER_NAME = 'MEX' ''' The name of the folder in a MEX run that stores raw data ''' MEX_RAW_FOLDER_NAME = 'raw' ''' The name of the client raw file of MEX analysis ''' MEX_RAW_CLIENT_FILE_NAME = 'client.csv' ''' The name of the lab raw file of MEX analysis ''' MEX_RAW_LAB_FILE_NAME = 'lab.csv' ''' The name of the file that contains meta data such as client name or created time. ''' META_FILE_NAME = 'meta.ini' JOBS_LOCK_PATH = DATA_FOLDER / 'jobs.lock' ''' The name of meta section in exported csv file ''' RAW_META_SECTION_NAME = '[DC_META]' ''' The name of the measurement meta data in raw file ''' RAW_MEASUREMENT_SECTION_NAME = '[COMET X-RAY MEASUREMENT]' ''' The name of the data section in raw file ''' RAW_DATA_SECTION_NAME = '[DATA]' # constrains ''' The location of the template constant file. When a new constant file is added, this file is copied to the location. ''' TEMPLATE_CONSTANT_FILE = Path(__file__).parent / 'template_constant.xlsx' TEMPLATE_CONSTANT_FILE.chmod(S_IREAD) # make the file read only ''' The folder that contains constant files ''' CONSTANT_FOLDER = DATA_FOLDER / 'constants' if not ensure_folder(CONSTANT_FOLDER): (CONSTANT_FOLDER / META_FILE_NAME).touch() CONSTANT_FILE_NAME = 'constant.xlsx' ''' The path of the Operation Manual ''' OPS_MANUAL = Path(__file__).parent.parent.parent / 'docs' / 'Operation Manual.pdf' OPS_MANUAL.chmod(S_IREAD) # make the file read only<file_sep>/data/jobs/CAL00003/NE 2571 3661/MEX/3/meta.ini [DEFAULT] added_at = 2021-10-05T20:52:42+08:00 edited_at = 2021-10-05T20:52:42+08:00 measured_at = 2021-02-17 ic_hv = -300 operator = <NAME> <file_sep>/gui_testing/test_US01.py """ The test file need to be run inside the gui_testing directory, with application centered on the (1920,1080) resolution main screen. The test cases are for the system testing, with the tests visulized. The test cases are testing the user story 1, mainly with the functionalities regarding: 1. add, delete, update client information; choose client to add equipments 2. add, delete equipments; choose equipment to add new run with a pair of CSVs 3. add, delete new run """ import unittest import os import shutil from time import sleep import pyautogui as pg # W0311: bad indentation; E1101:no-member; C0325: Unnecessary parens # pylint: disable=W0311, E1101, C0325 # use the current directory, where the script exists CWD = os.path.dirname(os.path.realpath(__file__)) class TestUserStory1(unittest.TestCase): """The user story 1 related system testing Args: unittest ([type]): [The default testing module from Python] """ @classmethod def setUpClass(self): """ Create or replace previous folder """ try: folder = os.getcwd() + "\\US01 Fail" shutil.rmtree(folder) except FileNotFoundError: print("[There's no such directory]") try: folder = os.getcwd() + "\\US01 Success" shutil.rmtree(folder) except FileNotFoundError: print("[There's no such directory]") try: folder = os.getcwd() + "\\US01" shutil.rmtree(folder) except FileNotFoundError: print("[There's no such directory]") try: self.cwd = os.getcwd() # for printing the current directory # print(self.cwd) os.mkdir("US01") os.chdir("US01") # cd to the directory for saving screenshots self.storage = '%s/' % os.getcwd() # escape the cwd string except: print("[Something is wrong when creating the directory]") @classmethod def tearDownClass(self): """ End the test, determine if tests succeed or fail Then, rename the folder. """ file_list = os.listdir() # print(file_list) # iterate through the filename string, if there's a keyword "fail", rename the folder for filename in file_list: if "fail" in filename: # print("Some tests failed") os.chdir("..") os.rename("US01", "US01 Fail") return os.chdir("..") os.rename("US01", "US01 Success") # print("All tests passed") def test_a_add_new_client(self): ''' add a new client ''' try: # The pyautogui doesn't recognize the pop up window -> use the coordination btn_add_new_client = pg.locateOnScreen( os.path.join(CWD, 'screenshot' ,'main_win' ,'add_new_client.png'), grayscale=False, confidence=.9) pg.moveTo(btn_add_new_client) pg.click() except: print("[There's no such button matching the picture]") raise # add a new client try: pg.moveTo(942, 464, 0.6) # cal number pg.click() pg.write("CAL00004") pg.moveTo(942, 502, 0.6) # client name pg.click() pg.write("Test client name") pg.moveTo(942, 540, 0.6) # address 1 pg.click() pg.write("Test client address1") pg.moveTo(942, 577, 0.6) # address 2 pg.click() pg.write("Test client address2") pg.moveTo(942, 634, 0.6) pg.click() except: print("[There's somthing wrong]") # locate the picture to see whether it exists try: pg.locateOnScreen(os.path.join(CWD,'screenshot', 'main_win', 'cal_CAL0004.png')) # succeeds, screenshot the application try: pg.screenshot( os.path.join(CWD,'US01', 'test add_new_client success .png'), region=(520, 127, (1405-520), (870-127)) ) except: print("[Fail to locate the folder]") except: print("[Fail to find the picture or add new client function fails]") pg.screenshot( os.path.join(CWD,'US01', 'test add_new_client success .png'), region=(520, 127, (1405-520), (870-127)) ) raise def test_b_add_equipment(self): ''' add an equipment, the information show up on GUI screen correctly''' # choose a client to add an equipment try: pg.moveTo(632, 487, 0.7) pg.click() btn_choose_client = pg.locateOnScreen( os.path.join(CWD, 'screenshot' ,'main_win' ,'choose_client.png'), grayscale=False, confidence=.9) pg.moveTo(btn_choose_client) pg.click() except: print("[Fail to find the picture or choose function fails]") raise # move to the button try: btn_add_new_equipment = pg.locateOnScreen( os.path.join(CWD, 'screenshot' ,'main_win_info' ,'info_add_new_equipment.png'), grayscale=False, confidence=.9) pg.moveTo(btn_add_new_equipment) pg.click() except: print("[Fail to find the picture or add new equipment function fails]") raise # finishing adding the equipment try: pg.moveTo(947, 473, 0.7) pg.click() pg.write("1234") pg.moveTo(999, 513, 0.7) pg.click() pg.write("test mode") pg.moveTo(962, 540, 0.7) # submit pg.click() except: print("[Fail to find the picture or add new equipment function fails]") raise try: pg.locateOnScreen(os.path.join(CWD, 'screenshot', 'main_win_info', 'info_id.png')) # print(result) # if successful, would print out the box area try: pg.screenshot( os.path.join(CWD,'US01', 'test add_new_equipemnt success .png'), region=(520, 127, (1405-520), (870-127)) ) except: print("[Fail to locate the folder]") except: print("[Fail to find the picture or add new equipment function fails]") pg.screenshot( os.path.join(CWD,'US01', 'test add_new_equipemnt fail .png'), region=(520, 127, (1405-520), (870-127)) ) raise def test_c_add_new_run(self): ''' add a pair of files to a run, timestamp marked, information on screen ''' # check the equipment info correct or not try: pg.locateOnScreen( os.path.join(CWD, 'screenshot', 'main_win', 'cal_CAL0004.png'), grayscale=False, confidence = .7 ) except: raise("[CAL Number incorrect, or cannot locate the picture]") try: pg.locateOnScreen( os.path.join(CWD, 'screenshot', 'main_win_info', 'info_client_name.png'), grayscale=False, confidence = .7 ) except: raise("[client name incorrect, or cannot locate the picture]") try: pg.locateOnScreen( os.path.join(CWD, 'screenshot', 'main_win_info', 'info_serial.png'), grayscale=False, confidence = .7 ) except: raise("[serial number incorrect, or cannot locate the picture]") try: pg.locateOnScreen( os.path.join(CWD, 'screenshot', 'main_win_info', 'info_id.png'), grayscale=False, confidence = .7 ) except: raise("[id incorrect, or cannot locate the picture]") # if all data correctly shown on the form, choose an equipment to add new run try: pg.moveTo(604, 606, 0.7) pg.click() btn_choose_equipment = pg.locateOnScreen( os.path.join(CWD, 'screenshot' ,'main_win_info' ,'info_choose_equipment.png'), grayscale=False, confidence=.9) pg.moveTo(btn_choose_equipment) pg.click() except: print("[Fail to find the picture or choose equipment function fails]") raise # go on testing the add new run functions try: btn_add_new_run = pg.locateOnScreen( os.path.join(CWD, 'screenshot', 'main_win_equip', 'equip_add_new_run.png'), grayscale=False, confidence = .9 ) pg.moveTo(btn_add_new_run) pg.click() except: raise("cannot locate the button add new run") # check the submit is successful try: pg.moveTo(674, 470, 0.7) # client file pg.click() pg.moveTo(977, 560, 0.7) # file pg.click() pg.moveTo(1281, 912, 0.7) # open pg.click() pg.moveTo(669, 539, 0.7) # lab file pg.click() pg.moveTo(907, 589, 0.7) # file pg.click() pg.moveTo(1281, 912, 0.7) pg.click() pg.moveTo(967, 601, 0.7) #submit pg.click() pg.locateOnScreen( os.path.join(CWD, 'screenshot', 'main_win', 'cal_CAL0004.png'), grayscale=False, confidence = .7 ) try: pg.screenshot( os.path.join(CWD,'US01', 'test add_new_run success .png'), region=(520, 127, (1405-520), (870-127)) ) except: print("[Fail to locate the folder]") except: pg.screenshot( os.path.join(CWD,'US01', 'test add_new_run fail .png'), region=(520, 127, (1405-520), (870-127)) ) raise("[CAL Number incorrect, or cannot locate the picture, or submit fails]") def test_d_delete_run(self): ''' delete a run in the equipment page ''' try: pg.moveTo(685, 568, 0.7) # row data pg.click() btn_del = pg.locateOnScreen( os.path.join(CWD, 'screenshot', 'main_win_equip', 'equip_del_run.png'), grayscale=False, confidence = .9 ) pg.moveTo(btn_del) pg.click() pg.moveTo(933, 534, 0.7) # confirm delete the run pg.click() # if cannot find the data id, meaning the data has been deleted successfully # directly screenshot the data id for scanning try: # data data_x = 543 data_y = 555 pg.screenshot( os.path.join(CWD, 'screenshot', 'main_win_equip', 'equip_data.png'), region=( data_x, data_y, (817 - data_x), (587 - data_y) ) ) # print(data) except: print("[Saving file failed]") sleep(1) # prepare for picture locating try: data = pg.locateOnScreen( os.path.join(CWD, 'screenshot', 'main_win_equip', 'equip_data.png'), grayscale=False, ) if data is None: print("[Data successfully deleted]") sleep(1) # pop window image get screenshot pg.screenshot( os.path.join(CWD,'US01', 'test_delete_run success .png'), region=(520, 127, (1405-520), (870-127)) ) else: print("[Data deletion failed]") pg.screenshot( os.path.join(CWD,'US01', 'test_delete_run fail .png'), region=(520, 127, (1405-520), (870-127)) ) except: print("[Fail to locate the filepath]") except: pg.screenshot( os.path.join(CWD,'US01', 'test_delete_run fail .png'), region=(520, 127, (1405-520), (870-127)) ) raise("[Data deletion failed]") def test_e_del_client(self): """Return to homepage to delete a client """ try: btn_home = pg.locateOnScreen( os.path.join(CWD, 'screenshot', 'main_win_info', 'info_home.png'), grayscale=False, confidence = .8 ) pg.moveTo(btn_home) pg.click() sleep(1) except: raise("[Fail to find the picture or home function fails]") try: pg.moveTo(669, 484, 0.7) # selecte one client pg.click() pg.moveTo(1235, 387, 0.7) # delete client button, fail to capture the picture pg.click() pg.moveTo(941, 533, 0.7) pg.click() except: raise("[Fail to find the picture delete function fails]") sleep(1) # for the picture locating precision try: image = pg.locateOnScreen( os.path.join(CWD, 'screenshot', 'main_win', 'cal_CAL0004.png'), grayscale=False, confidence = .9 ) # if image cannot be found, it would be None; otherwise screenshot the failure if image is None: print("[The client has been deleted successfully]") try: pg.screenshot( os.path.join(CWD,'US01', 'test_del_client success .png'), region=(520, 127, (1405-520), (870-127)) ) except: print("[Fail to locate the folder]") else: print("[Fail to delete the client, or the picture detection fail]") pg.screenshot( os.path.join(CWD,'US01', 'test_del_client fail .png'), region=(520, 127, (1405-520), (870-127)) ) except: print("[Fail to locate the filepath]") # test the client update button -> manully, successful if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestUserStory1) unittest.TextTestRunner(verbosity=2).run(suite) <file_sep>/gui_testing/test_US03.py """ The test file need to be run inside the gui_testing directory, with application centered on the (1920,1080) resolution main screen. The test cases are for the system testing, with the tests visulized. The test cases are testing the user story 3, mainly with the functionalities regarding: 1. The data is correctly saved. 2. The data shows up when open the application next time. """ import unittest import os import shutil from time import sleep import pyautogui as pg import test_US01 # W0311: bad indentation; E1101:no-member; C0325: Unnecessary parens # pylint: disable=W0311, E1101, C0325 # use the current directory, where the script exists CWD = os.path.dirname(os.path.realpath(__file__)) class TestUserStory3(unittest.TestCase): """The user story 3 related system testing Args: unittest ([type]): [The default testing module from Python] """ @classmethod def setUpClass(self): try: folder = os.getcwd() + "\\US03 Fail" shutil.rmtree(folder) except: print("[There's no such directory]") try: folder = os.getcwd() + "\\US03 Success" shutil.rmtree(folder) except: print("[There's no such directory]") try: folder = os.getcwd() + "\\US03" shutil.rmtree(folder) except: print("[There's no such directory]") try: self.cwd = os.getcwd() # for printing the current directory # print(self.cwd) os.mkdir("US03") os.chdir("US03") # cd to the directory for saving screenshots self.storage = '%s/' % os.getcwd() # escape the cwd string except: print("[Something is wrong when creating the directory]") @classmethod def tearDownClass(self): file_list = os.listdir() # print(file_list) # iterate through the filename string, if there's a keyword "fail", rename the folder for filename in file_list: if "fail" in filename: # print("Some tests failed") os.chdir("..") os.rename("US03", "US03 Fail") return os.chdir("..") os.rename("US03", "US03 Success") def test_a_keep_client_data(self): """Add a client, a equipment, and a run, information kept Before the test, the folder should be brought to the background. The mouse position might need adjustment. See gif illustration. """ test_US01.TestUserStory1.test_a_add_new_client(self) test_US01.TestUserStory1.test_b_add_equipment(self) test_US01.TestUserStory1.test_c_add_new_run(self) # screenshot the run id for opencv detection later # data try: data_x = 543 data_y = 555 pg.screenshot( os.path.join(CWD, 'screenshot', 'main_win_equip', 'equip_data.png'), region=( data_x, data_y, (817 - data_x), (587 - data_y) ) ) except: print("[Saving file failed]") # the task need to locate the folder to re-open the application again pg.moveTo(1360, 150, 0.7) # cross tab to close the application pg.click() pg.moveTo(906, 537, 0.7) # yes tab pg.click() sleep(1) pg.moveTo(1332, 581, 0.7) # empty place in the folder pg.click() # focus in the folder pg.moveTo(370, 840, 0.7) # where the application in the folder pg.doubleClick() # TODO: it needs approximately 15-30 seconds to open the application in my computer sleep(35) # the application should pop up and focused try: cal_num = pg.locateOnScreen(os.path.join(CWD,'screenshot', 'main_win', 'cal_CAL0004.png')) print(f"The cal num position: {cal_num}") except: print("[Fail to locate the picture, or the client information missing]") raise # choose client try: pg.moveTo(632, 487, 0.7) pg.click() btn_choose_client = pg.locateOnScreen( os.path.join(CWD, 'screenshot' ,'main_win' ,'choose_client.png'), grayscale=False, confidence=.9) pg.moveTo(btn_choose_client) pg.click() except: print("[Fail to find the picture or choose function fails]") raise # choose equipment try: pg.moveTo(604, 606, 0.7) pg.click() btn_choose_equipment = pg.locateOnScreen( os.path.join(CWD, 'screenshot' ,'main_win_info' ,'info_choose_equipment.png'), grayscale=False, confidence=.9) pg.moveTo(btn_choose_equipment) pg.click() except: print("[Fail to find the picture or choose equipment function fails]") raise sleep(1) # prepare for picture locating try: run_data = pg.locateOnScreen( os.path.join(CWD, 'screenshot', 'main_win_equip', 'equip_data.png'), grayscale=False, ) print(f"The run data position: {run_data}") except: print("[Fail to locate the picture, or equipment runs data missing]") try: pg.screenshot( os.path.join(CWD,'US03', 'test_a_keep_client_data success .png'), region=(520, 127, (1405-520), (870-127)) ) except: pg.screenshot( os.path.join(CWD,'US03', 'test_a_keep_client_data fail .png'), region=(520, 127, (1405-520), (870-127)) ) # the last step, delete the client test_US01.TestUserStory1.test_e_del_client(self) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestUserStory3) unittest.TextTestRunner(verbosity=2).run(suite) <file_sep>/README.md DC-Boxjelly ===================== DC-Boxjelly Private Github Repository - [DC-Boxjelly](#dc-boxjelly) - [Project Description](#project-description) - [Run from source code](#run-from-source-code) - [Features](#features) - [Documentation](#documentation) - [Specify python version](#specify-python-version) - [How to develop (Use command line to do the following process)](#how-to-develop-use-command-line-to-do-the-following-process) - [Interactive development](#interactive-development) - [UI development](#ui-development) - [Publish](#publish) - [File structure](#file-structure) - [System Requirements](#system-requirements) - [Technologies Used](#technologies-used) - [Setup Guide](#setup-guide) - [Testing](#testing) - [Release History](#release-history) - [Attribution](#attribution) ## Project Description This repository contains the source code of Digital Certification (Boxjelly Team), which supports management of MEX measurement and report generating. The reports can be viewed in the software as well as exported as PDF files. ## Run from source code - To directly run the program from source code, please use the `bat` script in project root. - Run `install.bat` to install dependencies through pip. - Run `run.bat` to start the program. ## Features - The storage of MEX measurement raw files as well as their CAL jobs and equipments. - Inputting and viewing of the files and their meta data (date, client information, etc.) - Comparing and analysing MEX data. - Generating PDF certification for MEX data. ## Documentation This section contains the documentation used in developing the software. ### Specify python version - If you want to do development in specify python version, please specify it in `pipenv`. - For example, instead of `pipenv sync`, use `pipenv sync --python 3.6`. - All pipenv commands need to add `--python x.x` switch. ### How to develop (Use command line to do the following process) - Install [pipenv](https://pipenv.pypa.io/en/latest/) - Run `pipenv sync --dev` to install dependency (including development dependency) - Run `pipenv shell` to start a shell based on the virtualenv - Then, use whatever shell command you want in the shell - If you want to install any packages, use `pipenv install` instead of `pip install`. - After installing packages, use `pipenv lock -r > requirements.txt` to regenerate requirements file. ### Interactive development - After the steps above, you can use `pipenv run repl` to start an interactive shell in IPython. You can import modules and test them, like `from models import Job`. - If you use repl, modified modules can be reloaded automatically. - For documents about auto reloading, see https://ipython.org/ipython-doc/3/config/extensions/autoreload.html ### UI development - First of all, please ensure that all dependency are install by `pipenv sync` - Run `qt5-tools designer` in pipenv shell or directly use `pipenv run designer` to start a qt designer. - After modifying `.ui` files in `app/gui/resources`, please run `pipenv run gen-resource` to generate `resources.py` file. ### Publish - Please ensure that pipenv is installed. - Run `package.bat` to package the project. - The packaged files are located at `dist` folder. ### File structure An overview of the source code is listed below. Detail documents can be found in each file and directory. - app: Source code for the application - core: core function, data reading and writing - gui: The gui - export: Functions for exporting, such as pdf or digital certification. - main.py: The entry point of the program. - assets: Files that used in publishing - data: Folder that contains jobs and constants - test: unit test files for `app/core` - tools: Utility scripts for developing. ## System Requirements - Microsoft windows - Python (>=3.4) - Microsoft Excel - (For development only) Pipenv ## Technologies Used - Python - Microsoft Excel - Pipenv - PyQt5 - GitHub and Git - openpyxl - xlwings ## Setup Guide See [INSTALL.md](INSTALL.md) ## Testing - To run unit tests, use `pipenv run test` - The gui testing are under `gui_testing` folder. ## Release History See full changelog on [CHANGELOG.md](./CHANGELOG.md) - 11th Oct 2021: Sprint2 - 17th Sep 2021: Sprint1 ## Attribution 1247145 - <NAME> <EMAIL> Product Owner 1070917 - <NAME> <EMAIL> Scrum master 1087943 - <NAME> <EMAIL> Development Environment Lead 1063288 - <NAME> ([@Liu233w](https://github.com/Liu233w)) <EMAIL> Architecture Lead 1044804 - <NAME> <EMAIL> Deployment Lead 1102336 - <NAME> <EMAIL> Quality Lead <file_sep>/gui_testing/record_gif.py """ The record_gif aims for recording the part of the screen automatically during the GUI test. Then, the script ends the recording and convert the video to gif image under the same folder. It's complementary to the GUI user story acceptance criteria tests. The script would record a mp4 format video, and convert it to gif under the same folder. Note: 1. The current solution doesn't record the the mouse position. 2. The video-to-gif convertion need to download the ffmpeg.exe. ( https://ffmpeg.org/download.html) 3. The solution is incomplete. """ import numpy as np import cv2 from PIL import ImageGrab import pyautogui as pg import ffmpy # W0311: bad indentation; E1101:no-member # pylint: disable=W0311, E1101 RECORDING = True FFMPEG_EXE_PATH = r"D:\Master of IT\Semester4\software project\ffmpeg\bin\ffmpeg.exe" # reference: https://www.youtube.com/watch?v=KTlgVCrO7IQ&ab_channel=ibrahimokdadov # the resolution must from bbox width, height below minus its starting point in the out; # otherwise, video cannot be played # TODO: display the mouse cursor while recording TEST_NAME = "test" VIDEO_NAME = TEST_NAME + '.mp4' fourcc = cv2.VideoWriter_fourcc(*'mp4v') # output would be name of the video, video type, frame rate, (resolution) out = cv2.VideoWriter(VIDEO_NAME, fourcc, 8, (1920-520-520, 1000-127-127)) while True: # bbox = (start_x, start_y, (end_x - start_x, end_y - start_y)) # catch the exe window pop up place # TODO: the image here could try pyautogui -> get the mouse position img = ImageGrab.grab(bbox=(520, 127, (1920-520), (1000-127))) img_np = np.array(img) # covert the img_np array's color scheme frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB) # show on the Screen window cv2.imshow("Screen", img_np) # the video would write the frame out.write(frame) # TODO: how to run the script with the test case? # the waitkey should use 1 instead of 0; otherwise cannot record if cv2.waitKey(1) & 0xFF == 27: break out.release() cv2.destroyAllWindows() ff = ffmpy.FFmpeg( global_options=['-y'], executable = FFMPEG_EXE_PATH, # need to download the ffmpeg.exe inputs = {"Test.mp4": None}, outputs = {"Test.gif": None}, ) ff.run() <file_sep>/data/jobs/CAL00001/PTW 30013 5122/meta.ini [DEFAULT] model = PTW 30013 serial = 5122 <file_sep>/CHANGELOG.md # Changelog ## [Sprint2](https://github.com/Johnlky/DC-Boxjelly/releases/tag/Sprint2) ### Added - Added PDF report generating - Added CSV file exporting - Added CSV file altering (re-upload) - Added importing csv file from home window. - Added version control to the constraints file. ### Changed - Improvement on GUI - Made it more readable ### Breaking Changes - Downgrade the python environment version from 3.9 to 3.6. - The development environment (pipenv) is now locked to 3.6 - It supports both 3.6 and 3.9 as runtime environment. ### Testing - Fix GUI testing on Python 3.6 environment. ### Docs - Added operation manual. - Added installation manual. - Added necessary documents to README. ## [Sprint1](https://github.com/Johnlky/DC-Boxjelly/releases/tag/Sprint1) ### Added - Added the storage of Job, Equipment and Run (file system). - Added importing MEX run. - Added viewing and changing metadata of Job, Equipment and Run. - Added MEX analysis calculation - Added MEX analysis charts ### Testing - Added unit tests of backend logic. - Added automatic GUI testing.<file_sep>/app/core/resolvers.py """ This file contains the code to do the calculation. Each resolver receives a model and outputs the calculated result, which can be a model or just a matrix. """ from datetime import date, datetime import pandas as pd import warnings import numpy as np import os import sys import re import matplotlib.pyplot as plt from matplotlib.ticker import StrMethodFormatter from matplotlib.pyplot import cm from app.core.models import constant_file_config warnings.filterwarnings('ignore') class Header_data(): """ the object to store run info data which read from the head of the raw data """ def __init__(self): self.CAL_num = "" self.Client_name = "" self.address_1 = "" self.address_2 = "" self.operator = "" self.serial = "" self.model = "" self.date = "" class Processed_data(): """ the object to store data which read from the raw data """ def __init__(self): self.df_before_mean = None self.df_mean = None self.df_after_mean = None class result_data(): """ Using object to save result in order to avoid too much returned elements """ def __init__(self): self.df_NK = None self.df_leakage = None self.highlight = [] self.X = [] self.df_otherConstant = None class HeaderError(RuntimeError): def __init__(self, arg): self.args = arg def calculator(client, lab): """ This function will calculate one run of NK (calibration coefficient) and the leakage current values. Besides, the coordinate of the leakage value which need to be highlighted is needed so that the front-end will be easy to highlight the cell. :param client: the client raw data path :param lab : the lab raw data path :return : return a object of the result which includes NK dataframe, leakage value dataframe, the coordinate of the leakage value which need to be highlighted (abs(value) > 0.2), the effective energy dataframe (X), and the list of NK (Y). X and Y is used to plot on chart. """ # extract data client_data, duplicate_num = extraction(client) lab_data, _ = extraction(lab) # order the lab beams to make sure that the further calculation will not have issue cats = client_data.df_mean.index.tolist() lab_data.df_mean.reset_index(inplace=True) lab_data.df_mean['Filter'] = pd.CategoricalIndex(lab_data.df_mean['Filter'], ordered=True, categories=cats) lab_data.df_mean.sort_values('Filter', inplace=True) lab_data.df_mean.set_index('Filter', inplace=True) # client calculation part BgdMC1_Before = client_data.df_before_mean['Current1(pA)'].values[0] BgdIC1_Before = client_data.df_before_mean['Current2(pA)'].values[0] MC1 = (client_data.df_mean['Current1(pA)'] - BgdMC1_Before).to_frame('NK') IC1 = (client_data.df_mean['Current2(pA)'] - BgdIC1_Before).to_frame('NK') R1 = (client_data.df_mean['Current2(pA)'] - BgdIC1_Before).to_frame('NK') / (client_data.df_mean['Current1(pA)'] - BgdMC1_Before).to_frame('NK') TM1 = client_data.df_mean['T(MC)'].to_frame('NK') TA1 = client_data.df_mean['T(Air)'].to_frame('NK') # lab calculation part BgdMC2_Before = lab_data.df_before_mean['Current1(pA)'].values[0] BgdIC2_Before = lab_data.df_before_mean['Current2(pA)'].values[0] MC2 = (lab_data.df_mean['Current1(pA)'] - BgdMC2_Before).to_frame('NK') IC2 = (lab_data.df_mean['Current2(pA)'] - BgdIC2_Before).to_frame('NK') R2 = (lab_data.df_mean['Current2(pA)'] - BgdIC2_Before).to_frame('NK') / (lab_data.df_mean['Current1(pA)'] - BgdMC2_Before).to_frame('NK') TM2 = lab_data.df_mean['T(MC)'].to_frame('NK') TS2 = lab_data.df_mean['T(SC)'].to_frame('NK') H2 = lab_data.df_mean['H(%)'].to_frame('NK') # read constant and KK from constant excel file constant = os.path.join(constant_file_config.get_path()) df_constant = pd.read_excel(constant, sheet_name='constant', engine='openpyxl') df_beams = pd.read_excel(constant, sheet_name='Beams', engine='openpyxl') # get ma and WE Ma = df_constant['ma'].values[0] WE = df_constant['WE'].values[0] # reform the KK into the same order as client_data.df_mean so that it will be easy to calculate directly # (do not need to extract the same index to do calculation. We can just calculate on data frame). # get the filter of the first measurement from KK df_beams = df_beams[df_beams.Filter.isin(client_data.df_mean.index)] cats = client_data.df_mean.index[:-duplicate_num] df_beams['Filter'] = pd.CategoricalIndex(df_beams['Filter'], ordered=True, categories=cats) df_beams.sort_values('Filter', inplace=True) # get the filter which measure two times from KK df_beams_duplicate = df_beams[df_beams.Filter.isin(client_data.df_mean.index[:duplicate_num])] cats = client_data.df_mean.index[:duplicate_num] df_beams_duplicate['Filter'] = pd.CategoricalIndex(df_beams_duplicate['Filter'], ordered=True, categories=cats) df_beams_duplicate['Filter'] = [Filter + '*' for Filter in df_beams_duplicate.Filter.tolist()] df_beams_duplicate.sort_values('Filter', inplace=True) # concate the processed beams df_processBeams = pd.concat([df_beams, df_beams_duplicate], axis=0).set_index('Filter') # concat together so that KK will have the same order as client_data.df_mean df_KK = df_processBeams['Product'].to_frame('NK') # Calculating NK NK = R2 * WE * df_KK * ((273.15 + TS2) / (273.15 + TM2)) * (0.995766667 + 0.000045 * H2) / ( Ma * R1 * (273.15 + TA1) / (273.15 + TM1)) NK = round(NK / 1000000, 2) NK.columns = ['NK'] # leakage df_leakage = pd.DataFrame({"Before": [BgdMC1_Before, BgdIC1_Before, BgdMC2_Before, BgdIC2_Before], "After": [client_data.df_after_mean['Current1(pA)'].values[0], client_data.df_after_mean['Current2(pA)'].values[0], lab_data.df_after_mean['Current1(pA)'].values[0], lab_data.df_after_mean['Current2(pA)'].values[0]]}, index=["Monitor 1", "Chamber (client)", "Monitor 2", "Standard (MEFAC)"]) # extract the effective energy for plotting the graph df_energy = df_processBeams['E_eff'].to_frame() # create an object to save result result = result_data() # saving NK result.df_NK = NK # saving leakage result.df_leakage = round(df_leakage, 2) + 0 # +0 to remove -0.0 # get the coordinate which the cell need to be highlighted result.highlight = [(x, y) for x, y in zip(*np.where(abs(result.df_leakage.values) > 0.2))] # saving the graph required data result.X = df_energy['E_eff'].to_frame('E_eff') # save other constant to result result.df_otherConstant = df_processBeams.drop(columns=['Product', 'E_eff']).fillna('') return result def extraction(path): """ This function use to extract the measurement data from the file. :param : path: the path of file :return: return the measurement data which is extracted from the file. Besides, return the number of beams quality which measure two times in order to use in the calculation part """ Backgrounds_num = 0 Measurements_num = 0 df_total = None with open(path, newline='', encoding="ISO-8859-1") as f: for line in f: if 'DATA' in line: break # get the Background number elif 'Backgrounds' in line: Backgrounds_num = int(line.split(',')[2]) # get the measurement number elif 'Measurements' in line: Measurements_num = int(line.split(',')[2]) df_total = pd.read_csv(f) df_total.drop(['kV', 'mA', 'HVLFilter(mm)', 'N', 'P(kPa)', 'Comment'], axis=1, inplace=True) # change the column type to numeric df_total = df_total.apply(pd.to_numeric, errors='ignore') # dataframe of the before xray data df_before = df_total[:Backgrounds_num] # dataframe of the beam data with open xray df_data = df_total[Backgrounds_num:-Backgrounds_num] # check the number of measurement for each beam df_size = df_data.groupby(['Filter']).size().to_frame('count') # seperate the beam which measure two times duplicate_beam = list(df_size[df_size['count'] > Measurements_num].index) df_noDuplicate = df_data[~df_data.Filter.isin(duplicate_beam)] df_duplicate = df_data[df_data.Filter.isin(duplicate_beam)] df_first = df_duplicate[:Measurements_num * len(duplicate_beam)] df_last = df_duplicate[-Measurements_num * len(duplicate_beam):] # put * on the last measurements (which measure two times) of beams' name df_last.Filter = [Filter + '*' for Filter in df_last.Filter.tolist()] # dataframe of the after xray data df_after = df_total[-Backgrounds_num:] # average the data and store to object data = Processed_data() # put the filter which measure two times at the last data.df_mean = pd.concat([df_first.groupby(['Filter']).mean(), df_noDuplicate.groupby(['Filter']).mean(), df_last.groupby(['Filter']).mean()], axis=0) data.df_before_mean = df_before.groupby(['Filter']).mean() data.df_after_mean = df_after.groupby(['Filter']).mean() # return number of duplicate_beam since kk need to know how many beams measure two times return data, len(duplicate_beam) def summary(name_list, result_list): """ This function is used to summary all runs of calibration coefficient. This function can deal with if the runs do not have same beam quality :param name_list : a list of all names of runs. ex: ['run1', 'run2'] :param result_list: a list of all NK of runs :param df_energy : a dataframe of the effective energy :return : return a dataframe of the summary """ # get the first dataframe in order to merge with others df_result = result_list[0].df_NK # merge all results' dataframes into one dataframe for i in range(1, len(result_list)): df_result = pd.merge(df_result, result_list[i].df_NK, left_index=True, right_index=True, how='outer') # give the column name and average the all rows df_result.columns = name_list df_result['Average'] = round(df_result.mean(axis=1), 2) # all results' values divided by the average value for name in name_list: df_result[name + '/Average'] = round(df_result[name] / df_result['Average'], 3).map('{:,.3f}'.format) df_result[name] = df_result[name].map('{:,.2f}'.format) # let the format be consisted in the GUI df_result['Average'] = df_result['Average'].map('{:,.2f}'.format) # deal with effective energy df_energy = result_list[0].X # merge the effective energy with summary df_summary = pd.merge(df_energy, df_result, left_index=True, right_index=True, how='outer') # sort by voltage df_summary['Tube voltage'] = [re.findall(r'\d+', beam)[0] for beam in df_summary.index] df_summary['Tube voltage'] = pd.to_numeric(df_summary['Tube voltage']) # find how many beams have measure two times duplicate_num = len([beam for beam in df_summary.index if '*' in beam]) df_first = df_summary[:-duplicate_num].sort_values(by='Tube voltage') df_second = df_summary[-duplicate_num:].sort_values(by='Tube voltage') df_first_sort = None for voltage in df_first['Tube voltage'].unique(): df_temp = df_first[df_first['Tube voltage'] == voltage] # extract one voltage df_temp.sort_values(by='E_eff', inplace=True) # sort by energy df_first_sort = pd.concat([df_first_sort, df_temp], axis=0) # concate with other voltage df_first_sort['E_eff'] = df_first_sort['E_eff'].apply('{:,.2f}'.format) df_second['E_eff'] = df_second['E_eff'].apply('{:,.2f}'.format) df_summary = pd.concat([df_first_sort, df_second], axis=0) return df_summary.drop(columns='Tube voltage') def pdf_visualization(path, df_summary, df_otherConstant): """ Merge all the constants and NK together. Besides, the data will be placed by voltage and order by effective energy. Finally, it will produce the tables and the pictures based on the dataframe :param df_summary: Dataframe - the summary of the selected runs :param df_otherConstant: Dataframe - the other constants of the beam quality. Since all run will have same beams, only one df_otherConstant needs to be passed :return: Dataframe - will return a dataframe which consist all the constants and NK """ # using dataframe.merge rather than pd.merge is because the index order will be preserved df_merge = df_summary['E_eff'].to_frame('Nominal effective energy [1]').reset_index() df_merge = df_merge.merge(df_otherConstant.reset_index(), how='outer') # merge energy with other constants # merge energy + other constants with NK df_merge = df_merge.merge(df_summary['Average'].to_frame('NK [2]').reset_index(), how='outer').set_index("Filter") # get the voltage for every beam df_merge['Tube voltage'] = [re.findall(r'\d+', beam)[0] for beam in df_merge.index] df_merge['Tube voltage'] = pd.to_numeric(df_merge['Tube voltage']) # Order the column as needs df_merge.index.name = 'Beam code' df_merge = df_merge.iloc[:, [7, 1, 2, 3, 4, 0, 5, 6]] # hard code U % value df_merge['U %'] = 1.4 df_merge = df_merge.apply(pd.to_numeric).fillna('') ################################################### Draw kVp #################################################### color = cm.rainbow(np.linspace(0, 1, len(df_merge['Tube voltage'].unique()))) plt.rcParams["figure.figsize"] = (8, 4) plot1 = plt.figure(1) for voltage, c in zip(df_merge['Tube voltage'].unique(), color): df_temp = df_merge[df_merge['Tube voltage'] == voltage] # extract one voltage plt.plot(df_temp['Tube voltage'], df_temp['NK [2]'], marker='D', label=str(voltage) + ' kVp', c=c) plt.xlabel("kVp", fontweight='bold') plt.ylabel(r'$\bfN_K$ (mGy/nc)', fontweight='bold') plt.grid(axis='y', linestyle='--') plt.legend(ncol=2) plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.1f}')) plot1.savefig(path + r'\kVp.png', bbox_inches='tight', dpi=1200) ################################################### Draw kVp #################################################### ################################################## Draw HVL Al ################################################## plot2 = plt.figure(2) for voltage, c in zip(df_merge['Tube voltage'].unique(), color): df_temp = df_merge[df_merge['Tube voltage'] == voltage] # extract one voltage df_temp = df_temp[~(df_temp['HVL(mm Al)'] == '')] # remove the HVL value which is '' if len(df_temp) == 0: continue plt.plot(np.round(df_temp['HVL(mm Al)'].to_list(), 2), df_temp['NK [2]'], '.-', label=str(voltage) + ' kVp', c=c) plt.xlabel(r'HVL (mm Al)', fontweight='bold') plt.ylabel(r'$\bfN_K$ (mGy/nc)', fontweight='bold') plt.grid(axis='y', linestyle='--') plt.gca().xaxis.set_major_formatter(StrMethodFormatter('{x:,.2f}')) plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.1f}')) plt.legend(ncol=2) plt.rcParams["figure.figsize"] = (8, 4) plot2.savefig(path + r'\HVL_Al.png', bbox_inches='tight', dpi=1200) ################################################## Draw HVL Al ################################################## ################################################## Draw HVL Cu ################################################## plot3 = plt.figure(3) for voltage, c in zip(df_merge['Tube voltage'].unique(), color): df_temp = df_merge[df_merge['Tube voltage'] == voltage] # extract one voltage df_temp = df_temp[~(df_temp['HVL(mm Cu)'] == '')] # remove the HVL value which is '' if len(df_temp) == 0: continue plt.plot(np.round(df_temp['HVL(mm Cu)'].to_list(), 2), df_temp['NK [2]'], '.-', label=str(voltage) + ' kVp', c=c) plt.xlabel(r'HVL (mm Cu)', fontweight='bold') plt.ylabel(r'$\bfN_K$ (mGy/nc)', fontweight='bold') plt.grid(axis='y', linestyle='--') plt.gca().xaxis.set_major_formatter(StrMethodFormatter('{x:,.2f}')) plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.1f}')) plt.legend(ncol=2) plt.rcParams["figure.figsize"] = (8, 4) plot3.savefig(path + r'\HVL_Cu.png', bbox_inches='tight', dpi=1200) plt.close('all') ################################################## Draw HVL Cu ################################################## ################################################## Save to excel ################################################### first_table_num = 40 subset_beams = ['NXA50', 'NXA70', 'NXB100', 'NXC120', 'NXD140', 'NXE150', 'NXF200', 'NXG250', 'NXH280', 'NXH300', 'NXH300*'] df_merge = df_merge.apply(pd.to_numeric, errors='ignore') # change '' to nan so that na_action can work df_merge['Added filter(mm Al)'] = df_merge['Added filter(mm Al)'].map('{:,.1f}'.format, na_action='ignore') df_merge['Added filter(mm Cu)'] = df_merge['Added filter(mm Cu)'].map('{:,.1f}'.format, na_action='ignore') df_merge['HVL(mm Al)'] = df_merge['HVL(mm Al)'].map('{:,.2f}'.format, na_action='ignore') df_merge['HVL(mm Cu)'] = df_merge['HVL(mm Cu)'].map('{:,.2f}'.format, na_action='ignore') df_merge['Nominal air kerma rate'] = df_merge['Nominal air kerma rate'].map('{:,.1f}'.format, na_action='ignore') df_subset = df_merge[df_merge.index.isin(subset_beams)].style.set_properties(**{'text-align': 'center'}) df_merge1 = df_merge.iloc[:first_table_num].style.set_properties(**{'text-align': 'center'}) df_merge2 = df_merge.iloc[first_table_num:].style.set_properties(**{'text-align': 'center'}) table_path = path + r'\pdf_table.xlsx' writer = pd.ExcelWriter(table_path, engine='xlsxwriter') df_subset.to_excel(writer, sheet_name='subset') df_merge1.to_excel(writer, sheet_name='total-1') df_merge2.to_excel(writer, sheet_name='total-2') writer.save() writer.close() ################################################## Save to excel ################################################### def extractionHeader(client_path: str, lab_path: str): """ This function is used to extract the run info data from the file. """ # check run num in file name (Disabled) # client_file_name = client_path.split('//')[-1] # lab_file_name = lab_path.split('//')[-1] # searchObj = re.search( r'Run[0-9]*', client_file_name, re.I) # run = searchObj.group() # if not re.search( run, lab_file_name, re.I): # raise HeaderError("Not the same run") client_data = Header_data() lab_data = Header_data() # read data from header with open(client_path, newline='', encoding="ISO-8859-1") as f: for line in f: if 'DATA' in line: break elif 'CAL Number' in line: client_data.CAL_num = line.split(',')[2].strip() elif 'Client name' in line: client_data.Client_name = line.split(',')[2].strip() elif 'Address 1' in line: client_data.address_1 = line.split(',')[2].strip() elif 'Address 2' in line: client_data.address_2 = line.split(',')[2].strip() elif 'Operator' in line: client_data.operator = line.split(',')[2].strip() elif 'Chamber' in line: chamber = line.split(',')[2].strip() if not re.match(r'(.+) (.+)', chamber): raise HeaderError("Client file does not contains model/serial, please check!") else: client_data.serial = chamber.split()[-1] client_data.model = " ".join(chamber.split()[:-1]) elif 'Date' in line: client_data.date = line.split(',')[2].strip() # client_data.date = datetime.strptime(dateStr, "%m/%d/%Y").date() with open(lab_path, newline='', encoding="ISO-8859-1") as f: for line in f: if 'DATA' in line: break elif 'CAL Number' in line: lab_data.CAL_num = line.split(',')[2].strip() elif 'Client name' in line: lab_data.Client_name = line.split(',')[2].strip() elif 'Address 1' in line: lab_data.address_1 = line.split(',')[2].strip() elif 'Address 2' in line: lab_data.address_2 = line.split(',')[2].strip() elif 'Operator' in line: lab_data.operator = line.split(',')[2].strip() elif 'Chamber' in line: lab_data.model = line.split(',')[2].strip() # data integrity check if client_data.model + client_data.serial == "MEFAC": raise HeaderError("Client file is a MEFAC run, please check!") elif lab_data.model != "MEFAC": raise HeaderError("Lab file is not MEFAC run, please check!") elif client_data.CAL_num == "": raise HeaderError("Client file does not contains CAL num, please check!") elif lab_data.CAL_num == "": raise HeaderError("Lab file does not contains CAL num, please check!") elif client_data.serial == "" or client_data.model == "": raise HeaderError("Client file does not contains model/serial, please check!") # elif not re.match(r"\d{4}", client_data.serial): # raise HeaderError("Invalid chamber in client file, please check!") elif lab_data.CAL_num != client_data.CAL_num: raise HeaderError("CAL num from Client file and Lab file not the same, please check!") return client_data<file_sep>/test/core/test_models.py import datetime from pathlib import Path import unittest import shutil import importlib import time_machine import pytz import filecmp import logging from app.core import definition, models std_out_log = logging.StreamHandler() std_out_log.setLevel(logging.DEBUG) logging.basicConfig(handlers=[std_out_log, ]) class ModelTestBase(unittest.TestCase): def setUp(self) -> None: shutil.rmtree(definition.DATA_FOLDER) # creatate necessary folders importlib.reload(definition) importlib.reload(models) (definition.DATA_FOLDER / '.gitkeep').touch() def assertMetaContent(self, path, value: list): meta = Path(path).read_text().strip().splitlines() self.assertListEqual(meta, value) def assertFileEqual(self, left: Path, right: Path, msg=None): self.assertTrue(left.is_file(), f'{left} should be a file') self.assertTrue(right.is_file(), f'{right} should be a file') self.assertEqual(left.read_bytes(), right.read_bytes(), msg) class TestJob(ModelTestBase): def test_CRUD(self): # assert no jobs self.assertEqual(len(models.Job), 0) # test add for i in range(1, 6): models.Job.make(str(i), client_name=f'Client {i}', client_address_1=f'{i}00 St') # test iter jobs = list(models.Job) # type: ignore self.assertEqual(len(jobs), 5) self.assertEqual(jobs[0].client_name, 'Client 1') self.assertEqual(jobs[0].client_address_1, '100 St') # test get self.assertEqual(models.Job['1'].client_name, 'Client 1') self.assertEqual(models.Job['1'].client_address_1, '100 St') # test delete self.assertEqual(len(models.Job), 5) del models.Job['1'] self.assertEqual(len(models.Job), 4) # test not existing key self.assertRaises(KeyError, lambda: models.Job['7']) # test create existed job self.assertRaises(ValueError, lambda: models.Job.make('2')) def test_set_meta_data(self): j = models.Job.make('1') j.client_name = '<NAME>' j.client_address_1 = 'An address' self.assertEqual(j.client_name, 'A client') self.assertEqual(j.client_address_1, 'An address') self.assertMetaContent('data/jobs/1/meta.ini', [ '[DEFAULT]', 'client_name = A client', 'client_address_1 = An address' ]) del j.client_address_1 self.assertIsNone(j.client_address_1) self.assertMetaContent('data/jobs/1/meta.ini', [ '[DEFAULT]', 'client_name = A client', ]) # test meta dict self.assertDictEqual(j.meta, { 'job_id': '1', 'client_name': '<NAME>', 'client_address_1': None, 'client_address_2': None, }) def test_modify_equipments(self): j = models.Job.make('1') # add j.add_equipment('AAA', '123') # iter for e in j: self.assertEqual(e.model, 'AAA') self.assertEqual(e.serial, '123') # contains self.assertTrue('AAA 123' in j) # len self.assertEqual(len(j), 1) # get e = j['AAA 123'] self.assertEqual(e.model, 'AAA') self.assertEqual(e.serial, '123') # add equipments with same serial j.add_equipment('AAA', '456') self.assertRaises(ValueError, lambda: j.add_equipment('AAA', '456')) # delete del j['AAA 123'] self.assertEqual(len(j), 1) class TestMexRun(ModelTestBase): def test_meta_data(self): # get object job = models.Job.make('CAL0001') equipment = job.add_equipment('AAA', '123') r = equipment.mex.add() self.assertEqual(r.id, 1) # write meta data r.operator = 'Random Person' # read meta data self.assertEqual(r.operator, 'Random Person') # meta file lines = Path( 'data/jobs/CAL0001/AAA 123/MEX/1/meta.ini').read_text().strip().splitlines() self.assertEqual(len(lines), 4) self.assertEqual(lines[0], '[DEFAULT]') self.assertRegex(lines[1], r'^added_at = ') self.assertRegex(lines[2], r'^edited_at = ') self.assertEqual(lines[3], 'operator = Random Person') @time_machine.travel(datetime.datetime(2021, 1, 1, 12, 0, 0, tzinfo=pytz.timezone('Australia/Melbourne'))) def test_raw_file(self): TEST_DATA_FOLDER = Path(__file__).parent / '_assert' / 'Data' CLIENT_A_RUN1_CLIENT = TEST_DATA_FOLDER / \ 'CAL00001 Raw ClientA-Run1-Client.csv' CLIENT_A_RUN1_LAB = TEST_DATA_FOLDER / \ 'CAL00001 Raw ClientA-Run1-Lab.csv' EXPORTED_SNAPSHOT = Path(__file__).parent / \ '_assert' / 'snapshots' / 'exported_raw_client.csv' # get object job = models.Job.make('CAL0001') equipment = job.add_equipment('AAA', '123') r = equipment.mex.add() # test client and lab object self.assertEqual(type(r.raw_client), type(r.raw_lab)) # by default, you get None self.assertEqual(r.raw_client.path, None) # test adding file r.raw_client.upload_from(CLIENT_A_RUN1_CLIENT) path = r.raw_client.path assert path is not None self.assertTrue(path.samefile('data/jobs/CAL0001/AAA 123/MEX/1/raw/client.csv'), 'test the raw file path') self.assertFileEqual(path, CLIENT_A_RUN1_CLIENT, 'test file content') # test modifying meta data self.assertEqual(r.IC_HV, '-250') self.assertEqual(r.measured_at, '2021-02-12') self.assertEqual(r.operator, '<NAME>') # test exporting r.raw_client.export_to(Path('data/test_exported.csv')) self.assertFileEqual( Path('data/test_exported.csv'), EXPORTED_SNAPSHOT) # test deleting r.raw_client.remove() self.assertFalse( Path('data/jobs/CAL0001/AAA 123/MEX/1/raw/client.csv').exists() ) self.assertIsNone(r.raw_client.path) # test uploading lab raw data, it does not update meta data r.raw_lab.upload_from(CLIENT_A_RUN1_LAB) path = r.raw_lab.path assert path is not None self.assertEqual(r.IC_HV, '-250') # test import raw file with [DC_META] section r.raw_client.upload_from(EXPORTED_SNAPSHOT) r.raw_client.export_to(Path('data/test_exported.csv')) self.assertFileEqual( Path('data/test_exported.csv'), EXPORTED_SNAPSHOT) class TestConstantFile(ModelTestBase): @time_machine.travel(datetime.datetime(2021, 1, 1, 12, 0, 0, tzinfo=pytz.timezone('Australia/Melbourne'))) def test_CRUD(self): # assert no constants self.assertEqual(len(models.ConstantFile), 0) # read non-existing constant self.assertRaises(KeyError, lambda: models.ConstantFile[1]) # create new constant and assert constant = models.ConstantFile.make() self.assertEqual(constant.id, 1) self.assertTrue(constant.path.samefile( 'data/constants/1/constant.xlsx')) self.assertTrue(filecmp.cmp( constant.path, definition.TEMPLATE_CONSTANT_FILE)) self.assertEqual(constant.added_at, '2021-01-01T13:20:00+11:00') self.assertIsNone(constant.note) # assert query self.assertEqual(len(models.ConstantFile), 1) self.assertTrue(1 in models.ConstantFile) self.assertEqual(models.ConstantFile[1].id, 1) for a in models.ConstantFile: self.assertEqual(a.id, 1) # assert delete del models.ConstantFile[1] # delete not existing object def rm(): del models.ConstantFile[1] self.assertRaises(KeyError, rm) def test_default(self): # no default at start self.assertIsNone(models.constant_file_config.default_id) self.assertIsNone(models.constant_file_config.default) # set a default constent file f = models.ConstantFile.make() models.constant_file_config.default_id = f.id self.assertMetaContent('data/constants/meta.ini', [ '[DEFAULT]', 'default = 1', ]) # get default constant default = models.constant_file_config.default self.assertIsNotNone(default) self.assertEqual(default.id, 1) # type: ignore # file path self.assertTrue(models.constant_file_config.get_path() .samefile('data/constants/1/constant.xlsx')) # delete the file f.delete() self.assertIsNone(models.constant_file_config.default) self.assertMetaContent('data/constants/meta.ini', [ ]) # file path self.assertTrue(models.constant_file_config.get_path() .samefile('app/core/template_constant.xlsx')) # set a wrong default id models.constant_file_config.default_id = '42' # but it still reads None self.assertIsNone(models.constant_file_config.default) # file path self.assertTrue(models.constant_file_config.get_path() .samefile('app/core/template_constant.xlsx')) if __name__ == '__main__': unittest.main() <file_sep>/Pipfile [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] matplotlib = "*" portalocker = "*" pyqt5 = "*" pyqtgraph = "*" pandas = "*" numpy = "*" pyinstaller = "*" openpyxl = "*" jinja2 = "*" xlsxwriter = "==3.0.1" xlwings = "*" comtypes = "*" [dev-packages] autopep8 = "*" ipython = "*" pyqt5-tools = "*" time-machine = "*" [require] python_version = "3.6" [scripts] repl = "python app/repl.py" test = "python -m unittest discover" main = "python -m app.main" designer = "qt5-tools designer" gen-resource = "pyrcc5 app/gui/resources.qrc -o app/gui/resources.py" <file_sep>/data/jobs/CAL00004/PTW 30013 6533/meta.ini [DEFAULT] model = PTW 30013 serial = 6533 <file_sep>/gui_testing/screenshot/grab_main_win_equip.py """ The screen resolution is (1920,1080). The script aims for cropping the images from the application main window, run page. The reason using the pyautogui instead of creenshot using Windows 10 bulit-in snip & sketch tools is that the image might not be recognized by opencv. """ import os import pyautogui as pg # W0311: bad indentation; E1101:no-member; C0325: Unnecessary parens; C0103: upper case naming # pylint: disable=W0311, E1101, C0325, C0103 try: os.mkdir('main_win_equip') except OSError: print("[The directory already existed]") # for buttons, which are aligned horizontally start_y = 454 end_y = 506 # button analyze btn_analyze_x = 536 btn_analyze_y = start_y pg.screenshot( 'main_win_equip/equip_analyze.png', region=( btn_analyze_x, btn_analyze_y, (747 - btn_analyze_x), (end_y - btn_analyze_y) ) ) # button add new run btn_add_run_x = 747 btn_add_run_y = start_y pg.screenshot( 'main_win_equip/equip_add_new_run.png', region=( btn_add_run_x, btn_add_run_y, (958 - btn_add_run_x), (end_y - btn_add_run_y) ) ) # button delete run btn_del_run_x = 958 btn_del_run_y = start_y pg.screenshot( 'main_win_equip/equip_del_run.png', region=( btn_del_run_x, btn_del_run_y, (1169 - btn_del_run_x), (end_y - btn_del_run_y) ) ) # button return btn_return_x = 1169 btn_return_y = start_y pg.screenshot( 'main_win_equip/equip_return.png', region=( btn_return_x, btn_return_y, (1380 - btn_return_x), (end_y - btn_return_y) ) ) <file_sep>/app/core/mixins.py from pathlib import Path import configparser import shutil from typing import Any, Callable, Dict, Optional from os import rename from .definition import META_FILE_NAME from .utils import ensure_folder class WithMetaMixin: """ A mixin representing a model contains a meta file It assume that the object contains a field called _folder, which represents the folder the model has. """ _folder: Path @property def _meta(self) -> Path: """ Get the path of the meta file """ return self._folder / META_FILE_NAME def _meta_exists(self) -> bool: """ Check if the meta file exists """ return self._meta.is_file() def _ensure_folder_with_meta(self, initial: Optional[Dict[str, str]] = None) -> bool: """ Ensure the folder exists, if not, create the folder with an empty meta file. @initial: a dict contains the initial meta data if a new meta file is created Returns True if the folder already exists. """ if ensure_folder(self._folder): assert self._meta_exists() return True else: self._meta.touch() if initial: for k, v in initial.items(): self._set_meta(k, v) return False def _get_meta(self, field: str, section='DEFAULT') -> Optional[str]: """ Return a dict represents the meta data of the folder """ config = configparser.ConfigParser() config.read(self._meta) return config.get(section, field, fallback=None) def _set_meta(self, field: str, value: str, section='DEFAULT'): """ Set a value into the meta data field. If it is setted as None, it is equivalent to invoking `_del_meta` """ if value is None: self._del_meta(field, section) config = configparser.ConfigParser() config.read(self._meta) try: config.set(section, field, value) except configparser.NoSectionError: config[section] = {field: value} with open(self._meta, 'w') as fr: config.write(fr) def _del_meta(self, field: str, section='DEFAULT'): """ Remove a field from meta """ config = configparser.ConfigParser() config.read(self._meta) try: config.remove_option(section, field) with open(self._meta, 'w') as fr: config.write(fr) except configparser.NoSectionError: pass def meta_property(name: str, docstring: Optional[str] = None, *, readonly=False, setter: Callable[[Any], str] = None) -> property: """ Create a property that reads and writes a field in meta file. Please ensure the class has `WithMetaMixin` @readonly: if it is True, only reading is available @setter: if it is provided, use it to transform input before writing meta data Usage: ``` class MyModel(WithMetaMixin, object): def __init__(self, id): ... self.my_field = self._make_meta_property(self, 'my_field', 'A description of my_field') # in other code m = MyModel(1) m.my_field = '123' # write print(m.my_field) # read, if field does not exist, return None del m.my_field # clear the field ``` """ def getx(self): return self._get_meta(name) def setx(self, value): if setter: value = setter(value) return self._set_meta(name, value) def delx(self): return self._del_meta(name) if readonly: return property(getx, doc=docstring) else: return property(getx, setx, delx, docstring) def assign_properties(obj, kwargs: Dict[str, str]): for key, value in kwargs.items(): setattr(obj, key, value) class DeleteFolderMixin: """ A mixin that adds operation to delete the folder this instance represents. The class must contains a _folder field. """ _folder: Path def delete(self): """ Remove the model, this process cannot be undone. After calling this method, invoking other methods are invalid. If folder cannot be deleted (maybe due to the permission error), raise OSError """ delete_path = str(self._folder.absolute()) + '.delete' rename(self._folder, delete_path) shutil.rmtree(delete_path) <file_sep>/app/gui/utils.py from datetime import datetime from PyQt5.QtCore import QFile, QIODevice from PyQt5.QtWidgets import QMainWindow from PyQt5.uic import loadUi import sys import pandas as pd import os import logging from app.core.models import Job, Equipment, ConstantFile import dateutil.parser logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) def loadUI(str, window): ui_file_name = str ui_file = QFile(ui_file_name) if not ui_file.open(QIODevice.ReadOnly): logger.critical(f"Cannot open {ui_file_name}: {ui_file.errorString()}") sys.exit(-1) loadedWindow = loadUi(ui_file, window) ui_file.close() if not loadedWindow: #print(loader.errorString()) sys.exit(-1) return loadedWindow def getHomeTableData(): ''' Return client info data as Dataframe ''' # data = { # 'status': [False, False, False], # 'CAL Number': ['CAL 001', 'CAL 002', 'CAL 003'], # 'Client Name': ['Amy', 'Jay', 'Jack'], # 'Clinet Address': ['8 Leonerd Street', '12 Collins Street', '5 Sutherland Street'] # } data = { 'CAL Number': [], 'Client Name': [] } for job in Job: data['CAL Number'].append(job.id), data['Client Name'].append(job.client_name), # data['Clinet Address'].append(str(job.client_address_1)+' '+str(job.client_address_2)), # data['Client Address'].append(''), df = pd.DataFrame(data) return df def getEquipmentsTableData(job: Job): ''' Return equipments data as Dataframe ''' #job = Job[jobID] data = { 'Serial Num': [], 'Make/Model': [], 'ID': [] } for equip in job: data['Make/Model'].append(equip.model), data['Serial Num'].append(equip.serial), data['ID'].append(equip.id), df = pd.DataFrame(data) return df def getRunsTableData(equip: Equipment): ''' Return runs data as Dataframe ''' #equip = Job[jobID][equipID] data = { 'ID': [], # 'Added Time': [], 'Edited Time': [], 'Measurement Date': [], 'Operator': [], } for run in equip.mex: data['ID'].append(run.id), # data['Added Time'].append(converTimeFormat(run.added_at)), data['Edited Time'].append(converTimeFormat(run.edited_at)), data['Measurement Date'].append(converTimeFormat(run.measured_at).split()[0]), data['Operator'].append(run.operator), df = pd.DataFrame(data) return df def getResultData(): data = { "Beam quality": ["NXJ40", "NXJ50"], "E_eff": [40.1, 40.1], "Run1_NK": [33.1, 33.1], "Run2_NK": [33.6, 33.5], "Average": [36.0, 36.0], "Run1/Average": [0.920, 0.920], "Run2/Average": [0.933, 0.933], } return pd.DataFrame(data) def converTimeFormat(time: str): if time: dateTime = dateutil.parser.isoparse(time) return dateTime.strftime('%d-%m-%Y %H:%M:%S') else: return None def getConstantsTableData(): ''' Return contants data as Dataframe ''' data = { 'ID': [], 'Create time': [], 'Description': [], } # insert templete constants data['ID'].append("Template") data['Create time'].append("01-10-2021 00:00:00") data['Description'].append("Templete Constants") # get all other constants obj for constantsFile in ConstantFile: data['ID'].append(constantsFile.id) data['Create time'].append(converTimeFormat(constantsFile.added_at)) if constantsFile.note == None: data['Description'].append("") else: data['Description'].append(constantsFile.note) df = pd.DataFrame(data) return df<file_sep>/gui_testing/README.md # Overview The folder includes the test scripts and the element screenshots. Each script would test the functionalities specified in the sprint one user-story backlog. More details and workflows are specified in the scripts. # Tools There are two main tools used in GUI (graphical user interface) testing. - PyautoGUI The library automates and mimics the user behaviors while using the application. Please see its documentation for more details (https://pyautogui.readthedocs.io/en/latest/). - OpenCV The library detects the cropped images, screenshots and records the screen. Please see its documentation for more details (https://docs.opencv.org/master/). # US0X Success/Fail folder The folders are generated during the tests. According to its test cases, the folder name would be the user story number with the "Success" or "Fail" string. The screenshots inside the folder are evidence for the test cases. # Others - to use one test case only inside a script - py -m unittest test_US01.TestUserStory1.test_e_del_client<file_sep>/gui_testing/test_US07.py """ The UI element names are stored as CSV files in the temp_data folder. Please check the CSV for the specific UI element name on different UI pages. The testing logic is to screenshot the application and get the text, and see if the specific text would appear after the certain action. In the US07, the goal is to generate the PDF with clicks. 1. Testing the homepage routes to the client info page. 2. Testing the client info page to the equipment info page. 3. Testing the equipment info page to the analysis page. 4. Testing the "Generate PDF" button to the saving window. 5. Testing the required output PDF name format. """ import pyautogui as pq from utils import UI import utils import pandas as pd import unittest import os import shutil from time import sleep # W0311: bad indentation; E1101:no-member; C0325: Unnecessary parens # pylint: disable=W0311, E1101, C0325 # use the current directory, where the script exists CWD = os.path.dirname(os.path.realpath(__file__)) class TestUserStory7(unittest.TestCase): """The user story 7 related system testing Args: unittest ([type]): [The default testing module from Python] """ @classmethod def setUpClass(self): """ Create or replace previous folder """ try: folder = os.getcwd() + "\\US07 Fail" shutil.rmtree(folder) except FileNotFoundError: print("[There's no such directory]") try: folder = os.getcwd() + "\\US07 Success" shutil.rmtree(folder) except FileNotFoundError: print("[There's no such directory]") try: folder = os.getcwd() + "\\US07" shutil.rmtree(folder) except FileNotFoundError: print("[There's no such directory]") try: self.cwd = os.getcwd() # for printing the current directory # print(self.cwd) os.mkdir("US07") os.chdir("US07") # cd to the directory for saving screenshots self.storage = '%s/' % os.getcwd() # escape the cwd string except: print("[Something is wrong when creating the directory]") @classmethod def tearDownClass(self): """ End the test, determine if tests succeed or fail Then, rename the folder. """ file_list = os.listdir() # print(file_list) # iterate through the filename string, if there's a keyword "fail", rename the folder for filename in file_list: if "fail" in filename: # print("Some tests failed") os.chdir("..") os.rename("US07", "US07 Fail") return os.chdir("..") os.rename("US07", "US07 Success") def test_a_gen_pdf(self): # homepage utils.screenshot_app_window('homepage') utils.get_text('homepage') homepage_ui = UI('../temp_data/homepage.csv', 'string') cli_A_x, cli_A_y = homepage_ui.get_pos("ClientA", "app") select_x, select_y = homepage_ui.get_pos("Select Client", "app") pq.moveTo(cli_A_x+1, cli_A_y+1,1) pq.click() pq.moveTo(select_x+1, select_y+1, 1) pq.click() # route to the next page # route to client_info page # assert if the string 5122 on the screen try: utils.screenshot_app_window('client_info') utils.get_text('client_info') client_ui = UI('../temp_data/client_info.csv', 'string') lst = utils.get_string_list(client_ui) self.assertTrue("5122" in lst) pq.screenshot( os.path.join(CWD,'US07', 'to the client_page success .png'), region=(utils.APP_START_X, utils.APP_START_Y, (1446-utils.APP_START_X), (888-utils.APP_START_Y)) ) except: print("[Assertion error, the page doesn't route]") pq.screenshot( os.path.join(CWD,'US07', 'to the client_page fail .png'), region=(utils.APP_START_X, utils.APP_START_Y, (1446-utils.APP_START_X), (888-utils.APP_START_Y)) ) raise # client_info page serial_x, serial_y = client_ui.get_pos("5122", "app") choose_x, choose_y = client_ui.get_pos("Choose Equipment", "app") pq.moveTo(serial_x+1, serial_y+1, 1) pq.click() pq.moveTo(choose_x+1, choose_y+1, 1) pq.click() # route the next page # route to the equipment info # assert if the string Duncan Butler on the screen try: utils.screenshot_app_window('equipment_info') utils.get_text('equipment_info') equipment_ui = UI('../temp_data/equipment_info.csv', 'string') lst = utils.get_string_list(equipment_ui) self.assertTrue("Duncan Butler" in lst) pq.screenshot( os.path.join(CWD,'US07', 'to the equipment_page success .png'), region=(utils.APP_START_X, utils.APP_START_Y, (1446-utils.APP_START_X), (888-utils.APP_START_Y)) ) except: print("[Assertion error, the page doesn't route]") pq.screenshot( os.path.join(CWD,'US07', 'to the equipment_page fail .png'), region=(utils.APP_START_X, utils.APP_START_Y, (1446-utils.APP_START_X), (888-utils.APP_START_Y)) ) raise # equipment_info page operator_x, operator_y = equipment_ui.get_pos("Duncan Butler", "app") analyse_x, analyse_y = equipment_ui.get_pos("Analyse Run", "app") pq.moveTo(operator_x+1, operator_y+1, 1) pq.click() pq.moveTo(analyse_x+1, analyse_y+1, 1) pq.click() sleep(2) # route to the analysis page # assert the string Generate PDF on the screen try: utils.screenshot_app_window('analysis', utils.ANA_START_X, utils.ANA_START_Y, 1820, 948) utils.get_text('analysis') analysis_ui = UI('../temp_data/analysis.csv', 'string') lst = utils.get_string_list(analysis_ui) self.assertTrue("Generate PDF" in lst) pq.screenshot( os.path.join(CWD,'US07', 'to the analysis_page success .png'), region=(utils.ANA_START_X, utils.ANA_START_Y, (1820-utils.ANA_START_X), (948-utils.ANA_START_Y)) ) except: print("[Assertion error, the page doesn't route]") pq.screenshot( os.path.join(CWD,'US07', 'to the analysis_page fail .png'), region=(utils.ANA_START_X, utils.ANA_START_Y, (1820-utils.ANA_START_X), (948-utils.ANA_START_Y)) ) raise # analysis page gen_pdf_x, gen_pdf_y = analysis_ui.get_pos("Generate PDF", "analysis") pq.moveTo(gen_pdf_x+1,gen_pdf_y+1, 1) pq.click() sleep(2) # route to the saving page # assert the string Save on the screen try: utils.screenshot_app_window('save', utils.SAVE_START_X, utils.SAVE_START_Y, 1250, 675) utils.get_text('save') save_ui = UI('../temp_data/save.csv', 'string') lst = utils.get_string_list(save_ui) self.assertTrue("Save" in lst) pq.screenshot( os.path.join(CWD,'US07', 'to the saving window success .png'), region=(utils.ANA_START_X, utils.ANA_START_Y, (1820-utils.ANA_START_X), (948-utils.ANA_START_Y)) ) except: print("[Assertion error, the page doesn't route]") pq.screenshot( os.path.join(CWD,'US07', 'to the saving window fail .png'), region=(utils.ANA_START_X, utils.ANA_START_Y, (1820-utils.ANA_START_X), (948-utils.ANA_START_Y)) ) raise # save page save_x, save_y = save_ui.get_pos("Save", "save") pq.moveTo(save_x+1, save_y+1, 1) pq.click()
5b00f95480f96673c7343bd7596d1a4c1d230549
[ "Markdown", "TOML", "Python", "INI" ]
46
INI
Johnlky/DC-Boxjelly
dcff949a2d580a9bdbbe62d3891cfe8b835538a2
a599ebce4f74762e282701993dd5ff5005d69c48
refs/heads/main
<repo_name>henrihaka1/gammaEngine<file_sep>/README.md # gammaEngine credits to Cherno for his amazing tutorial series <file_sep>/Sandbox/src/SandboxApp.cpp #include <Gamma.h> class Sandbox : public Gamma::Application { public: Sandbox() { } ~Sandbox() { } }; Gamma::Application* Gamma::CreateApplication() { return new Sandbox(); }<file_sep>/GammaEngine/src/Gamma/Core.h #pragma once #ifdef GM_PLATFORM_WINDOWS #ifdef GM_BUILD_DLL #define GAMMA_API __declspec(dllexport) #else #define GAMMA_API __declspec(dllimport) #endif #else #error Gamma only supports Windows! #endif <file_sep>/GammaEngine/src/Gamma.h #pragma once //For use only by Gamma Applications #include "Gamma/Application.h" //----Entry Point------------- #include "Gamma/EntryPoint.h" //----------------------------<file_sep>/GammaEngine/src/Gamma/EntryPoint.h #pragma once #ifdef GM_PLATFORM_WINDOWS extern Gamma::Application* Gamma::CreateApplication(); int main(int argc, char** argv) { auto app = Gamma::CreateApplication(); app->Run(); delete app; } #endif <file_sep>/GammaEngine/src/Gamma/Application.h #pragma once #include "Core.h" namespace Gamma { class GAMMA_API Application { public: Application(); virtual ~Application(); //methods void Run(); }; //This method needs to be defined in the client Application* CreateApplication(); }
385dbd7e7d83014ce1d537606c2f07710e8cf52b
[ "Markdown", "C", "C++" ]
6
Markdown
henrihaka1/gammaEngine
43d45babfad4d175891b2794330ac4f37a37a270
21be00c8ef545d2753c265ecd9ed97eed98e430a
refs/heads/master
<repo_name>haocoder/recipes<file_sep>/thread/SignalSlotTrivial.h #ifndef MUDUO_BASE_SIGNALSLOTTRIVIAL_H #define MUDUO_BASE_SIGNALSLOTTRIVIAL_H #include <memory> #include <vector> template<typename Signature> class SignalTrivial; template <typename RET, typename... ARGS> class SignalTrivial<RET(ARGS...)> { public: typedef std::function<void (ARGS...)> Functor; void connect(Functor&& func) { functors_.push_back(std::forward<Functor>(func)); } void call(ARGS&&... args) { // gcc 4.6 supports //for (const Functor& f: functors_) typename std::vector<Functor>::iterator it = functors_.begin(); for (; it != functors_.end(); ++it) { (*it)(args...); } } private: std::vector<Functor> functors_; }; #endif // MUDUO_BASE_SIGNALSLOTTRIVIAL_H <file_sep>/algorithm/mergeMaps.cc #include <assert.h> #include <algorithm> #include <iostream> #include <map> #include <string> #include <vector> template<typename C> class MergedIterator { public: explicit MergedIterator(const std::vector<C>& input) { heap_.reserve(input.size()); int i = 0; for (const C& c : input) { if (!c.empty()) heap_.push_back({.iter = c.cbegin(), .end = c.cend(), .idx = i++}); } std::make_heap(heap_.begin(), heap_.end()); } bool done() const { return heap_.empty(); } const typename C::value_type& get() const { assert(!done()); return *heap_.front().iter; } void next() { assert(!done()); std::pop_heap(heap_.begin(), heap_.end()); if (++heap_.back().iter == heap_.back().end) heap_.pop_back(); else std::push_heap(heap_.begin(), heap_.end()); } private: typedef typename C::const_iterator Iterator; struct Item { Iterator iter, end; int idx = 0; // TODO: generalize this using C::value_comp ? bool operator<(const Item& rhs) const { if (iter->first == rhs.iter->first) return idx > rhs.idx; return iter->first > rhs.iter->first; } }; std::vector<Item> heap_; }; int main() { using Map = std::map<int, std::string>; std::vector<Map> maps(4); maps[0][1] = "1.a"; maps[1][1] = "1.b"; maps[2][1] = "1.c"; maps[0][2] = "2.a"; maps[1][3] = "3.b"; maps[2][4] = "4.c"; maps[0][9] = "9.a"; maps[1][8] = "8.b"; maps[2][7] = "7.c"; for (MergedIterator<Map> s(maps); !s.done(); s.next()) { std::cout << s.get().first << " " << s.get().second << "\n"; } } <file_sep>/puzzle/poker/poker.cc #include <algorithm> #include <map> #include <vector> #include <assert.h> #include <stdio.h> // CAUTION: unreadable code struct Card { int rank; // 2 .. 14 : 2 .. 9, T, J, Q, K, A int suit; // 1 .. 4 Card() : rank(0), suit(0) { } }; struct String { char str[16]; }; struct Hand { Card cards[5]; String toString() const { String result; int idx = 0; for (int i = 0; i < 5; ++i) { result.str[idx++] = "0123456789TJQKA"[cards[i].rank]; result.str[idx++] = " CDHS"[cards[i].suit]; result.str[idx++] = ' '; } assert(idx == 15); result.str[14] = '\0'; return result; } }; struct Score { int score; int ranks[5]; Hand hand; bool operator<(const Score& rhs) const { return score < rhs.score || (score == rhs.score && std::lexicographical_compare(ranks, ranks+5, rhs.ranks, rhs.ranks+5)); } }; struct Group { int count; int rank; bool operator<(const Group& rhs) const { return count > rhs.count || (count == rhs.count && rank > rhs.rank); } }; void fillGroups(const int ranks[], Group groups[], int* len) { int idx = -1; int last_rank = 0; for (int i = 0; i < 5; ++i) { if (ranks[i] == last_rank) { ++groups[idx].count; } else { ++idx; ++groups[idx].count; groups[idx].rank = last_rank = ranks[i]; } } *len = idx+1; std::sort(groups, groups+5); } Score getScore(const Hand& hand) { int ranks[5] = { 0, }; bool flush = true; int suit = hand.cards[0].suit; for (int i = 0; i < 5; ++i) { ranks[i] = hand.cards[i].rank; flush = flush && suit == hand.cards[i].suit; } std::sort(ranks, ranks+5); // 'A' is 1 for straight A, 2, 3, 4, 5 if (ranks[0] == 2 && ranks[1] == 3 && ranks[2] == 4 && ranks[3] == 5 && ranks[4] == 14) { ranks[0] = 1; ranks[1] = 2; ranks[2] = 3; ranks[3] = 4; ranks[4] = 5; } Group groups[5] = { { 0, }, }; int group_len = 0; fillGroups(ranks, groups, &group_len); assert(group_len <= 5); bool straight = group_len == 5 && ranks[4] - ranks[0] == 4; /* for (int i = 0; i < group_len; ++i) printf("%d %d, ", groups[i].count, groups[i].rank); printf("\n"); */ int score = 0; if (group_len == 1) score = 9; else if (straight && flush) score = 8; else if (group_len == 2 && groups[0].count == 4) score = 7; else if (group_len == 2 && groups[0].count == 3) score = 6; else if (flush) score = 5; else if (straight) score = 4; else if (group_len == 3 && groups[0].count == 3) score = 3; else if (group_len == 3 && groups[0].count == 2) score = 2; else if (group_len == 4) score = 1; else assert(group_len == 5); Score result = { 0, }; result.score = score; int idx = 0; for (int i = 0; i < group_len; ++i) for (int j = 0; j < groups[i].count; ++j) result.ranks[idx++] = groups[i].rank; assert(idx == 5); result.hand = hand; return result; } Hand formHand(int choose[]) { Hand hand; int c = 0; for (int i = 0; i < 52; ++i) { if (choose[i]) { hand.cards[c].rank = i / 4 + 2; hand.cards[c].suit = i % 4 + 1; ++c; if (c == 5) break; } } assert(c == 5); return hand; } int main() { int choose[52] = { 1, 1, 1, 1, 1, 0, }; int count = 0; std::vector<Score> scores; do { Hand hand(formHand(choose)); //puts(hand.toString().str); Score score = getScore(hand); scores.push_back(score); ++count; } while (std::prev_permutation(choose, choose + 52)); std::sort(scores.begin(), scores.end()); for (auto it = scores.rbegin(); it != scores.rend(); ++it) printf("((%d, [%d, %d, %d, %d, %d]), '%s')\n", it->score, it->ranks[0], it->ranks[1], it->ranks[2], it->ranks[3], it->ranks[4], it->hand.toString().str); } <file_sep>/puzzle/fibonacci.cc // g++ -Wall fibonacci.cc -O2 -lgmp -o fib // Set skip_get_str = true, N = 1,000,000 measured on i7-7600U laptop // linear : 2.60 s // fast : 18.73 ms // faster : 8.12 ms // fastest: 2.78 ms #include <unordered_map> #include <assert.h> #include <gmpxx.h> #include <sys/time.h> const bool skip_get_str = false; double now() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec / 1000000.0; } class FibonacciIterator { public: std::string operator*() const { return fn.get_str(); } FibonacciIterator& operator++() { prev.swap(fn); fn += prev; return *this; } private: mpz_class fn = 1, prev = 0; }; std::string linearFibonacci(int N) { assert(N >= 1); FibonacciIterator iter; // F(1) for (int i = 1; i < N; ++i) { ++iter; } return skip_get_str ? "" : *iter; } // [ a b ] // [ c d ] struct Matrix { Matrix(int x11, int x12, int x21, int x22) : a(x11), b(x12), c(x21), d(x22) { } void operator*=(const Matrix& rhs) { mpz_class x11 = a * rhs.a + b * rhs.c; mpz_class x12 = a * rhs.b + b * rhs.d; mpz_class x21 = c * rhs.a + d * rhs.c; mpz_class x22 = c * rhs.b + d * rhs.d; a.swap(x11); b.swap(x12); c.swap(x21); d.swap(x22); } void square() { operator*=(*this); // TODO: there is one slight faster square algorithm, saving 1 multiplication by reusing b*c. } mpz_class a, b, c, d; }; /* [ 1 1 ] ^ n [F(n+1) F(n) ] [ 1 0 ] = [F(n) F(n-1)] */ std::string fastFibonacci(int N) { assert(N >= 1); Matrix base(1, 1, 1, 0), result(1, 0, 0, 1); int n = N-1; while (n > 1) { if (n % 2 == 1) { result *= base; } base.square(); n /= 2; } result *= base; // TODO: only need to calculate 'a' return skip_get_str ? "" : result.a.get_str(); } /* consider symmetry, the Matrix [a b; c d] has only three independent elements: a b c, because b==c. */ std::string fasterFibonacci(int N) { assert(N >= 1); mpz_class a(1), b(1), d(0), x(1), y(0), z(1), tmp; int n = N-1; while (n > 1) { if (n % 2 == 1) { // [ x y ] [ a b ] // [ y z ] *= [ b d ] tmp = y*b; z = tmp + z*d; y = x*b + y*d; x = x*a + tmp; } tmp = b*b; b = a*b + b*d; d = tmp + d*d; a = a*a + tmp; n /= 2; } tmp = x*a + y*b; return skip_get_str ? "" : tmp.get_str(); } // f(2n) = f(n) * (f(n-1) + f(n+1)) // f(2n+1) = f(n)^2 + f(n+1)^2 class Fib { public: explicit Fib(int N) { cache_[0] = 0; cache_[1] = 1; cache_[2] = 1; cache_[3] = 2; /* cache_[4] = 3; cache_[5] = 5; cache_[6] = 8; cache_[7] = 13; cache_[8] = 21; cache_[9] = 34; */ calc(N); result_ = &cache_[N]; } const mpz_class& get() const { return *result_; } private: void calc(int N) { assert(N >= 0); auto it = cache_.find(N); if (it == cache_.end()) { if (N & 1) { calc(N/2); calc(N/2 + 1); const mpz_class& a = cache_[N/2]; const mpz_class& b = cache_[N/2 + 1]; cache_[N] = a*a + b*b; } else { calc(N/2 - 1); calc(N/2); const mpz_class& a = cache_[N/2 - 1]; const mpz_class& b = cache_[N/2]; cache_[N/2 + 1] = a + b; const mpz_class& c = cache_[N/2 + 1]; cache_[N] = b * (a + c); } } } std::unordered_map<int, mpz_class> cache_; const mpz_class* result_ = nullptr; }; std::string fastestFibonacci(int N) { Fib f(N); return skip_get_str ? "" : f.get().get_str(); } std::string floatFibonacci(int N, int prec) { // prec / N = log2(1+sqrt(5)) - 1 = 0.694242 mpf_class a(5, prec), b; mpf_class s5 = sqrt(a); assert(s5.get_prec() == prec); a = (1 + s5) / 2; b = (1 - s5) / 2; mpf_pow_ui(a.get_mpf_t(), a.get_mpf_t(), N); mpf_pow_ui(b.get_mpf_t(), b.get_mpf_t(), N); mpf_class c = s5 / 5 * (a - b) + 0.5; assert(c.get_prec() == prec); mp_exp_t expo; std::string str = c.get_str(expo); return str.substr(0, expo); } int get_precision(int N, int prec, const std::string& expected) { while (floatFibonacci(N, prec) != expected) { prec += 64; } return prec; } void find_precision() { FibonacciIterator iter; int prec = 64; for (int i = 1; i <= 50000; ++i) { int newprec = get_precision(i, prec, *iter); bool print = (i % 10000 == 0) || newprec != prec; prec = newprec; if (print) printf("%d %d %.5f\n", i, prec, double(prec) / i); ++iter; } } int main(int argc, char* argv[]) { if (argc > 1) { const int N = atoi(argv[1]); std::string result; double start = now(); const int kRepeat = 100; for (int i = 0; i < (skip_get_str ? kRepeat : 1); ++i) { if (argc > 2) { if (argv[2][0] == 'F') { result = fastestFibonacci(N); } else if (argv[2][0] == 'f') { result = fasterFibonacci(N); } else { result = fastFibonacci(N); } } else { result = linearFibonacci(N); } } if (skip_get_str) { printf("%.3f ms\n", (now() - start) * 1000.0 / kRepeat); } else { printf("%s\n", result.c_str()); } } else { printf("Usage: %s number [fFx]\n", argv[0]); FibonacciIterator iter; for (int i = 1; i < 10000; ++i) { if (fastFibonacci(i) != *iter || fasterFibonacci(i) != *iter || fastestFibonacci(i) != *iter || floatFibonacci(i, 6976) != *iter) { printf("ERROR %d\n", i); break; } ++iter; } // find_precision(); // floatFibonacci(1000000, 694272); } } <file_sep>/java/billing/DataFields.java package billing; // FIXME: should be in groovy public class DataFields { public static enum UserField { kUserType, kJoinTime, kIsNewUser, kPackages, kSlips, kDaysServed, } public static enum SlipType { kPhoneCall, kShortMessage, kInternet, } public static enum UserType { kNormal, kVip; public String getRuleName() { return name().substring(1).toLowerCase() + "_user"; } } public static enum PackageType { kNormalUserPhoneCall, kNormalUserShortMessage, kNormalUserInternet, kVipUserPackage1, kVipUserPackage2, } } <file_sep>/string/StringTrivialTest.cc #include "StringTrivial.h" #include <vector> using namespace trivial2; const char String::kEmpty[] = ""; void foo(String x) { } void bar(const String& x) { } String baz() { String ret("world"); return ret; } int main() { String s0; String s1("hello"); String s2(s0); String s3(s1); s2 = s1; s3 = s3; s1 = "aewsome"; foo(s1); bar(s1); foo("temporary"); bar("temporary"); String s4 = baz(); s4 = baz(); std::vector<String> svec; svec.push_back(s0); svec.push_back(s1); svec.push_back("good job"); } <file_sep>/puzzle/poker/generate.py #!/usr/bin/python import itertools import poker def gen(num): cards = [] ranks = '23456789TJQKA' for rank in reversed(ranks): for suit in 'SHDC': cards.append(rank + suit) return itertools.combinations(cards, num) if __name__ == '__main__': scores = [] for hand in gen(5): scores.append((poker.score(hand), " ".join(hand))) scores.sort(reverse=True) for s in scores: print s <file_sep>/string/test.sh #!/bin/sh g++ StringEager.cc test.cc -Wall -g -DBOOST_TEST_DYN_LINK -lboost_unit_test_framework -m64 -std=c++0x -o u64 ./u64 <file_sep>/basic/factorial.cc #include "uint.h" #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { if (argc > 1) { const int N = atoi(argv[1]); UnsignedInt result(1); for (int i = 1; i <= N; ++i) { result.multiply(i); } printf("%s\n", result.toDec().c_str()); } else { printf("Usage: %s number\n", argv[0]); } } <file_sep>/string/main.cc #include "StringEager.h" #include "StringSso.h" #include <stdio.h> int main() { printf("%zd\n", sizeof(muduo::StringEager)); printf("%zd\n", sizeof(muduo::StringSso)); muduo::StringEager x; } <file_sep>/python/chargen.py #!/usr/bin/python import socket import sys def get_message(): alphabet = "".join(chr(x) for x in range(33, 127)) alphabet += alphabet return "\n".join(alphabet[x:x+72] for x in range(127-33)) + "\n" def chargen(sock): message = get_message() # print len(message) try: while True: sock.sendall(message) except: pass def main(argv): if len(argv) < 3: binary = argv[0] print "Usage:\n %s -l port\n %s host port" % (argv[0], argv[0]) return port = int(argv[2]) if argv[1] == "-l": # server server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(('', port)) server_socket.listen(5) while True: (client_socket, client_address) = server_socket.accept() chargen(client_socket) else: # client sock = socket.create_connection((argv[1], port)) chargen(sock) if __name__ == "__main__": main(sys.argv) <file_sep>/basic/counted_ptr_test.cc #include "counted_ptr.h" #include <vector> #include <stdio.h> counted_ptr<int> foo() { counted_ptr<int> sp(new int(123)); return sp; } void bar(counted_ptr<int> x) { printf("%d\n", x.use_count()); } class Zoo; struct Age { int value; }; int main() { counted_ptr<int> sp1; counted_ptr<int> sp2(new int); sp1 = sp2; counted_ptr<int> sp3(sp2); { counted_ptr<int> sp4(sp2); counted_ptr<int> sp5(sp1); printf("%d\n", sp5.use_count()); bar(std::move(sp5)); } counted_ptr<int> sp6(foo()); printf("%d\n", *sp6); counted_ptr<Age> sp7(new Age); sp7->value = 43; printf("%d\n", sp7->value); std::vector<counted_ptr<int>> vec; vec.push_back(sp1); vec.push_back(sp2); vec.push_back(sp3); vec.push_back(sp6); if (sp2) printf("%p\n", sp2.get()); // counted_ptr<Zoo> x; } <file_sep>/benchmark/format_test.cc #include "format.h" #include "gtest/gtest.h" namespace { using ::testing::Eq; // Optional ::testing aliases. Remove if unused. using ::testing::Test; TEST(FormatTest, Human) { setlocale(LC_NUMERIC, ""); size_t numbers[] = { 0, 999, 1000, 9990, 9994, 9995, 10049, 10'050, 10'149, 10'150, 10'249, 99'949, 99'950, 100'000, 100'499, 999'499, 999'500, 9'994'999, 9'995'000, 9'995'001, 9'995'002, 999'000'000, 999'500'000-1, 999'500'500, 1'000'000'000, 10'000'000'000, 100'000'000'000, 1000'000'000'000, 10'000'000'000'000, 100'000'000'000'000, 1'000'000'000'000'000, 10'000'000'000'000'000, 100'000'000'000'000'000, 1000'000'000'000'000'000, 10'000'000'000'000'000'000U, INT64_MAX, UINT64_MAX, }; for (size_t n : numbers) { printf("%'32zu '%5s'\n", n, formatSI(n).c_str()); } } TEST(FormatTest, SI) { EXPECT_EQ("0", formatSI(0)); EXPECT_EQ("12.3k", formatSI(12345)); EXPECT_EQ("23.5k", formatSI(23456)); EXPECT_EQ("100k", formatSI(99999)); EXPECT_EQ("123k", formatSI(123456)); EXPECT_EQ("235k", formatSI(234567)); EXPECT_EQ("1.23M", formatSI(1234567)); EXPECT_EQ("9.99M", formatSI(9990000)); EXPECT_EQ("9.99M", formatSI(9995000-1)); EXPECT_EQ("10.0M", formatSI(9995000)); EXPECT_EQ("10.0M", formatSI(10000000-1)); EXPECT_EQ("10.0M", formatSI(10000000)); EXPECT_EQ("10.0M", formatSI(10049999)); EXPECT_EQ("10.1M", formatSI(10050000)); EXPECT_EQ("10.1M", formatSI(10150000-1)); EXPECT_EQ("10.2M", formatSI(10150000)); EXPECT_EQ("12.3M", formatSI(12345678)); EXPECT_EQ("99.9M", formatSI(99900000)); EXPECT_EQ("99.9M", formatSI(99950000-1)); EXPECT_EQ("100M", formatSI(99950000)); EXPECT_EQ("100M", formatSI(100*1000*1000)); EXPECT_EQ("9.99G", formatSI( 9'990'000'000)); EXPECT_EQ("9.99G", formatSI( 9'995'000'000-1)); EXPECT_EQ("10.0G", formatSI( 9'995'000'000)); EXPECT_EQ("99.9G", formatSI(99'950'000'000-1)); EXPECT_EQ("100G", formatSI(99'950'000'000)); EXPECT_EQ("100G", formatSI(100'000'000'000)); } TEST(FormatTest, HumanIEC) { setlocale(LC_NUMERIC, ""); size_t numbers[] = { 0, 1023, 1024, 9999, 10229, 10230, 10232, 10233, 10234, 10235, 10240-1, 10240, 102347, 102348, // 99.9492 Ki 102349, // 99.9502 Ki 1024*999, 1023487, 1023488, 1048063, 1048064, 1024*1000, 1024*1024-1, 1024*1024, 10480517, 10480518, // 9.995 Mi 10*1024*1024-1, 10*1024*1024, 104805171, 104805172, // 99.95 Mi 1048051711, 1048051712, 1048051713, 1073217535, 1073217536, 1073741824-1, 1073741824, 10732049530, 10732049531, 107320495308, 107320495309, 1099511627776 - 1, 1099511627776, 10989618719621, 10989618719622, 109896187196211, 109896187196212, INT64_MAX, UINT64_MAX, }; for (size_t n : numbers) { printf("%'32zu '%6s'\n", n, formatIEC(n).c_str()); } } } // namespace <file_sep>/topk/merger.cc #include <boost/asio/io_service.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/ptr_container/ptr_vector.hpp> #include <fstream> #include <stdio.h> class Source { public: explicit Source(std::istream* in) : in_(in), count_(0), word_() { } bool next() { std::string line; if (getline(*in_, line)) { size_t tab = line.find('\t'); if (tab != std::string::npos) { count_ = atoll(line.c_str()); if (count_ > 0) { word_ = line.substr(tab+1); return true; } } } return false; } bool operator<(const Source& rhs) const { return count_ < rhs.count_; } void output(std::ostream& out) { out << count_ << '\t' << word_ << '\n'; } private: std::istream* in_; int64_t count_; std::string word_; }; boost::asio::ip::tcp::endpoint get_endpoint(const std::string& ipport) { size_t colon = ipport.find(':'); if (colon != std::string::npos) { std::string ip = ipport.substr(0, colon); uint16_t port = static_cast<uint16_t>(atoi(ipport.c_str() + colon + 1)); return boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(ip), port); } else { throw std::invalid_argument("Invalid format of endpoint"); } } int main(int argc, char* argv[]) { if (argc >= 3) { boost::ptr_vector<boost::asio::ip::tcp::iostream> inputs; std::vector<Source> keys; const int64_t topK = atoll(argv[1]); for (int i = 2; i < argc; ++i) { inputs.push_back(new boost::asio::ip::tcp::iostream(get_endpoint(argv[i]))); Source src(&inputs.back()); if (src.next()) { keys.push_back(src); } } printf("Connected to %zd sender(s)\n", keys.size()); std::ofstream out("output"); int64_t cnt = 0; std::make_heap(keys.begin(), keys.end()); while (!keys.empty() && cnt < topK) { std::pop_heap(keys.begin(), keys.end()); keys.back().output(out); ++cnt; if (keys.back().next()) { std::push_heap(keys.begin(), keys.end()); } else { keys.pop_back(); } } printf("merging done\n"); } else { printf("Usage: %s topK ip1:port1 [ip2:port2 ...]\n", argv[0]); } } <file_sep>/esort/sort02.cc // version 02: first impl to sort large files. // sort and merge // 30% faster than sort(1) for all 1GB 5GB 10GB files #include <boost/noncopyable.hpp> #include <boost/ptr_container/ptr_vector.hpp> #include <datetime/Timestamp.h> #include <algorithm> #include <string> #include <ext/vstring.h> #include <vector> #include <assert.h> #include <stdio.h> #include <string.h> #include <sys/resource.h> // typedef std::string string; typedef __gnu_cxx::__sso_string string; using muduo::Timestamp; #define TMP_DIR "/tmp/" class InputFile : boost::noncopyable { public: InputFile(const char* filename) : file_(fopen(filename, "rb")) { assert(file_); setbuffer(file_, buffer_, sizeof buffer_); } ~InputFile() { fclose(file_); } bool readLine(string* line) { char buf[256]; if (fgets_unlocked(buf, sizeof buf, file_)) { line->assign(buf); return true; } else { return false; } } int read(char* buf, int size) { return fread_unlocked(buf, 1, size, file_); } private: FILE* file_; char buffer_[64*1024]; }; const int kRecordSize = 100; const int kKeySize = 10; class OutputFile : boost::noncopyable { public: OutputFile(const char* filename) : file_(fopen(filename, "wb")) { assert(file_); setbuffer(file_, buffer_, sizeof buffer_); } ~OutputFile() { fclose(file_); } void writeLine(const string& line) { if (line.empty()) { fwrite_unlocked("\n", 1, 1, file_); } else if (line[line.size() - 1] == '\n') { fwrite_unlocked(line.c_str(), 1, line.size(), file_); } else { fwrite_unlocked(line.c_str(), 1, line.size(), file_); fwrite_unlocked("\n", 1, 1, file_); } } void writeRecord(char (&record)[kRecordSize]) { fwrite_unlocked(record, 1, kRecordSize, file_); } private: FILE* file_; char buffer_[64*1024]; }; const bool kUseReadLine = false; const int kBatchRecords = 10000000; void readInput(InputFile& in, std::vector<string>* data) { int64_t totalSize = 0; data->clear(); data->reserve(kBatchRecords); for (int i = 0; i < kBatchRecords; ++i) { char buf[kRecordSize]; if (int n = in.read(buf, sizeof buf)) { assert (n == kRecordSize); totalSize += n; data->push_back(string(buf, n)); } else { break; } } } struct Key { char key[kKeySize]; int index; Key(const string& record, int idx) : index(idx) { memcpy(key, record.data(), sizeof key); } bool operator<(const Key& rhs) const { return memcmp(key, rhs.key, sizeof key) < 0; } }; void sort(const std::vector<string>& data, std::vector<Key>* keys) { Timestamp start = Timestamp::now(); keys->reserve(data.size()); for (size_t i = 0; i < data.size(); ++i) { keys->push_back(Key(data[i], i)); } // printf("make keys %f\n", data.size(), timeDifference(Timestamp::now(), start)); std::sort(keys->begin(), keys->end()); } int sortSplit(const char* filename) { std::vector<string> data; // read InputFile in(filename); int batch = 0; while(true) { Timestamp startThis = Timestamp::now(); readInput(in, &data); Timestamp readDone = Timestamp::now(); printf("%zd\nread %f\n", data.size(), timeDifference(readDone, startThis)); if (data.empty()) { break; } std::vector<Key> keys; sort(data, &keys); Timestamp sortDone = Timestamp::now(); printf("sort %f\n", timeDifference(sortDone, readDone)); // output { char output[256]; snprintf(output, sizeof output, TMP_DIR "tmp%d", batch++); OutputFile out(output); for (std::vector<Key>::iterator it = keys.begin(); it != keys.end(); ++it) { out.writeLine(data[it->index]); } } Timestamp writeDone = Timestamp::now(); printf("write %f\n", timeDifference(writeDone, sortDone)); } return batch; } struct Record { char data[kRecordSize]; InputFile* input; Record(InputFile* in) : input(in) { } bool next() { return input->read(data, sizeof data) == kRecordSize; } bool operator<(const Record& rhs) const { // make_heap to build min-heap, for merging return memcmp(data, rhs.data, kKeySize) > 0; } }; void merge(const int batch) { printf("merge %d files\n", batch); boost::ptr_vector<InputFile> inputs; std::vector<Record> keys; for (int i = 0; i < batch; ++i) { char filename[128]; snprintf(filename, sizeof filename, TMP_DIR "tmp%d", i); inputs.push_back(new InputFile(filename)); Record rec(&inputs.back()); if (rec.next()) { keys.push_back(rec); } } OutputFile out("output"); std::make_heap(keys.begin(), keys.end()); while (!keys.empty()) { std::pop_heap(keys.begin(), keys.end()); out.writeRecord(keys.back().data); if (keys.back().next()) { std::push_heap(keys.begin(), keys.end()); } else { keys.pop_back(); } } } int main(int argc, char* argv[]) { bool kKeepIntermediateFiles = false; { // set max virtual memory to 3GB. size_t kOneGB = 1024*1024*1024; rlimit rl = { 3.0*kOneGB, 3.0*kOneGB }; setrlimit(RLIMIT_AS, &rl); } Timestamp start = Timestamp::now(); // sort int batch = sortSplit(argv[1]); Timestamp sortDone = Timestamp::now(); printf("sortSplit %f\n", timeDifference(sortDone, start)); if (batch == 1) { unlink("output"); rename(TMP_DIR "tmp0", "output"); } else { // merge merge(batch); Timestamp mergeDone = Timestamp::now(); printf("mergeSplit %f\n", timeDifference(mergeDone, sortDone)); } if (!kKeepIntermediateFiles) { for (int i = 0; i < batch; ++i) { char tmp[256]; snprintf(tmp, sizeof tmp, TMP_DIR "tmp%d", i); unlink(tmp); } } printf("total %f\n", timeDifference(Timestamp::now(), start)); } <file_sep>/topk/word_freq_shards.cc /* sort word by frequency, sharding while counting version. 1. read input file, do counting, if counts > 10M keys, write counts to 10 shard files: word \t count 2. assume each shard file fits in memory, read each shard file, accumulate counts, and write to 10 count files: count \t word 3. merge 10 count files using heap. Limits: each shard must fit in memory. */ #include <boost/noncopyable.hpp> #include <boost/ptr_container/ptr_vector.hpp> #include <fstream> #include <iostream> #include <unordered_map> #ifdef STD_STRING #warning "STD STRING" #include <string> using std::string; #else #include <ext/vstring.h> typedef __gnu_cxx::__sso_string string; #endif const size_t kMaxSize = 10 * 1000 * 1000; class Sharder : boost::noncopyable { public: explicit Sharder(int nbuckets) : buckets_(nbuckets) { for (int i = 0; i < nbuckets; ++i) { char buf[256]; snprintf(buf, sizeof buf, "shard-%05d-of-%05d", i, nbuckets); buckets_.push_back(new std::ofstream(buf)); } assert(buckets_.size() == static_cast<size_t>(nbuckets)); } void output(const string& word, int64_t count) { size_t idx = std::hash<string>()(word) % buckets_.size(); buckets_[idx] << word << '\t' << count << '\n'; } protected: boost::ptr_vector<std::ofstream> buckets_; }; void shard(int nbuckets, int argc, char* argv[]) { Sharder sharder(nbuckets); for (int i = 1; i < argc; ++i) { std::cout << " processing input file " << argv[i] << std::endl; std::unordered_map<string, int64_t> counts; std::ifstream in(argv[i]); while (in && !in.eof()) { counts.clear(); string word; while (in >> word) { counts[word]++; if (counts.size() > kMaxSize) { std::cout << " split" << std::endl; break; } } for (const auto& kv : counts) { sharder.output(kv.first, kv.second); } } } std::cout << "shuffling done" << std::endl; } // ======= sort_shards ======= std::unordered_map<string, int64_t> read_shard(int idx, int nbuckets) { std::unordered_map<string, int64_t> counts; char buf[256]; snprintf(buf, sizeof buf, "shard-%05d-of-%05d", idx, nbuckets); std::cout << " reading " << buf << std::endl; { std::ifstream in(buf); string line; while (getline(in, line)) { size_t tab = line.find('\t'); if (tab != string::npos) { int64_t count = strtol(line.c_str() + tab, NULL, 10); if (count > 0) { counts[line.substr(0, tab)] += count; } } } } ::unlink(buf); return counts; } void sort_shards(const int nbuckets) { for (int i = 0; i < nbuckets; ++i) { // std::cout << " sorting " << std::endl; std::vector<std::pair<int64_t, string>> counts; for (const auto& entry : read_shard(i, nbuckets)) { counts.push_back(make_pair(entry.second, entry.first)); } std::sort(counts.begin(), counts.end()); char buf[256]; snprintf(buf, sizeof buf, "count-%05d-of-%05d", i, nbuckets); std::ofstream out(buf); std::cout << " writing " << buf << std::endl; for (auto it = counts.rbegin(); it != counts.rend(); ++it) { out << it->first << '\t' << it->second << '\n'; } } std::cout << "reducing done" << std::endl; } // ======= merge ======= class Source // copyable { public: explicit Source(std::istream* in) : in_(in), count_(0), word_() { } bool next() { string line; if (getline(*in_, line)) { size_t tab = line.find('\t'); if (tab != string::npos) { count_ = strtol(line.c_str(), NULL, 10); if (count_ > 0) { word_ = line.substr(tab+1); return true; } } } return false; } bool operator<(const Source& rhs) const { return count_ < rhs.count_; } void outputTo(std::ostream& out) const { out << count_ << '\t' << word_ << '\n'; } private: std::istream* in_; int64_t count_; string word_; }; void merge(const int nbuckets) { boost::ptr_vector<std::ifstream> inputs; std::vector<Source> keys; for (int i = 0; i < nbuckets; ++i) { char buf[256]; snprintf(buf, sizeof buf, "count-%05d-of-%05d", i, nbuckets); inputs.push_back(new std::ifstream(buf)); Source rec(&inputs.back()); if (rec.next()) { keys.push_back(rec); } ::unlink(buf); } std::ofstream out("output"); std::make_heap(keys.begin(), keys.end()); while (!keys.empty()) { std::pop_heap(keys.begin(), keys.end()); keys.back().outputTo(out); if (keys.back().next()) { std::push_heap(keys.begin(), keys.end()); } else { keys.pop_back(); } } std::cout << "merging done\n"; } int main(int argc, char* argv[]) { int nbuckets = 10; shard(nbuckets, argc, argv); sort_shards(nbuckets); merge(nbuckets); } <file_sep>/basic/tutorial/build.sh #!/bin/sh g++ -std=c++0x -O2 -Wall -g factorial.cc -o factorial g++ -std=c++0x -O2 -Wall -g sieve.cc -o sieve <file_sep>/basic/combination.cc #include "uint.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { if (argc > 2) { int M = atoi(argv[1]); const int N = atoi(argv[2]); assert(0 <= M && M <= N); if (M > N/2) M = N - M; UnsignedInt result(1); for (int i = 1; i <= M; ++i) { result.multiply(N - i + 1); int r = result.devide(i); assert(r == 0); if (r != 0) abort(); } printf("%s\n", result.toDec().c_str()); } else { printf("Usage: %s M N\n", argv[0]); printf("Choose M elements out of N.\n"); } } <file_sep>/benchmark/bm_containers.cc #include <assert.h> #include <fstream> #include <map> #include <random> #include <unordered_map> #include "absl/container/flat_hash_map.h" #include "absl/container/node_hash_map.h" #include "benchmark/benchmark.h" const int kMaxSize = 10'000'000; std::vector<std::string> g_keys; // of size kMaxSize int64_t getTotalLength(const std::vector<std::string>& keys) { return std::accumulate( keys.begin(), keys.end(), 0LL, [](int64_t len, const auto& key) { return len + key.size(); }); } template<class Map> static void BM_wordcount(benchmark::State& state) { assert(state.range(0) <= g_keys.size()); std::vector<std::string> keys(g_keys.begin(), g_keys.begin() + state.range(0)); int64_t total_length = getTotalLength(keys); for (auto _ : state) { Map counts; for (const auto& key : keys) counts[key]++; } state.SetItemsProcessed(keys.size() * state.iterations()); state.SetBytesProcessed(total_length * state.iterations()); } using treemap = std::map<std::string, int64_t>; BENCHMARK_TEMPLATE(BM_wordcount, treemap) ->RangeMultiplier(10)->Range(10, kMaxSize) ->Unit(benchmark::kMillisecond); using hashmap = std::unordered_map<std::string, int64_t>; BENCHMARK_TEMPLATE(BM_wordcount, hashmap) ->RangeMultiplier(10)->Range(10, kMaxSize) ->Unit(benchmark::kMillisecond); using nodemap = absl::node_hash_map<std::string, int64_t>; BENCHMARK_TEMPLATE(BM_wordcount, nodemap) ->RangeMultiplier(10)->Range(10, kMaxSize) ->Unit(benchmark::kMillisecond); using flatmap = absl::flat_hash_map<std::string, int64_t>; BENCHMARK_TEMPLATE(BM_wordcount, flatmap) ->RangeMultiplier(10)->Range(10, kMaxSize) ->Unit(benchmark::kMillisecond); template<class STR> static void BM_wordsort(benchmark::State& state) { assert(state.range(0) <= g_keys.size()); std::vector<std::string> keys(g_keys.begin(), g_keys.begin() + state.range(0)); int64_t total_length = getTotalLength(keys); for (auto _ : state) { state.PauseTiming(); std::vector<STR> copy(keys.begin(), keys.end()); state.ResumeTiming(); std::sort(copy.begin(), copy.end()); } state.SetItemsProcessed(keys.size() * state.iterations()); state.SetBytesProcessed(total_length * state.iterations()); } BENCHMARK_TEMPLATE(BM_wordsort, std::string) ->RangeMultiplier(10)->Range(10, kMaxSize) ->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_wordsort, std::string_view) ->RangeMultiplier(10)->Range(10, kMaxSize) ->Unit(benchmark::kMillisecond); std::vector<std::string> getKeys(int n, bool truncate) { std::vector<std::string> keys; std::mt19937_64 gen(43); for (int i = 0; i < n; ++i) { char buf[64]; if (truncate) { snprintf(buf, sizeof buf, "%lu", gen() & 0xffffffff); } else { snprintf(buf, sizeof buf, "%lu", gen()); } keys.push_back(buf); } return keys; } int main(int argc, char* argv[]) { benchmark::Initialize(&argc, argv); if (argc > 1 && ::strcmp(argv[1], "--short") == 0) { g_keys = getKeys(kMaxSize, /*truncate=*/true); } else if (argc > 1) { std::ifstream in(argv[1]); std::string line; while (getline(in, line)) { g_keys.push_back(line); if (g_keys.size() >= kMaxSize) break; } } else { g_keys = getKeys(kMaxSize, /*truncate=*/false); } assert(g_keys.size() >= kMaxSize); int64_t len = 0; for (const auto& key : g_keys) len += key.size(); printf("Average key length = %.2f\n", double(len) / g_keys.size()); benchmark::RunSpecifiedBenchmarks(); printf("Average key length = %.2f\n", double(len) / g_keys.size()); } <file_sep>/ssl/timer.h #pragma once #include <stdint.h> #include <time.h> #include <sys/time.h> inline double now() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec / 1e6; } struct Timer { Timer() : start_(0), total_(0) { } void start() { start_ = gettime(); } void stop() { total_ += gettime() - start_; } void reset() { start_ = 0; total_ = 0; } double seconds() const { return total_ / 1e9; } static int64_t gettime() { struct timespec ts; clock_gettime(CLOCK_MONOTONIC_RAW, &ts); return ts.tv_sec * 1e9 + ts.tv_nsec; } private: int64_t start_, total_; }; <file_sep>/java/bankqueue/event/CustomerLeaveEvent.java package bankqueue.event; import bankqueue.Bank; import bankqueue.WindowType; import bankqueue.customer.Customer; public class CustomerLeaveEvent extends Event { private final Customer customer; private final Bank bank; private final WindowType type; public CustomerLeaveEvent(int time, Customer customer, Bank bank, WindowType type) { super(time); this.customer = customer; this.bank = bank; this.type = type; } @Override public void happen(EventSimulator simulator) { assert simulator.getNow() == scheduledTime; bank.leave(simulator.getNow(), customer, type); } } <file_sep>/basic/exact.cc #include "uint.h" #include <float.h> #include <stdio.h> #include <iostream> #include <ios> // convert a floating point number to exact decimal number class Float { public: Float(int exponent, uint64_t mantissa) : E(exponent), M(mantissa) { } std::string decimal() const { std::string dec = integer(); std::pair<std::string, int> frac = fraction(); dec += '.'; dec.append(frac.second, '0'); dec.append(frac.first); return dec; } static Float fromDouble(double x) { union { double f; uint64_t u; }; f = x; // CAUTION: only works on 64-bit platforms? return fromDouble((u & 0x7ff0000000000000) >> 52, u & 0xFFFFFFFFFFFFF); } static Float fromDouble(int exponent, uint64_t fraction) { // FIXME: subnormal return Float(exponent-1023-52, fraction | 0x10000000000000); } private: std::string integer() const { int e = E; uint64_t m = M; while (e < 0) { m >>= 1; ++e; } uint32_t lo = m & 0xFFFFFFFF; uint32_t hi = m >> 32; UnsignedInt u(lo); if (hi) { UnsignedInt x(hi); x.multiply(0x10000); x.multiply(0x10000); u.add(x); } if (e) { UnsignedInt y(2); y.power(e); u.multiply(y); } return u.toDec(); } // 0.1111111111 // |||||||||| // 0.5||||||||| // 0.25|||||||| // 0.125||||||| // 0.0625|||||| // 0.03125||||| // 0.015625|||| // 0.0078125||| // 0.00390625|| // 0.001953125| // 0.0009765625 std::pair<std::string, int> fraction() const { int e = E; uint64_t m = M; UnsignedInt f(0); UnsignedInt d(5); while (e < 0 && (m & 1) == 0) { m >>= 1; ++e; } const int digits = (e < 0) ? -e : 0; while (e < 0) { f.multiply(5); if (m & 1) { f.add(d); } m >>= 1; ++e; d.multiply(10); } std::string x = f.toDec(); int zeros = x.size() < digits ? digits - x.size() : 0; return std::make_pair(x, zeros); } private: const int E; const uint64_t M; }; using namespace std; int main(int argc, char* argv[]) { if (argc > 1) { for (int i = 1; i < argc; ++i) { double x = strtod(argv[i], NULL); printf("%s = %a\n", argv[i], x); cout << Float::fromDouble(x).decimal() << endl; if (i != argc - 1) printf("\n"); } } else { Float f1 = Float::fromDouble(1); cout << f1.decimal() << endl; Float pi = Float::fromDouble(0x400, 0x921fb54442d18); cout << pi.decimal() << endl; Float f3 = Float::fromDouble(0x3fd, 0x5555555555555); cout << f3.decimal() << endl; Float f01 = Float::fromDouble(0.1); cout << f01.decimal() << endl; Float fy(1023, 2); // 2 ** 1024 cout << fy.decimal() << endl; assert(strtod("0x1.FffffFFFFffffP1023", NULL) == DBL_MAX); Float fx = Float::fromDouble(DBL_MAX); cout << fx.decimal() << endl; Float fm = Float::fromDouble(DBL_MIN); cout << fm.decimal() << endl; Float fe = Float::fromDouble(DBL_EPSILON); cout << fe.decimal() << endl; printf("%a\n", DBL_MAX); printf("%a\n", DBL_MIN); printf("%a\n", DBL_EPSILON); } } <file_sep>/topk/input.h #pragma once #include <string> #include <fcntl.h> class SegmentInput { public: explicit SegmentInput(const char* filename, int bufsize=kBufferSize) : filename_(filename), fd_(::open(filename, O_RDONLY)), buffer_size_(bufsize), data_(new char[buffer_size_]) { refill(); } const std::string& filename() const { return filename_; } int64_t tell() const { return offset_; } const std::string& current_word() const { return word_; } int64_t current_count() const { return count_; } bool next() { if (avail_ <= 0) return false; char* nl = static_cast<char*>(::memchr(start_, '\n', avail_)); if (nl) { char* tab = static_cast<char*>(::memchr(start_, '\t', nl - start_)); if (tab) { count_ = strtol(tab+1, NULL, 10); word_ = std::string_view(start_, tab-start_); int len = nl - start_ + 1; avail_ -= len; offset_ += len; assert(avail_ >= 0); if (avail_ == 0) { refill(); } else { start_ += len; } return true; } else { avail_ = 0; assert(0); return false; } } else { refill(); return next(); } } private: void refill() { start_ = data_.get(); avail_ = ::pread(fd_, start_, buffer_size_, offset_); } const std::string filename_; const int fd_; const int buffer_size_; int64_t offset_ = 0; // file position char* start_ = nullptr; int avail_ = 0; std::unique_ptr<char[]> data_; std::string word_; int64_t count_ = 0; SegmentInput(const SegmentInput&) = delete; void operator=(const SegmentInput&) = delete; }; <file_sep>/benchmark/format.cc #include "format.h" /* Format a number with 5 characters, including SI units. [0, 999] [1.00k, 999k] [1.00M, 999M] [1.00G, 999G] [1.00T, 999T] [1.00P, 999P] [1.00E, inf) */ std::string formatSI(size_t s) { char buf[64]; if (s < 1000) snprintf(buf, sizeof(buf), "%zd", s); else if (s < 9995) snprintf(buf, sizeof(buf), "%.2fk", s/1e3); else if (s < 99950) snprintf(buf, sizeof(buf), "%.1fk", s/1e3); else if (s < 999500) snprintf(buf, sizeof(buf), "%.0fk", s/1e3); else if (s < 9995000) snprintf(buf, sizeof(buf), "%.2fM", s/1e6); else if (s < 99950000) snprintf(buf, sizeof(buf), "%.1fM", s/1e6); else if (s < 999500000) snprintf(buf, sizeof(buf), "%.0fM", s/1e6); else if (s < 9995000000) snprintf(buf, sizeof(buf), "%.2fG", s/1e9); else if (s < 99950000000) snprintf(buf, sizeof(buf), "%.1fG", s/1e9); else if (s < 999500000000) snprintf(buf, sizeof(buf), "%.0fG", s/1e9); else if (s < 9995000000000) snprintf(buf, sizeof(buf), "%.2fT", s/1e12); else if (s < 99950000000000) snprintf(buf, sizeof(buf), "%.1fT", s/1e12); else if (s < 999500000000000) snprintf(buf, sizeof(buf), "%.0fT", s/1e12); else if (s < 9995000000000000) snprintf(buf, sizeof(buf), "%.2fP", s/1e15); else if (s < 99950000000000000) snprintf(buf, sizeof(buf), "%.1fP", s/1e15); else if (s < 999500000000000000) snprintf(buf, sizeof(buf), "%.0fP", s/1e15); else if (s < 9995000000000000000ULL) snprintf(buf, sizeof(buf), "%.2fE", s/1e18); else snprintf(buf, sizeof(buf), "%.1fE", s/1e18); return buf; } /* std::string formatSI(size_t s) { double n = s; char buf[64] = ""; if (s < 100000) // [0, 99999] snprintf(buf, sizeof(buf), "%zd", s); else if (s < 9999500) // [ 100k, 9999k] snprintf(buf, sizeof(buf), "%zdk", (s+500)/1000); else if (s < 99950000) // [10.0M, 99.9M] snprintf(buf, sizeof(buf), "%.1fM", s/1e6); else if (s < 9999500000) // [ 100M, 9999M] snprintf(buf, sizeof(buf), "%zdM", (s+500000)/1000000); else if (s < 99950000000) // [10.0G, 99.9G] snprintf(buf, sizeof(buf), "%.1fG", n/1e9); else if (n < 1e13) // [ 100G, 9999G] snprintf(buf, sizeof(buf), "%.0fG", n/1e9); else if (n < 1e14) snprintf(buf, sizeof(buf), "%.1fT", n/1e12); else if (n < 1e16) snprintf(buf, sizeof(buf), "%.0fT", n/1e12); else if (n < 1e17) snprintf(buf, sizeof(buf), "%.1fP", n/1e15); else if (n < 1e19) snprintf(buf, sizeof(buf), "%.0fP", n/1e15); else snprintf(buf, sizeof(buf), "%.1fE", n/1e18); return buf; } */ /* [0, 1023] [1.00Ki, 9.99Ki] [10.0Ki, 99.9Ki] [ 100Ki, 1023Ki] [1.00Mi, 9.99Mi] */ std::string formatIEC(size_t s) { double n = s; char buf[64]; const double Ki = 1024.0; const double Mi = Ki * 1024.0; const double Gi = Mi * 1024.0; const double Ti = Gi * 1024.0; const double Pi = Ti * 1024.0; const double Ei = Pi * 1024.0; if (n < Ki) snprintf(buf, sizeof buf, "%zd", s); else if (s < Ki*9.995) snprintf(buf, sizeof buf, "%.2fKi", s / Ki); else if (s < Ki*99.95) snprintf(buf, sizeof buf, "%.1fKi", s / Ki); else if (s < Ki*1023.5) snprintf(buf, sizeof buf, "%.0fKi", s / Ki); else if (s < Mi*9.995) snprintf(buf, sizeof buf, "%.2fMi", s / Mi); else if (s < Mi*99.95) snprintf(buf, sizeof buf, "%.1fMi", s / Mi); else if (s < Mi*1023.5) snprintf(buf, sizeof buf, "%.0fMi", s / Mi); else if (s < Gi*9.995) snprintf(buf, sizeof buf, "%.2fGi", s / Gi); else if (s < Gi*99.95) snprintf(buf, sizeof buf, "%.1fGi", s / Gi); else if (s < Gi*1023.5) snprintf(buf, sizeof buf, "%.0fGi", s / Gi); else if (s < Ti*9.995) snprintf(buf, sizeof buf, "%.2fTi", s / Ti); else if (s < Ti*99.95) snprintf(buf, sizeof buf, "%.1fTi", s / Ti); else if (s < Ti*1023.5) snprintf(buf, sizeof buf, "%.0fTi", s / Ti); else if (s < Pi*9.995) snprintf(buf, sizeof buf, "%.2fPi", s / Pi); else if (s < Pi*99.95) snprintf(buf, sizeof buf, "%.1fPi", s / Pi); else if (s < Pi*1023.5) snprintf(buf, sizeof buf, "%.0fPi", s / Pi); else if (s < Ei*9.995) snprintf(buf, sizeof buf, "%.2fEi", s / Ei ); else snprintf(buf, sizeof buf, "%.1fEi", s / Ei ); return buf; } <file_sep>/puzzle/poker/bench.py #!/usr/bin/python import time import poker, poker2, generate if __name__ == '__main__': start = time.time() max1 = max(generate.gen(5)) elapsed = time.time() - start print ("%.4f" % (elapsed)), max1 start = time.time() max2 = max(generate.gen(5), key=poker.score) elapsed = time.time() - start print ("%.4f" % (elapsed)), max2 start = time.time() max3 = max(generate.gen(5), key=poker2.score2) elapsed = time.time() - start print ("%.4f" % (elapsed)), max3 <file_sep>/tpc/bin/echo.cc #include "Acceptor.h" #include "InetAddress.h" #include "TcpStream.h" #include <thread> #include <string.h> // a thread-per-connection current echo server int main(int argc, char* argv[]) { bool nodelay = false; bool ipv6 = false; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-6") == 0) ipv6 = true; if (strcmp(argv[i], "-D") == 0) nodelay = true; } InetAddress listenAddr(3007, ipv6); Acceptor acceptor(listenAddr); printf("Listen on port 3007\n"); printf("Accepting... Ctrl-C to exit\n"); int count = 0; while (true) { TcpStreamPtr tcpStream = acceptor.accept(); printf("accepted no. %d client\n", ++count); if (nodelay) tcpStream->setTcpNoDelay(true); // C++11 doesn't allow capturing unique_ptr in lambda, C++14 allows. std::thread thr([count] (TcpStreamPtr stream) { printf("thread for no. %d client started.\n", count); char buf[4096]; int nr = 0; while ( (nr = stream->receiveSome(buf, sizeof(buf))) > 0) { int nw = stream->sendAll(buf, nr); if (nw < nr) { break; } } printf("thread for no. %d client ended.\n", count); }, std::move(tcpStream)); thr.detach(); } } <file_sep>/datetime/build.sh #!/bin/sh gpic shift_month.pic | groff | ps2eps --loose --gsbbox > shift_month.eps eps2png --pnggray -resolution 144 shift_month.eps gpic shift_month_cumsum.pic | groff | ps2eps --loose --gsbbox > shift_month_cumsum.eps eps2png --png16m -resolution 144 shift_month_cumsum.eps mpost linear_regression.mp ps2eps --loose --gsbbox < linear_regression-1.mps > linear_regression-1.eps eps2png --png16m -resolution 300 linear_regression-1.eps ps2eps --loose --gsbbox < linear_regression-2.mps > linear_regression-2.eps eps2png --png16m -resolution 300 linear_regression-2.eps latex formula_shift.tex dvips formula_shift ps2eps --loose --gsbbox < formula_shift.ps > formula_shift.eps eps2png --pnggray -resolution 300 formula_shift.eps <file_sep>/tpc/bin/tcpperf.cc #include "datetime/Timestamp.h" #include "Acceptor.h" #include "InetAddress.h" #include "TcpStream.h" #ifdef __linux #include <linux/tcp.h> #else #include <netinet/tcp.h> #endif #include <stdio.h> #include <stdlib.h> #include <unistd.h> using muduo::Timestamp; class BandwidthReporter { public: BandwidthReporter(int fd, bool sender) : fd_(fd), sender_(sender) { } void reportDelta(double now, int64_t total_bytes) { report(now, total_bytes - last_bytes_, now - last_time_); last_time_ = now; last_bytes_ = total_bytes; } void reportAll(double now, int64_t total_bytes, int64_t syscalls) { printf("Transferred %.3fMB %.3fMiB in %.3fs, %lld syscalls, %.1f Bytes/syscall\n", total_bytes / 1e6, total_bytes / (1024.0 * 1024), now, (long long)syscalls, total_bytes * 1.0 / syscalls); report(now, total_bytes, now); } private: void report(double now, int64_t bytes, double elapsed) { double mbps = elapsed > 0 ? bytes / 1e6 / elapsed : 0.0; printf("%6.3f %6.2fMB/s %6.1fMbits/s ", now, mbps, mbps*8); if (sender_) printSender(); else printReceiver(); } void printSender() { int sndbuf = 0; socklen_t optlen = sizeof sndbuf; if (::getsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &sndbuf, &optlen) < 0) perror("getsockopt(SNDBUF)"); struct tcp_info tcpi = {0}; socklen_t len = sizeof(tcpi); if (getsockopt(fd_, IPPROTO_TCP, TCP_INFO, &tcpi, &len) < 0) perror("getsockopt(TCP_INFO)"); // bytes_in_flight = tcpi.tcpi_bytes_sent - tcpi.tcpi_bytes_acked; // tcpi.tcpi_notsent_bytes; int snd_cwnd = tcpi.tcpi_snd_cwnd; int ssthresh = tcpi.tcpi_snd_ssthresh; #ifdef __linux snd_cwnd *= tcpi.tcpi_snd_mss; // Linux's cwnd is # of mss. if (ssthresh < INT32_MAX) ssthresh *= tcpi.tcpi_snd_mss; #endif #ifdef __linux int retrans = tcpi.tcpi_total_retrans; #elif __FreeBSD__ int retrans = tcpi.tcpi_snd_rexmitpack; #endif printf(" sndbuf=%.1fK snd_cwnd=%.1fK ssthresh=%.1fK snd_wnd=%.1fK rtt=%d/%d", sndbuf / 1024.0, snd_cwnd / 1024.0, ssthresh / 1024.0, tcpi.tcpi_snd_wnd / 1024.0, tcpi.tcpi_rtt, tcpi.tcpi_rttvar); if (retrans - last_retrans_ > 0) { printf(" retrans=%d", retrans - last_retrans_); } printf("\n"); last_retrans_ = retrans; } void printReceiver() const { int rcvbuf = 0; socklen_t optlen = sizeof rcvbuf; if (::getsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &optlen) < 0) perror("getsockopt(RCVBUF)"); printf(" rcvbuf=%.1fK\n", rcvbuf / 1024.0); } const int fd_ = 0; const bool sender_ = false; double last_time_ = 0; int64_t last_bytes_ = 0; int last_retrans_ = 0; }; void runClient(const InetAddress& serverAddr, int64_t bytes_limit, double duration) { TcpStreamPtr stream(TcpStream::connect(serverAddr)); if (!stream) { printf("Unable to connect %s\n", serverAddr.toIpPort().c_str()); perror(""); return; } char cong[64] = ""; socklen_t optlen = sizeof cong; if (::getsockopt(stream->fd(), IPPROTO_TCP, TCP_CONGESTION, cong, &optlen) < 0) perror("getsockopt(TCP_CONGESTION)"); printf("Connected %s -> %s, congestion control: %s\n", stream->getLocalAddr().toIpPort().c_str(), stream->getPeerAddr().toIpPort().c_str(), cong); const Timestamp start = Timestamp::now(); const int block_size = 64 * 1024; std::string message(block_size, 'S'); int seconds = 1; int64_t total_bytes = 0; int64_t syscalls = 0; double elapsed = 0; BandwidthReporter rpt(stream->fd(), true); rpt.reportDelta(0, 0); while (total_bytes < bytes_limit) { int bytes = std::min<int64_t>(message.size(), bytes_limit - total_bytes); int nw = stream->sendSome(message.data(), bytes); if (nw <= 0) break; total_bytes += nw; syscalls++; elapsed = timeDifference(Timestamp::now(), start); if (elapsed >= duration) break; if (elapsed >= seconds) { rpt.reportDelta(elapsed, total_bytes); while (elapsed >= seconds) ++seconds; } } stream->shutdownWrite(); Timestamp shutdown = Timestamp::now(); elapsed = timeDifference(shutdown, start); rpt.reportDelta(elapsed, total_bytes); char buf[1024]; int nr = stream->receiveSome(buf, sizeof buf); if (nr != 0) printf("nr = %d\n", nr); Timestamp end = Timestamp::now(); elapsed = timeDifference(end, start); rpt.reportAll(elapsed, total_bytes, syscalls); } void runServer(int port) { InetAddress listenAddr(port); Acceptor acceptor(listenAddr); int count = 0; while (true) { printf("Accepting on port %d ... Ctrl-C to exit\n", port); TcpStreamPtr stream = acceptor.accept(); ++count; printf("accepted no. %d client %s <- %s\n", count, stream->getLocalAddr().toIpPort().c_str(), stream->getPeerAddr().toIpPort().c_str()); const Timestamp start = Timestamp::now(); int seconds = 1; int64_t bytes = 0; int64_t syscalls = 0; double elapsed = 0; BandwidthReporter rpt(stream->fd(), false); rpt.reportDelta(elapsed, bytes); char buf[65536]; while (true) { int nr = stream->receiveSome(buf, sizeof buf); if (nr <= 0) break; bytes += nr; syscalls++; elapsed = timeDifference(Timestamp::now(), start); if (elapsed >= seconds) { rpt.reportDelta(elapsed, bytes); while (elapsed >= seconds) ++seconds; } } elapsed = timeDifference(Timestamp::now(), start); rpt.reportAll(elapsed, bytes, syscalls); printf("Client no. %d done\n", count); } } int64_t parseBytes(const char* arg) { char* end = NULL; int64_t bytes = strtoll(arg, &end, 10); switch (*end) { case '\0': return bytes; case 'k': return bytes * 1000; case 'K': return bytes * 1024; case 'm': return bytes * 1000 * 1000; case 'M': return bytes * 1024 * 1024; case 'g': return bytes * 1000 * 1000 * 1000; case 'G': return bytes * 1024 * 1024 * 1024; default: return 0; } } int main(int argc, char* argv[]) { int opt; bool client = false, server = false; std::string serverAddr; int port = 2009; const int64_t kGigaBytes = 1024 * 1024 * 1024; int64_t bytes_limit = 10 * kGigaBytes; double duration = 10; while ((opt = getopt(argc, argv, "sc:t:b:p:")) != -1) { switch (opt) { case 's': server = true; break; case 'c': client = true; serverAddr = optarg; break; case 't': duration = strtod(optarg, NULL); break; case 'b': bytes_limit = parseBytes(optarg); break; case 'p': port = strtol(optarg, NULL, 10); break; default: fprintf(stderr, "Usage: %s FIXME\n", argv[0]); break; } } if (client) runClient(InetAddress(serverAddr, port), bytes_limit, duration); else if (server) runServer(port); } <file_sep>/faketcp/Makefile CXXFLAGS=-g -Wall -pthread BINARIES=icmpecho rejectall acceptall discardall discardall2 echoall echoall2 connectmany all: $(BINARIES) icmpecho: icmpecho.cc faketcp.cc rejectall: rejectall.cc faketcp.cc acceptall: acceptall.cc faketcp.cc discardall: discardall.cc faketcp.cc discardall2: discardall2.cc faketcp.cc discardall2: CXXFLAGS += -std=c++0x echoall: echoall.cc faketcp.cc echoall2: echoall2.cc faketcp.cc echoall2: CXXFLAGS += -std=c++0x connectmany: connectmany.cc faketcp.cc $(BINARIES): g++ $(CXXFLAGS) $(LDFLAGS) $(filter %.cc,$^) -o $@ clean: rm -f $(BINARIES) <file_sep>/string/StringSso.h // excerpts from http://code.google.com/p/muduo/ // // Use of this source code is governed by a BSD-style license // that can be found in the License file. // // Author: <NAME> (giantchen at gmail dot com) #ifndef MUDUO_BASE_STRINGSSO_H #define MUDUO_BASE_STRINGSSO_H #include <stddef.h> // size_t #include <stdint.h> // uint32_t namespace muduo { /** * Short string optimized. * * similiar data structure of __gnu_cxx::__sso_string * sizeof() == 24 on 32-bit * sizeof() == 32 on 64-bit * max_size() == 1GB, on both 32-bit & 64-bit * local buffer == 15 on 32-bit * local buffer == 19 on 64-bit * */ class StringSso // : copyable // public boost::less_than_comparable<StringSso>, // public boost::less_than_comparable<StringSso, const char*>, // public boost::equality_comparable<StringSso>, // public boost::equality_comparable<StringSso, const char*>, // public boost::addable<StringSso>, // public boost::addable<StringSso, const char*> { public: typedef char value_type; typedef uint32_t size_type; typedef int32_t difference_type; typedef value_type& reference; typedef const char& const_reference; typedef value_type* pointer; typedef const char* const_pointer; typedef pointer iterator; typedef const_pointer const_iterator; static const size_type npos = -1; StringSso(const StringSso&); StringSso& operator=(const StringSso&); #ifdef __GXX_EXPERIMENTAL_CXX0X__ StringSso(StringSso&&); StringSso& operator=(StringSso&&); #endif private: const static int kLocalBuffer = sizeof(void*) == 8 ? 19 : 15; char* start_; uint32_t size_; union { uint32_t capacity_; char buf_[kLocalBuffer+1]; } data_; }; } #endif // MUDUO_BASE_STRINGSSO_H <file_sep>/digest/DigestOOP.cc #include "DigestOOP.h" #include <openssl/crypto.h> #include <openssl/md5.h> #include <openssl/sha.h> namespace oop { class MD5Digest : public Digest { public: MD5Digest() { MD5_Init(&ctx_); } ~MD5Digest() override { OPENSSL_cleanse(&ctx_, sizeof(ctx_)); } void update(const void* data, int len) override { MD5_Update(&ctx_, data, len); } std::string digest() override { unsigned char result[MD5_DIGEST_LENGTH]; MD5_Final(result, &ctx_); return std::string(reinterpret_cast<char*>(result), MD5_DIGEST_LENGTH); } int length() const override { return MD5_DIGEST_LENGTH; } private: MD5_CTX ctx_; }; class SHA1Digest : public Digest { public: SHA1Digest() { SHA1_Init(&ctx_); } ~SHA1Digest() override { OPENSSL_cleanse(&ctx_, sizeof(ctx_)); } void update(const void* data, int len) override { SHA1_Update(&ctx_, data, len); } std::string digest() override { unsigned char result[SHA_DIGEST_LENGTH]; SHA1_Final(result, &ctx_); return std::string(reinterpret_cast<char*>(result), SHA_DIGEST_LENGTH); } int length() const override { return SHA_DIGEST_LENGTH; } private: SHA_CTX ctx_; }; class SHA256Digest : public Digest { public: SHA256Digest() { SHA256_Init(&ctx_); } ~SHA256Digest() override { OPENSSL_cleanse(&ctx_, sizeof(ctx_)); } void update(const void* data, int len) override { SHA256_Update(&ctx_, data, len); } std::string digest() override { unsigned char result[SHA256_DIGEST_LENGTH]; SHA256_Final(result, &ctx_); return std::string(reinterpret_cast<char*>(result), SHA256_DIGEST_LENGTH); } int length() const override { return SHA256_DIGEST_LENGTH; } private: SHA256_CTX ctx_; }; // static std::unique_ptr<Digest> Digest::create(Type t) { std::unique_ptr<Digest> result; // TODO: std::make_unique if (t == MD5) result.reset(new MD5Digest); else if (t == SHA1) result.reset(new SHA1Digest); else if (t == SHA256) result.reset(new SHA256Digest); return result; } } // namespace oop <file_sep>/ssl/benchmark-polarssl.cc #include <polarssl/ctr_drbg.h> #include <polarssl/error.h> #include <polarssl/entropy.h> #include <polarssl/ssl.h> #include <polarssl/certs.h> #include <muduo/net/Buffer.h> #include <string> #include <stdio.h> #include <sys/time.h> #include "timer.h" muduo::net::Buffer clientOut, serverOut; int net_recv(void* ctx, unsigned char* buf, size_t len) { muduo::net::Buffer* in = static_cast<muduo::net::Buffer*>(ctx); //printf("%s recv %zd\n", in == &clientOut ? "server" : "client", len); if (in->readableBytes() > 0) { size_t n = std::min(in->readableBytes(), len); memcpy(buf, in->peek(), n); in->retrieve(n); /* if (n < len) printf("got %zd\n", n); else printf("\n"); */ return n; } else { //printf("got 0\n"); return POLARSSL_ERR_NET_WANT_READ; } } int net_send(void* ctx, const unsigned char* buf, size_t len) { muduo::net::Buffer* out = static_cast<muduo::net::Buffer*>(ctx); // printf("%s send %zd\n", out == &clientOut ? "client" : "server", len); out->append(buf, len); return len; } int main(int argc, char* argv[]) { entropy_context entropy; entropy_init(&entropy); ctr_drbg_context ctr_drbg; ctr_drbg_init(&ctr_drbg, entropy_func, &entropy, NULL, 0); ssl_context ssl; bzero(&ssl, sizeof ssl); ssl_init(&ssl); ssl_set_rng(&ssl, ctr_drbg_random, &ctr_drbg); ssl_set_bio(&ssl, &net_recv, &serverOut, &net_send, &clientOut); ssl_set_endpoint(&ssl, SSL_IS_CLIENT); ssl_set_authmode(&ssl, SSL_VERIFY_NONE); const char* srv_cert = test_srv_crt_ec; const char* srv_key = test_srv_key_ec; std::string arg = argc > 1 ? argv[1] : "r"; bool useRSA = arg == "r" || arg == "er"; bool useECDHE = arg == "er" || arg == "ee"; if (useRSA) { srv_cert = test_srv_crt; srv_key = test_srv_key; } x509_crt cert; x509_crt_init(&cert); // int ret = x509_crt_parse_file(&cert, argv[1]); // printf("cert parse %d\n", ret); x509_crt_parse(&cert, reinterpret_cast<const unsigned char*>(srv_cert), strlen(srv_cert)); x509_crt_parse(&cert, reinterpret_cast<const unsigned char*>(test_ca_list), strlen(test_ca_list)); pk_context pkey; pk_init(&pkey); pk_parse_key(&pkey, reinterpret_cast<const unsigned char*>(srv_key), strlen(srv_key), NULL, 0); // ret = pk_parse_keyfile(&pkey, argv[2], NULL); // printf("key parse %d\n", ret); ssl_context ssl_server; bzero(&ssl_server, sizeof ssl_server); ssl_init(&ssl_server); ssl_set_rng(&ssl_server, ctr_drbg_random, &ctr_drbg); ssl_set_bio(&ssl_server, &net_recv, &clientOut, &net_send, &serverOut); ssl_set_endpoint(&ssl_server, SSL_IS_SERVER); ssl_set_authmode(&ssl_server, SSL_VERIFY_NONE); //ssl_set_ca_chain(&ssl_server, cert.next, NULL, NULL); ssl_set_own_cert(&ssl_server, &cert, &pkey); ecp_group_id curves[] = { POLARSSL_ECP_DP_SECP256R1, POLARSSL_ECP_DP_SECP224K1, POLARSSL_ECP_DP_NONE }; ssl_set_curves(&ssl_server, curves); if (useECDHE) { int ciphersuites[] = { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 0 }; ssl_set_ciphersuites(&ssl_server, ciphersuites); } else { int ciphersuites[] = { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, 0 }; ssl_set_ciphersuites(&ssl_server, ciphersuites); } double start = now(); Timer tc, ts; const int N = 500; for (int i = 0; i < N; ++i) { ssl_session_reset(&ssl); ssl_session_reset(&ssl_server); while (true) { tc.start(); int ret = ssl_handshake(&ssl); tc.stop(); //printf("ssl %d\n", ret); if (ret < 0) { if (ret != POLARSSL_ERR_NET_WANT_READ) { char errbuf[512]; polarssl_strerror(ret, errbuf, sizeof errbuf); printf("client error %d %s\n", ret, errbuf); break; } } else if (ret == 0 && i == 0) { printf("client done %s %s\n", ssl_get_version(&ssl), ssl_get_ciphersuite(&ssl)); } ts.start(); int ret2 = ssl_handshake(&ssl_server); ts.stop(); // printf("srv %d\n", ret2); if (ret2 < 0) { if (ret != POLARSSL_ERR_NET_WANT_READ) { char errbuf[512]; polarssl_strerror(ret2, errbuf, sizeof errbuf); printf("server error %d %s\n", ret2, errbuf); break; } } else if (ret2 == 0) { // printf("server done %s %s\n", ssl_get_version(&ssl_server), ssl_get_ciphersuite(&ssl_server)); } if (ret == 0 && ret2 == 0) break; } } double elapsed = now() - start; printf("%.2fs %.1f handshakes/s\n", elapsed, N / elapsed); printf("client %.3f %.1f\n", tc.seconds(), N / tc.seconds()); printf("server %.3f %.1f\n", ts.seconds(), N / ts.seconds()); printf("server/client %.2f\n", ts.seconds() / tc.seconds()); double start2 = now(); const int M = 200; unsigned char buf[16384] = { 0 }; for (int i = 0; i < M*1024; ++i) { int n = ssl_write(&ssl, buf, 1024); if (n < 0) { char errbuf[512]; polarssl_strerror(n, errbuf, sizeof errbuf); printf("%s\n", errbuf); } /* n = ssl_read(&ssl_server, buf, 8192); if (n != 1024) break; if (n < 0) { char errbuf[512]; polarssl_strerror(n, errbuf, sizeof errbuf); printf("%s\n", errbuf); } */ clientOut.retrieveAll(); } elapsed = now() - start2; printf("%.2f %.1f MiB/s\n", elapsed, M / elapsed); ssl_free(&ssl); ssl_free(&ssl_server); pk_free(&pkey); x509_crt_free(&cert); entropy_free(&entropy); } <file_sep>/thread/test/NonRecursiveMutex_test.cc #include "../Mutex.h" #include "../Thread.h" #include <vector> #include <stdio.h> using namespace muduo; class Foo { public: void doit() const; }; MutexLock mutex; std::vector<Foo> foos; void post(const Foo& f) { MutexLockGuard lock(mutex); foos.push_back(f); } void traverse() { MutexLockGuard lock(mutex); for (std::vector<Foo>::const_iterator it = foos.begin(); it != foos.end(); ++it) { it->doit(); } } void Foo::doit() const { Foo f; post(f); // 调用post(),对于非递归Mutex, 重复加锁会导致死锁 } int main() { Foo f; post(f); traverse(); } <file_sep>/digest/DigestOOP.h #pragma once #include <memory> #include <string> #ifdef __cpp_lib_string_view #include <string_view> #endif namespace oop { class Digest { public: virtual ~Digest() {} virtual void update(const void* data, int len) = 0; #ifdef __cpp_lib_string_view void update(std::string_view str) { update(str.data(), str.length()); } #endif virtual std::string digest() = 0; virtual int length() const = 0; enum Type { SHA1 = 1, SHA256 = 2, MD5 = 5, }; static std::unique_ptr<Digest> create(Type t); protected: Digest() {} private: Digest(const Digest&) = delete; void operator=(const Digest&) = delete; }; } <file_sep>/tpc/bin/roundtrip_tcp.cc #include "InetAddress.h" #include "TcpStream.h" #include <limits> #include <memory> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <vector> int64_t kNanos = 1e9; int64_t clock_diff(struct timespec x, struct timespec y) { return (x.tv_sec - y.tv_sec) * kNanos + x.tv_nsec - y.tv_nsec; } struct timespec get_time() { struct timespec now; clock_gettime(CLOCK_MONOTONIC, &now); return now; } struct Sample { int index; int64_t start_nano; int64_t rtt_nano; }; std::vector<Sample> run(const char* host, int delay_ms, int length_s, int batch, int payload_size, bool silent) { const struct timespec start = get_time(); std::vector<Sample> rtts; InetAddress addr; if (!InetAddress::resolve(host, 3007, &addr)) { printf("Unable to resolve %s\n", host); return rtts; } // printf("connecting to %s\n", addr.toIpPort().c_str()); TcpStreamPtr stream(TcpStream::connect(addr)); if (!stream) { printf("Unable to connect %s\n", addr.toIpPort().c_str()); perror(""); return rtts; } std::unique_ptr<char[]> payload(new char[payload_size]); int64_t count = 0, sum_rtt = 0; int64_t min_rtt = std::numeric_limits<int64_t>::max(), max_rtt = 0; while (true) { const struct timespec batch_start = get_time(); double elapsed_s = (double)clock_diff(batch_start, start) / kNanos; if (elapsed_s >= length_s) { if (silent && count > 0) { printf("count %ld, avg rtt %.2fus, min %.2fus, max %.2fus\n", count, sum_rtt / 1e3 / count, min_rtt / 1e3, max_rtt / 1e3); } break; } for (int i = 0; i < batch; ++i) { const struct timespec before = get_time(); int nw = stream->sendAll(payload.get(), payload_size); if (nw != payload_size) return rtts; int nr = stream->receiveAll(payload.get(), payload_size); if (nr != payload_size) return rtts; const struct timespec after = get_time(); int64_t rtt = clock_diff(after, before); ++count; sum_rtt += rtt; if (rtt > max_rtt) max_rtt = rtt; if (rtt < min_rtt) min_rtt = rtt; Sample s = { .index = i, .rtt_nano = rtt, }; if (i == 0) s.start_nano = clock_diff(before, start); else s.start_nano = clock_diff(before, batch_start); if (!silent) rtts.push_back(s); } if (delay_ms > 0) { ::usleep(delay_ms * 1000); } } return rtts; } int main(int argc, char* argv[]) { int opt; int delay = 0, length = 3, batch = 4, payload = 1; bool silent = false; while ((opt = getopt(argc, argv, "b:d:l:p:s")) != -1) { switch (opt) { case 'b': batch = atoi(optarg); break; case 'd': delay = atoi(optarg); break; case 'l': length = atoi(optarg); break; case 'p': payload = atoi(optarg); break; case 's': silent = true; break; default: ; } } if (optind >= argc) { fprintf(stderr, "Usage:\nroundtrip_tcp [-b batch_size] [-d delay_ms] [-l length_in_seconds] echo_server_host\n"); return 1; } if (batch < 1) { batch = 1; } if (delay < 0) { delay = 0; } if (payload < 1) { payload = 1; } std::vector<Sample> rtts = run(argv[optind], delay, length, batch, payload, silent); if (!silent) { printf("index start rtt\n"); for (Sample s : rtts) { printf("%d %ld %ld\n", s.index, s.start_nano, s.rtt_nano); } } } <file_sep>/basic/fibonacci.cc // Set skip_to_string = true, N = 1,000,000 measured on i7-7600U laptop // linear : 11.45 s // fast : 0.639 s // faster : 0.437 s // fastest: 0.215 s #include "uint.h" #include <unordered_map> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <sys/time.h> const bool skip_to_string = false; double now() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec / 1000000.0; } std::string fastFibonacci(int N) { assert (N >= 0); // double start = now(); UnsignedInt n0(0), n1(1), n2(1); UnsignedInt* result = &n1; UnsignedInt t0(0), t1(1), t2(1), t3; UnsignedInt s1, s2; if (N == 0) { result = &n0; } else if (N >= 3) { if (N % 2 == 0) { result = &n0; } while (N >>= 1) { // A := A * A t3 = t2; t3.add(t0); t3.multiply(t1); t0.multiply(t0); t1.multiply(t1); t2.multiply(t2); t2.add(t1); t0.add(t1); t1.swap(t3); if (N % 2) { // TODO: find faster method // N := A * N s1 = n1; s1.multiply(t0); s2 = n2; s2.multiply(t1); s2.add(s1); n1.multiply(t1); n2.multiply(t2); n2.add(n1); n0.multiply(t0); n0.add(n1); n1.swap(s2); } } } // printf("%f\n", now() - start); return skip_to_string ? "" : result->toDec(); }; std::string fasterFibonacci(int N) { // double start = now(); UnsignedInt n0(0), n1(1), n2(1); UnsignedInt* result = &n1; UnsignedInt t; if (N == 0) { result = &n0; } else if (N >= 3) { int bit = 1; while (bit <= N) bit <<= 1; bit >>= 1; assert((bit & N) > 0); // http://en.wikipedia.org/wiki/Exponentiation_by_squaring#Runtime_example:_compute_310_2 for (bit >>= 1; bit > 0; bit >>= 1) { // A = A * A t = n2; t.add(n0); t.multiply(n1); n0.multiply(n0); n1.multiply(n1); n2.multiply(n2); n2.add(n1); n0.add(n1); n1.swap(t); if (bit & N) { // A = [ 1 1; 1 0] * A n0.swap(n1); n1 = n2; n2.add(n0); } } } // printf("%f\n", now() - start); return skip_to_string ? "" : result->toDec(); } // f(2n) = f(n) * (f(n-1) + f(n+1)) // f(2n+1) = f(n)^2 + f(n+1)^2 class Fib { public: explicit Fib(int N) { cache_[0] = UnsignedInt(0); cache_[1] = UnsignedInt(1); cache_[2] = UnsignedInt(1); /* cache_[3] = UnsignedInt(2); cache_[4] = UnsignedInt(3); cache_[5] = UnsignedInt(5); cache_[6] = UnsignedInt(8); cache_[7] = UnsignedInt(13); cache_[8] = UnsignedInt(21); cache_[9] = UnsignedInt(34); */ calc(N); result_ = &cache_[N]; } const UnsignedInt& get() const { return *result_; } private: void calc(int N) { assert(N >= 0); auto it = cache_.find(N); if (it == cache_.end()) { calc(N/2); calc(N/2 + 1); if (N & 1) { UnsignedInt a = cache_[N/2]; a.multiply(a); UnsignedInt b = cache_[N/2 + 1]; b.multiply(b); a.add(b); cache_[N] = std::move(a); } else { calc(N/2 - 1); UnsignedInt a = cache_[N/2 - 1]; a.add(cache_[N/2 + 1]); a.multiply(cache_[N/2]); cache_[N] = std::move(a); } } } std::unordered_map<int, UnsignedInt> cache_; const UnsignedInt* result_ = nullptr; }; std::string fastestFibonacci(int N) { Fib f(N); return skip_to_string ? "" : f.get().toDec(); } class FibonacciIterator { public: std::string operator*() const { return fn.toDec(); } FibonacciIterator& operator++() { prev.swap(fn); fn.add(prev); return *this; } private: UnsignedInt fn = 1, prev = 0; }; std::string linearFibonacci(int N) { assert(N >= 0); // double start = now(); FibonacciIterator iter; // F(1) for (int i = 1; i < N; ++i) { ++iter; } //printf("%f\n", now() - start); return skip_to_string ? "" : (N == 0 ? "0" : *iter); }; int main(int argc, char* argv[]) { if (argc > 1) { const int N = atoi(argv[1]); std::string result; if (argc > 2) { if (argv[2][0] == 'F') { result = fastestFibonacci(N); } else if (argv[2][0] == 'f') { result = fasterFibonacci(N); } else { result = fastFibonacci(N); } } else { result = linearFibonacci(N); } printf("%s\n", result.c_str()); } else { printf("Usage: %s number [fFx]\n", argv[0]); FibonacciIterator iter; for (int i = 1; i < 10000; ++i) { if (fastFibonacci(i) != *iter || fasterFibonacci(i) != *iter || fastestFibonacci(i) != *iter) { printf("ERROR %d\n", i); } ++iter; } } } <file_sep>/tpc/bin/footprint.py #!/usr/bin/python3 # Read and analyse stdout of footprint.cc # $ sudo ./footprint 100000 | ./footprint.py from collections import OrderedDict import re, sys slabs = {} sections = [] section = None for line in sys.stdin: if m := re.match('===== (.*) =====', line): section_name = m.group(1) # print(section_name) if (section): sections.append(section) section = (section_name, OrderedDict(), OrderedDict()) meminfo = True continue if re.match('slabinfo -', line): meminfo = False continue if meminfo: if m := re.match('(.*): *(\\d+) kB', line): section[1][m.group(1)] = int(m.group(2)) else: if line[0] == '#': continue (slab, active, total, objsize) = line.split()[:4] slabs[slab] = int(objsize) section[2][slab] = int(active) sections.append(section) for i in range(1, len(sections)): print('=====', sections[i][0]) meminfo = sections[i][1] old = sections[i-1][1] for key in meminfo: diff = meminfo[key]-old[key] if diff: print(key, meminfo[key], diff) print('-----') slab = sections[i][2] old = sections[i-1][2] for key in slab: diff = slab[key]-old[key] if diff: print(key, slabs[key], slab[key], diff) <file_sep>/string/StringTrivial.h #pragma once #include <utility> #include <assert.h> #include <string.h> namespace trivial { // A trivial String class that designed for write-on-paper in an interview class String { public: String() : data_(new char[1]) { *data_ = '\0'; } String(const char* str) : data_(new char[strlen(str) + 1]) { strcpy(data_, str); } String(const String& rhs) : data_(new char[rhs.size() + 1]) { strcpy(data_, rhs.c_str()); } /* Implement copy-ctor with delegating constructor in C++11 String(const String& rhs) : String(rhs.data_) { } */ ~String() noexcept { delete[] data_; } /* Traditional: String& operator=(const String& rhs) { String tmp(rhs); swap(tmp); return *this; } */ // In C++11, this is unifying assignment operator String& operator=(String rhs) // yes, pass-by-value { // http://en.wikibooks.org/wiki/More_C++_Idioms/Copy-and-swap swap(rhs); return *this; } // C++11 move-ctor String(String&& rhs) noexcept : data_(rhs.data_) { rhs.data_ = nullptr; } /* Not needed if we have pass-by-value operator=() above, * and it conflits. http://stackoverflow.com/questions/17961719/ String& operator=(String&& rhs) { swap(rhs); return *this; } */ // Accessors size_t size() const { return strlen(data_); } const char* c_str() const { return data_; } void swap(String& rhs) { std::swap(data_, rhs.data_); } private: char* data_; }; } namespace trivial2 { // string in C++11 with a length member class String { public: String() noexcept : data_(nullptr), len_(0) { } ~String() { delete[] data_; } // only read str when len > 0 String(const char* str, size_t len) : data_(len > 0 ? new char[len+1] : nullptr), len_(len) { if (len_ > 0) { memcpy(data_, str, len_); data_[len_] = '\0'; } else { assert(data_ == nullptr); } } String(const char* str) : String(str, strlen(str)) { } String(const String& rhs) : String(rhs.data_, rhs.len_) { } String(String&& rhs) noexcept : data_(rhs.data_), len_(rhs.len_) { rhs.len_ = 0; rhs.data_ = nullptr; } String& operator=(String rhs) { swap(rhs); return *this; } void swap(String& rhs) noexcept { std::swap(len_, rhs.len_); std::swap(data_, rhs.data_); } // const char* data() const { return c_str(); } const char* c_str() const noexcept { return data_ ? data_ : kEmpty; } size_t size() const noexcept { return len_; } private: char* data_; size_t len_; static const char kEmpty[]; }; // const char String::kEmpty[] = ""; } <file_sep>/benchmark/bm_fileio.cc /* $ sudo bash -c "echo 1 > /proc/sys/vm/drop_caches" */ #include <fcntl.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fstream> #include <string> #include "benchmark/benchmark.h" const char* g_filename; static void BM_read(benchmark::State& state) { const int64_t buflen = state.range(0); void* buffer = ::malloc(buflen); int64_t len = 0; for (auto _ : state) { int fd = ::open(g_filename, O_RDONLY); if (fd < 0) { state.SkipWithError("Failed to read data!"); break; } ssize_t nr = 0; while ( (nr = ::read(fd, buffer, buflen)) > 0) { len += nr; } ::close(fd); } state.SetBytesProcessed(len); ::free(buffer); } BENCHMARK(BM_read)->RangeMultiplier(2)->Range(512, 8 * 1024 * 1024)->UseRealTime()->Unit(benchmark::kMillisecond); struct GetLine { bool operator()(FILE* fp) const { char line[1024]; return ::fgets(line, sizeof line, fp); } }; struct GetLineAssign { bool operator()(FILE* fp) const { char line[1024] = ""; // same as bzero(line, 1024) return ::fgets(line, sizeof line, fp); } }; template<typename FUNC> static void BM_fgets(benchmark::State& state) { int64_t len = 0; int64_t lines = 0; char buffer[128 * 1024]; FUNC func; for (auto _ : state) { FILE* fp = ::fopen(g_filename, "r"); if (!fp) { state.SkipWithError("Failed to read data!"); break; } ::setbuffer(fp, buffer, sizeof buffer); while (func(fp)) { lines++; } len += ::ftell(fp); ::fclose(fp); } state.SetBytesProcessed(len); state.SetItemsProcessed(lines); } BENCHMARK_TEMPLATE(BM_fgets, GetLine)->UseRealTime()->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_fgets, GetLineAssign)->UseRealTime()->Unit(benchmark::kMillisecond); static void BM_getline(benchmark::State& state) { int64_t len = 0; int64_t lines = 0; for (auto _ : state) { std::ifstream in(g_filename); if (!in) { state.SkipWithError("Failed to read data!"); break; } std::string line; while (getline(in, line)) { len += line.size()+1; lines++; } } state.SetBytesProcessed(len); state.SetItemsProcessed(lines); } BENCHMARK(BM_getline)->UseRealTime()->Unit(benchmark::kMillisecond); int main(int argc, char* argv[]) { benchmark::Initialize(&argc, argv); if (argc > 1) { g_filename = argv[1]; benchmark::RunSpecifiedBenchmarks(); } else { printf("Usage: %s file_to_read\n", argv[0]); } } <file_sep>/datetime/Makefile CXXFLAGS=-g -Wall -O0 -I /usr/local/include PNG_DPI=300 TEXES=$(wildcard *.tex) PICS=$(wildcard *.pic) TEX_PNGS=$(subst tex,png,$(TEXES)) PIC_PNGS=$(subst pic,png,$(PICS)) %.eps : %.pic gpic $< | groff | ps2eps --loose --gsbbox > $@ %.eps : %.tex latex $< dvips $(basename $<) ps2eps --loose --gsbbox < $(basename $<).ps > $(basename $<).eps %.png : %.eps eps2png --png16m -resolution $(PNG_DPI) $< BINARIES=date_test date_unittest timestamp_unittest timezone_dump timezone_unittest all: $(BINARIES) doc: $(TEX_PNGS) $(PIC_PNGS) $(PIC_PNGS): PNG_DPI=144 $(BINARIES): $(CXX) $(CXXFLAGS) $(filter %.cc,$^) -o $@ date_test: Date.h Date.cc Date_test.cc date_unittest: Date.h Date.cc Date_unittest.cc timestamp_unittest: Timestamp.h Timestamp.cc Timestamp_unittest.cc timezone_dump: TimeZone.h TimeZone.cc Date.cc TimeZone_dump.cc timezone_unittest: TimeZone.h TimeZone.cc Date.cc TimeZone_unittest.cc test: date_unittest ./date_unittest clean: rm -f *.aux rm -f *.dvi rm -f *.eps rm -f *.log rm -f *.mps rm -f *.mpx rm -f *.ps rm -f *_unittest clean-all: clean rm -f *.png rm -f $(BINARIES) <file_sep>/benchmark/format_bench.cc #include "format.h" #include "benchmark/benchmark.h" #include <random> static void BM_formatSI(benchmark::State& state) { std::mt19937_64 gen(43); for (auto _ : state) { formatSI(gen()); } state.SetItemsProcessed(state.iterations()); } BENCHMARK(BM_formatSI); static void BM_formatIEC(benchmark::State& state) { std::mt19937_64 gen(43); for (auto _ : state) { formatIEC(gen()); } state.SetItemsProcessed(state.iterations()); } BENCHMARK(BM_formatIEC); <file_sep>/benchmark/bench_dd.py #!/usr/bin/python3 import re, subprocess bs = 1 count = 1024 * 1024 while bs <= 1024 * 1024 * 8: args = ['dd', 'if=/dev/zero', 'of=/dev/null', 'bs=%d' % bs, 'count=%d' % count] result = subprocess.run(args, capture_output=True) seconds = 0 message = str(result.stderr) if m := re.search('copied, (.*?) s, ', message): seconds = float(m.group(1)) elif m := re.search('bytes transferred in (.*?) secs', message): seconds = float(m.group(1)) else: print('Unable to parse dd output:\n%s' % message) break print('bs=%7d count=%7d %6.3fs %8.3fus/record %9.3fMB/s' % (bs, count, seconds, seconds * 1e6 / count, bs * count / 1e6 / seconds)) bs *= 2 if seconds > 1: count /= 2 result = """ Raspberry Pi 4 running FreeBSD 13-RELEASE: freebsd% python3.9 bench_dd.py bs= 1 count=1048576 3.307s 3.154us/record 0.317MB/s bs= 2 count= 524288 1.682s 3.209us/record 0.623MB/s bs= 4 count= 262144 0.824s 3.144us/record 1.272MB/s bs= 8 count= 262144 0.855s 3.262us/record 2.453MB/s bs= 16 count= 262144 0.831s 3.171us/record 5.046MB/s bs= 32 count= 262144 0.813s 3.101us/record 10.321MB/s bs= 64 count= 262144 0.848s 3.236us/record 19.779MB/s bs= 128 count= 262144 0.848s 3.235us/record 39.569MB/s bs= 256 count= 262144 0.863s 3.293us/record 77.746MB/s bs= 512 count= 262144 0.844s 3.220us/record 159.029MB/s bs= 1024 count= 262144 0.894s 3.411us/record 300.221MB/s bs= 2048 count= 262144 0.984s 3.755us/record 545.461MB/s bs= 4096 count= 262144 1.106s 4.219us/record 970.906MB/s bs= 8192 count= 131072 0.675s 5.148us/record 1591.372MB/s bs= 16384 count= 131072 0.917s 6.992us/record 2343.125MB/s bs= 32768 count= 131072 1.385s 10.567us/record 3100.959MB/s bs= 65536 count= 65536 1.189s 18.144us/record 3611.984MB/s bs= 131072 count= 32768 1.130s 34.500us/record 3799.209MB/s bs= 262144 count= 16384 1.155s 70.499us/record 3718.413MB/s bs= 524288 count= 8192 1.264s 154.328us/record 3397.221MB/s bs=1048576 count= 4096 1.543s 376.625us/record 2784.138MB/s bs=2097152 count= 2048 2.041s 996.766us/record 2103.957MB/s bs=4194304 count= 1024 2.441s 2383.790us/record 1759.511MB/s bs=8388608 count= 512 2.690s 5253.455us/record 1596.779MB/s Raspberry Pi 4 running Raspbian GNU/Linux 10 armv7, kernel 5.10 $ python3 bench_dd.py bs= 1 count=1048576 1.067s 1.018us/record 0.982MB/s bs= 2 count= 524288 0.529s 1.009us/record 1.982MB/s bs= 4 count= 524288 0.540s 1.030us/record 3.885MB/s bs= 8 count= 524288 0.537s 1.025us/record 7.805MB/s bs= 16 count= 524288 0.533s 1.016us/record 15.741MB/s bs= 32 count= 524288 0.537s 1.023us/record 31.265MB/s bs= 64 count= 524288 1.527s 2.913us/record 21.972MB/s bs= 128 count= 262144 0.758s 2.892us/record 44.258MB/s bs= 256 count= 262144 0.760s 2.899us/record 88.300MB/s bs= 512 count= 262144 0.768s 2.930us/record 174.728MB/s bs= 1024 count= 262144 0.795s 3.034us/record 337.543MB/s bs= 2048 count= 262144 0.817s 3.117us/record 657.138MB/s bs= 4096 count= 262144 0.886s 3.378us/record 1212.454MB/s bs= 8192 count= 262144 1.406s 5.365us/record 1527.034MB/s bs= 16384 count= 131072 1.294s 9.875us/record 1659.057MB/s bs= 32768 count= 65536 1.245s 19.003us/record 1724.402MB/s bs= 65536 count= 32768 1.227s 37.450us/record 1749.962MB/s bs= 131072 count= 16384 1.264s 77.148us/record 1698.972MB/s bs= 262144 count= 8192 1.257s 153.500us/record 1707.781MB/s bs= 524288 count= 4096 1.303s 318.062us/record 1648.385MB/s bs=1048576 count= 2048 1.503s 733.804us/record 1428.960MB/s bs=2097152 count= 1024 1.839s 1796.094us/record 1167.618MB/s bs=4194304 count= 512 1.833s 3580.527us/record 1171.421MB/s bs=8388608 count= 256 1.860s 7266.406us/record 1154.437MB/s Raspberry Pi 4 running Debian 11 arm64, kernel 5.10 $ ./bench_dd.py bs= 1 count=1048576 1.464s 1.396us/record 0.716MB/s bs= 2 count= 524288 0.729s 1.390us/record 1.439MB/s bs= 4 count= 524288 0.735s 1.402us/record 2.852MB/s bs= 8 count= 524288 0.740s 1.411us/record 5.670MB/s bs= 16 count= 524288 0.746s 1.423us/record 11.246MB/s bs= 32 count= 524288 0.737s 1.407us/record 22.750MB/s bs= 64 count= 524288 0.738s 1.408us/record 45.465MB/s bs= 128 count= 524288 0.745s 1.421us/record 90.060MB/s bs= 256 count= 524288 0.752s 1.434us/record 178.504MB/s bs= 512 count= 524288 0.780s 1.488us/record 344.122MB/s bs= 1024 count= 524288 0.831s 1.585us/record 645.859MB/s bs= 2048 count= 524288 0.914s 1.742us/record 1175.405MB/s bs= 4096 count= 524288 1.096s 2.090us/record 1960.027MB/s bs= 8192 count= 262144 0.750s 2.861us/record 2863.609MB/s bs= 16384 count= 262144 1.125s 4.290us/record 3819.446MB/s bs= 32768 count= 131072 1.001s 7.638us/record 4289.905MB/s bs= 65536 count= 65536 0.975s 14.882us/record 4403.740MB/s bs= 131072 count= 65536 1.834s 27.978us/record 4684.865MB/s bs= 262144 count= 32768 2.088s 63.717us/record 4114.190MB/s bs= 524288 count= 16384 2.347s 143.225us/record 3660.587MB/s bs=1048576 count= 8192 3.553s 433.748us/record 2417.480MB/s bs=2097152 count= 4096 5.754s 1404.768us/record 1492.881MB/s bs=4194304 count= 2048 6.109s 2982.832us/record 1406.148MB/s bs=8388608 count= 1024 6.307s 6159.189us/record 1361.966MB/s Raspberry Pi 4 running Ubuntu server 21.04 arm64, kernel 5.11 $ ./bench_dd.py bs= 1 count=1048576 5.409s 5.159us/record 0.194MB/s bs= 2 count= 524288 2.828s 5.393us/record 0.371MB/s bs= 4 count= 262144 1.415s 5.397us/record 0.741MB/s bs= 8 count= 131072 0.682s 5.202us/record 1.538MB/s bs= 16 count= 131072 0.719s 5.483us/record 2.918MB/s bs= 32 count= 131072 0.674s 5.143us/record 6.222MB/s bs= 64 count= 131072 0.704s 5.373us/record 11.911MB/s bs= 128 count= 131072 0.711s 5.425us/record 23.593MB/s bs= 256 count= 131072 0.690s 5.262us/record 48.655MB/s bs= 512 count= 131072 0.714s 5.449us/record 93.955MB/s bs= 1024 count= 131072 0.707s 5.392us/record 189.911MB/s bs= 2048 count= 131072 0.751s 5.728us/record 357.517MB/s bs= 4096 count= 131072 0.802s 6.116us/record 669.720MB/s bs= 8192 count= 131072 1.038s 7.916us/record 1034.902MB/s bs= 16384 count= 65536 0.833s 12.712us/record 1288.837MB/s bs= 32768 count= 65536 1.325s 20.212us/record 1621.207MB/s bs= 65536 count= 32768 1.282s 39.113us/record 1675.575MB/s bs= 131072 count= 16384 1.211s 73.936us/record 1772.773MB/s bs= 262144 count= 8192 1.185s 144.619us/record 1812.651MB/s bs= 524288 count= 4096 1.091s 266.418us/record 1967.912MB/s bs=1048576 count= 2048 1.372s 670.063us/record 1564.891MB/s bs=2097152 count= 1024 1.543s 1507.129us/record 1391.488MB/s bs=4194304 count= 512 1.650s 3223.105us/record 1301.324MB/s bs=8388608 count= 256 1.583s 6185.391us/record 1356.197MB/s ================================================================ Raspberry Pi 3 running Raspbian GNU/Linux 10 armv7, kernel 5.10 $ ./bench_dd.py bs= 1 count=1048576 1.507s 1.437us/record 0.696MB/s bs= 2 count= 524288 0.753s 1.437us/record 1.392MB/s bs= 4 count= 524288 0.757s 1.444us/record 2.770MB/s bs= 8 count= 524288 0.762s 1.454us/record 5.503MB/s bs= 16 count= 524288 0.763s 1.456us/record 10.992MB/s bs= 32 count= 524288 0.767s 1.463us/record 21.878MB/s bs= 64 count= 524288 0.897s 1.711us/record 37.394MB/s bs= 128 count= 524288 0.899s 1.715us/record 74.630MB/s bs= 256 count= 524288 0.925s 1.764us/record 145.141MB/s bs= 512 count= 524288 0.943s 1.799us/record 284.672MB/s bs= 1024 count= 524288 1.013s 1.933us/record 529.725MB/s bs= 2048 count= 262144 0.565s 2.155us/record 950.259MB/s bs= 4096 count= 262144 0.671s 2.559us/record 1600.774MB/s bs= 8192 count= 262144 0.996s 3.799us/record 2156.141MB/s bs= 16384 count= 262144 1.627s 6.208us/record 2639.224MB/s bs= 32768 count= 131072 1.456s 11.111us/record 2949.152MB/s bs= 65536 count= 65536 1.365s 20.821us/record 3147.534MB/s bs= 131072 count= 32768 1.324s 40.391us/record 3245.109MB/s bs= 262144 count= 16384 1.301s 79.400us/record 3301.561MB/s bs= 524288 count= 8192 1.369s 167.107us/record 3137.440MB/s bs=1048576 count= 4096 1.862s 454.695us/record 2306.109MB/s bs=2097152 count= 2048 2.197s 1072.520us/record 1955.351MB/s bs=4194304 count= 1024 2.454s 2396.406us/record 1750.247MB/s bs=8388608 count= 512 2.584s 5046.152us/record 1662.377MB/s Raspberry Pi 3 running Ubuntu server 21.04 arm64, kernel 5.11 $ ./bench_dd.py bs= 1 count=1048576 10.017s 9.553us/record 0.105MB/s bs= 2 count= 524288 5.021s 9.577us/record 0.209MB/s bs= 4 count= 262144 2.505s 9.554us/record 0.419MB/s bs= 8 count= 131072 1.251s 9.546us/record 0.838MB/s bs= 16 count= 65536 0.631s 9.623us/record 1.663MB/s bs= 32 count= 65536 0.629s 9.605us/record 3.332MB/s bs= 64 count= 65536 0.630s 9.606us/record 6.663MB/s bs= 128 count= 65536 0.636s 9.700us/record 13.195MB/s bs= 256 count= 65536 0.634s 9.667us/record 26.481MB/s bs= 512 count= 65536 0.635s 9.687us/record 52.854MB/s bs= 1024 count= 65536 0.645s 9.840us/record 104.064MB/s bs= 2048 count= 65536 0.655s 10.002us/record 204.760MB/s bs= 4096 count= 65536 0.688s 10.498us/record 390.177MB/s bs= 8192 count= 65536 0.903s 13.782us/record 594.390MB/s bs= 16384 count= 65536 1.343s 20.487us/record 799.712MB/s bs= 32768 count= 32768 1.105s 33.717us/record 971.844MB/s bs= 65536 count= 16384 0.987s 60.240us/record 1087.909MB/s bs= 131072 count= 16384 1.854s 113.177us/record 1158.110MB/s bs= 262144 count= 8192 1.801s 219.850us/record 1192.377MB/s bs= 524288 count= 4096 1.796s 438.547us/record 1195.511MB/s bs=1048576 count= 2048 1.972s 963.125us/record 1088.723MB/s bs=2097152 count= 1024 2.151s 2100.605us/record 998.356MB/s bs=4194304 count= 512 2.253s 4400.293us/record 953.187MB/s bs=8388608 count= 256 2.306s 9005.898us/record 931.457MB/s Raspberry Pi 3 running Debian 11 arm64, kernel 5.10 $ ./bench_dd.py bs= 1 count=1048576 2.171s 2.070us/record 0.483MB/s bs= 2 count= 524288 1.069s 2.039us/record 0.981MB/s bs= 4 count= 262144 0.543s 2.071us/record 1.931MB/s bs= 8 count= 262144 0.539s 2.058us/record 3.888MB/s bs= 16 count= 262144 0.543s 2.070us/record 7.730MB/s bs= 32 count= 262144 0.543s 2.072us/record 15.443MB/s bs= 64 count= 262144 0.544s 2.077us/record 30.817MB/s bs= 128 count= 262144 0.552s 2.105us/record 60.802MB/s bs= 256 count= 262144 0.557s 2.126us/record 120.423MB/s bs= 512 count= 262144 0.572s 2.184us/record 234.471MB/s bs= 1024 count= 262144 0.599s 2.286us/record 447.998MB/s bs= 2048 count= 262144 0.656s 2.501us/record 818.834MB/s bs= 4096 count= 262144 0.767s 2.926us/record 1399.933MB/s bs= 8192 count= 262144 1.018s 3.883us/record 2109.512MB/s bs= 16384 count= 131072 0.757s 5.776us/record 2836.329MB/s bs= 32768 count= 131072 1.252s 9.549us/record 3431.527MB/s bs= 65536 count= 65536 1.116s 17.026us/record 3849.261MB/s bs= 131072 count= 32768 1.052s 32.093us/record 4084.183MB/s bs= 262144 count= 16384 1.045s 63.790us/record 4109.505MB/s bs= 524288 count= 8192 1.092s 133.292us/record 3933.372MB/s bs=1048576 count= 4096 2.321s 566.655us/record 1850.465MB/s bs=2097152 count= 2048 2.984s 1457.168us/record 1439.197MB/s bs=4194304 count= 1024 3.431s 3350.625us/record 1251.798MB/s bs=8388608 count= 512 3.456s 6750.234us/record 1242.714MB/s ================================================================ Raspberry Pi 2 running Raspbian GNU/Linux 10 armv7, kernel 5.10 $ ./bench_dd.py bs= 1 count=1048576 2.294s 2.188us/record 0.457MB/s bs= 2 count= 524288 1.155s 2.203us/record 0.908MB/s bs= 4 count= 262144 0.573s 2.187us/record 1.829MB/s bs= 8 count= 262144 0.581s 2.215us/record 3.611MB/s bs= 16 count= 262144 0.579s 2.210us/record 7.239MB/s bs= 32 count= 262144 0.582s 2.221us/record 14.405MB/s bs= 64 count= 262144 0.767s 2.926us/record 21.874MB/s bs= 128 count= 262144 0.725s 2.767us/record 46.261MB/s bs= 256 count= 262144 0.794s 3.028us/record 84.557MB/s bs= 512 count= 262144 0.773s 2.951us/record 173.523MB/s bs= 1024 count= 262144 0.799s 3.050us/record 335.763MB/s bs= 2048 count= 262144 1.093s 4.170us/record 491.168MB/s bs= 4096 count= 131072 0.547s 4.170us/record 982.276MB/s bs= 8192 count= 131072 1.039s 7.929us/record 1033.159MB/s bs= 16384 count= 65536 0.771s 11.765us/record 1392.607MB/s bs= 32768 count= 65536 1.511s 23.059us/record 1421.036MB/s bs= 65536 count= 32768 2.009s 61.321us/record 1068.740MB/s bs= 131072 count= 16384 1.858s 113.374us/record 1156.103MB/s bs= 262144 count= 8192 2.055s 250.829us/record 1045.111MB/s bs= 524288 count= 4096 2.036s 496.960us/record 1054.989MB/s bs=1048576 count= 2048 2.070s 1010.869us/record 1037.301MB/s bs=2097152 count= 1024 2.084s 2035.068us/record 1030.507MB/s bs=4194304 count= 512 2.097s 4094.844us/record 1024.289MB/s bs=8388608 count= 256 2.096s 8189.414us/record 1024.323MB/s Overclocking https://wiki.debian.org/RaspberryPi#Overclocking_Pi_2 arm_freq=1000 core_freq=500 sdram_freq=400 over_voltage=0 over_voltage_sdram_p=0 over_voltage_sdram_i=0 over_voltage_sdram_c=0 $ ./bench_dd.py bs= 1 count=1048576 2.071s 1.975us/record 0.506MB/s bs= 2 count= 524288 1.038s 1.979us/record 1.011MB/s bs= 4 count= 262144 0.520s 1.984us/record 2.016MB/s bs= 8 count= 262144 0.520s 1.982us/record 4.036MB/s bs= 16 count= 262144 0.524s 2.001us/record 7.997MB/s bs= 32 count= 262144 0.524s 1.999us/record 16.006MB/s bs= 64 count= 262144 0.692s 2.640us/record 24.246MB/s bs= 128 count= 262144 0.654s 2.494us/record 51.329MB/s bs= 256 count= 262144 0.653s 2.492us/record 102.746MB/s bs= 512 count= 262144 0.672s 2.564us/record 199.718MB/s bs= 1024 count= 262144 0.732s 2.792us/record 366.773MB/s bs= 2048 count= 262144 0.785s 2.993us/record 684.160MB/s bs= 4096 count= 262144 0.968s 3.694us/record 1108.962MB/s bs= 8192 count= 262144 1.612s 6.148us/record 1332.376MB/s bs= 16384 count= 131072 1.504s 11.471us/record 1428.238MB/s bs= 32768 count= 65536 1.497s 22.840us/record 1434.649MB/s bs= 65536 count= 32768 1.432s 43.706us/record 1499.482MB/s bs= 131072 count= 16384 1.437s 87.693us/record 1494.671MB/s bs= 262144 count= 8192 1.426s 174.119us/record 1505.548MB/s bs= 524288 count= 4096 1.415s 345.540us/record 1517.302MB/s bs=1048576 count= 2048 1.428s 697.305us/record 1503.756MB/s bs=2097152 count= 1024 1.430s 1396.846us/record 1501.348MB/s bs=4194304 count= 512 1.442s 2815.664us/record 1489.632MB/s bs=8388608 count= 256 1.444s 5642.461us/record 1486.693MB/s ================================================================ HP e8300, CPU i7-3770 freebsd13% ./bench_dd.py bs= 1 count=1048576 0.728s 0.694us/record 1.440MB/s bs= 2 count=1048576 0.573s 0.547us/record 3.658MB/s bs= 4 count=1048576 0.565s 0.539us/record 7.418MB/s bs= 8 count=1048576 0.575s 0.548us/record 14.595MB/s bs= 16 count=1048576 0.572s 0.546us/record 29.329MB/s bs= 32 count=1048576 0.574s 0.548us/record 58.435MB/s bs= 64 count=1048576 0.573s 0.546us/record 117.174MB/s bs= 128 count=1048576 0.568s 0.542us/record 236.122MB/s bs= 256 count=1048576 0.577s 0.550us/record 465.528MB/s bs= 512 count=1048576 0.585s 0.558us/record 917.797MB/s bs= 1024 count=1048576 0.591s 0.564us/record 1815.495MB/s bs= 2048 count=1048576 0.610s 0.582us/record 3517.599MB/s bs= 4096 count=1048576 0.648s 0.618us/record 6624.642MB/s bs= 8192 count=1048576 0.716s 0.683us/record 12000.920MB/s bs= 16384 count=1048576 0.886s 0.845us/record 19391.838MB/s bs= 32768 count=1048576 1.414s 1.349us/record 24291.204MB/s bs= 65536 count= 524288 1.167s 2.226us/record 29446.678MB/s bs= 131072 count= 262144 1.049s 4.001us/record 32757.097MB/s bs= 262144 count= 131072 0.996s 7.597us/record 34507.742MB/s bs= 524288 count= 131072 1.938s 14.784us/record 35462.791MB/s bs=1048576 count= 65536 1.954s 29.814us/record 35170.740MB/s bs=2097152 count= 32768 1.978s 60.353us/record 34748.329MB/s bs=4194304 count= 16384 2.007s 122.520us/record 34233.639MB/s bs=8388608 count= 8192 2.103s 256.698us/record 32678.930MB/s debian11$ ./bench_dd.py bs= 1 count=1048576 0.558s 0.532us/record 1.880MB/s bs= 2 count=1048576 0.550s 0.524us/record 3.814MB/s bs= 4 count=1048576 0.551s 0.526us/record 7.611MB/s bs= 8 count=1048576 0.550s 0.525us/record 15.252MB/s bs= 16 count=1048576 0.550s 0.524us/record 30.509MB/s bs= 32 count=1048576 0.550s 0.524us/record 61.048MB/s bs= 64 count=1048576 0.553s 0.527us/record 121.398MB/s bs= 128 count=1048576 0.556s 0.530us/record 241.471MB/s bs= 256 count=1048576 0.565s 0.538us/record 475.482MB/s bs= 512 count=1048576 0.583s 0.556us/record 921.523MB/s bs= 1024 count=1048576 0.608s 0.580us/record 1764.989MB/s bs= 2048 count=1048576 0.640s 0.611us/record 3353.923MB/s bs= 4096 count=1048576 0.701s 0.669us/record 6126.015MB/s bs= 8192 count=1048576 0.870s 0.830us/record 9870.674MB/s bs= 16384 count=1048576 1.191s 1.136us/record 14427.529MB/s bs= 32768 count= 524288 1.004s 1.915us/record 17109.038MB/s bs= 65536 count= 262144 0.822s 3.135us/record 20902.551MB/s bs= 131072 count= 262144 1.496s 5.705us/record 22973.575MB/s bs= 262144 count= 131072 1.468s 11.200us/record 23406.614MB/s bs= 524288 count= 65536 1.519s 23.171us/record 22626.825MB/s bs=1048576 count= 32768 1.495s 45.614us/record 22988.023MB/s bs=2097152 count= 16384 1.487s 90.750us/record 23109.237MB/s bs=4194304 count= 8192 1.474s 179.918us/record 23312.281MB/s bs=8388608 count= 4096 1.588s 387.625us/record 21641.067MB/s """ <file_sep>/ssl/TlsContext.h #pragma once #include "Common.h" #include "TlsConfig.h" // Internal class class TlsContext : noncopyable { public: enum Endpoint { kClient, kServer }; TlsContext(Endpoint type, TlsConfig* config) : context_(type == kServer ? tls_server() : tls_client()) { check(tls_configure(context_, config->get())); } TlsContext(TlsContext&& rhs) { swap(rhs); } ~TlsContext() { tls_free(context_); } TlsContext& operator=(TlsContext rhs) // ??? { swap(rhs); return *this; } void swap(TlsContext& rhs) { std::swap(context_, rhs.context_); } // void reset(struct tls* ctx) { context_ = ctx; } // struct tls* get() { return context_; } const char* cipher() { return tls_conn_cipher(context_); } // if there is no error, this will segfault. const char* error() { return tls_error(context_); } int connect(const char* hostport, const char* servername = nullptr) { return tls_connect_servername(context_, hostport, nullptr, servername); } TlsContext accept(int sockfd) { struct tls* conn_ctx = nullptr; check(tls_accept_socket(context_, &conn_ctx, sockfd)); return TlsContext(conn_ctx); } int handshake() { int ret = -1; do { ret = tls_handshake(context_); } while(ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT); return ret; } int read(void* buf, int len) { return tls_read(context_, buf, len); } int write(const void* buf, int len) { return tls_write(context_, buf, len); } private: explicit TlsContext(struct tls* context) : context_(context) {} void check(int ret) { if (ret != 0) { LOG_FATAL << tls_error(context_); } } struct tls* context_ = nullptr; }; <file_sep>/protobuf/descriptor_test.cc #include "codec.h" #include "query.pb.h" #include <iostream> #include <typeinfo> #include <assert.h> #include <stdio.h> using std::cout; using std::endl; template<typename T> void testDescriptor() { std::string type_name = T::descriptor()->full_name(); cout << type_name << endl; const google::protobuf::Descriptor* descriptor = google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(type_name); assert(descriptor == T::descriptor()); cout << "FindMessageTypeByName() = " << descriptor << endl; cout << "T::descriptor() = " << T::descriptor() << endl; cout << endl; const google::protobuf::Message* prototype = google::protobuf::MessageFactory::generated_factory()->GetPrototype(descriptor); assert(prototype == &T::default_instance()); cout << "GetPrototype() = " << prototype << endl; cout << "T::default_instance() = " << &T::default_instance() << endl; cout << endl; T* new_obj = dynamic_cast<T*>(prototype->New()); assert(new_obj != NULL); assert(new_obj != prototype); assert(typeid(*new_obj) == typeid(T::default_instance())); cout << "prototype->New() = " << new_obj << endl; cout << endl; delete new_obj; } int main() { GOOGLE_PROTOBUF_VERIFY_VERSION; testDescriptor<muduo::Query>(); testDescriptor<muduo::Answer>(); google::protobuf::Message* newQuery = createMessage("muduo.Query"); assert(newQuery != NULL); assert(typeid(*newQuery) == typeid(muduo::Query::default_instance())); cout << "createMessage(\"muduo.Query\") = " << newQuery << endl; google::protobuf::Message* newAnswer = createMessage("muduo.Answer"); assert(newAnswer != NULL); assert(typeid(*newAnswer) == typeid(muduo::Answer::default_instance())); cout << "createMessage(\"muduo.Answer\") = " << newAnswer << endl; delete newQuery; delete newAnswer; puts("All pass!!!"); google::protobuf::ShutdownProtobufLibrary(); } <file_sep>/reactor/s10/Makefile LIB_SRC = \ Acceptor.cc \ Buffer.cc \ Channel.cc \ EventLoop.cc \ EventLoopThread.cc \ EventLoopThreadPool.cc \ InetAddress.cc \ Poller.cc \ Socket.cc \ SocketsOps.cc \ TcpConnection.cc \ TcpServer.cc \ Timer.cc \ TimerQueue.cc BINARIES = test1 test2 test3 test4 test5 test6 test7 test8 test9 test10 \ test11 all: $(BINARIES) include ../reactor_lib.mk test1: test1.cc test2: test2.cc test3: test3.cc test4: test4.cc test5: test5.cc test6: test6.cc test7: test7.cc test8: test8.cc test9: test9.cc test10: test10.cc test11: test11.cc <file_sep>/faketcp/faketcp.cc #include "faketcp.h" #include <fcntl.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <linux/if_tun.h> #include <netinet/in.h> #include <netinet/ip_icmp.h> #include <sys/ioctl.h> int sethostaddr(const char* dev) { struct ifreq ifr; bzero(&ifr, sizeof(ifr)); strcpy(ifr.ifr_name, dev); struct sockaddr_in addr; bzero(&addr, sizeof addr); addr.sin_family = AF_INET; inet_pton(AF_INET, "192.168.0.1", &addr.sin_addr); //addr.sin_addr.s_addr = htonl(0xc0a80001); bcopy(&addr, &ifr.ifr_addr, sizeof addr); int sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) return sockfd; int err = 0; // ifconfig tun0 192.168.0.1 if ((err = ioctl(sockfd, SIOCSIFADDR, (void *) &ifr)) < 0) { perror("ioctl SIOCSIFADDR"); goto done; } // ifup tun0 if ((err = ioctl(sockfd, SIOCGIFFLAGS, (void *) &ifr)) < 0) { perror("ioctl SIOCGIFFLAGS"); goto done; } ifr.ifr_flags |= IFF_UP; if ((err = ioctl(sockfd, SIOCSIFFLAGS, (void *) &ifr)) < 0) { perror("ioctl SIOCSIFFLAGS"); goto done; } // ifconfig tun0 192.168.0.1/24 inet_pton(AF_INET, "255.255.255.0", &addr.sin_addr); bcopy(&addr, &ifr.ifr_netmask, sizeof addr); if ((err = ioctl(sockfd, SIOCSIFNETMASK, (void *) &ifr)) < 0) { perror("ioctl SIOCSIFNETMASK"); goto done; } done: close(sockfd); return err; } int tun_alloc(char dev[IFNAMSIZ], bool offload) { struct ifreq ifr; int fd, err; if ((fd = open("/dev/net/tun", O_RDWR)) < 0) { perror("open"); return -1; } bzero(&ifr, sizeof(ifr)); ifr.ifr_flags = IFF_TUN | IFF_NO_PI; if (*dev) { strncpy(ifr.ifr_name, dev, IFNAMSIZ); } if ((err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0) { perror("ioctl TUNSETIFF"); close(fd); return err; } if (offload) { const uint32_t offload_flags = TUN_F_CSUM | TUN_F_TSO4 | TUN_F_TSO6 | TUN_F_TSO_ECN; if (ioctl(fd, TUNSETOFFLOAD, offload_flags) != 0) { perror("TUNSETOFFLOAD"); return -1; } } strcpy(dev, ifr.ifr_name); if ((err = sethostaddr(dev)) < 0) return err; return fd; } uint16_t in_checksum(const void* buf, int len) { assert(len % 2 == 0); const uint16_t* data = static_cast<const uint16_t*>(buf); int sum = 0; for (int i = 0; i < len; i+=2) { sum += *data++; } while (sum >> 16) sum = (sum & 0xFFFF) + (sum >> 16); assert(sum <= 0xFFFF); return ~sum; } void icmp_input(int fd, const void* input, const void* payload, int len) { const struct iphdr* iphdr = static_cast<const struct iphdr*>(input); const struct icmphdr* icmphdr = static_cast<const struct icmphdr*>(payload); // const int icmphdr_size = sizeof(*icmphdr); const int iphdr_len = iphdr->ihl*4; if (icmphdr->type == ICMP_ECHO) { char source[INET_ADDRSTRLEN]; char dest[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &iphdr->saddr, source, INET_ADDRSTRLEN); inet_ntop(AF_INET, &iphdr->daddr, dest, INET_ADDRSTRLEN); printf("%s > %s: ", source, dest); printf("ICMP echo request, id %d, seq %d, length %d\n", ntohs(icmphdr->un.echo.id), ntohs(icmphdr->un.echo.sequence), len - iphdr_len); union { unsigned char output[ETH_FRAME_LEN]; struct { struct iphdr iphdr; struct icmphdr icmphdr; } out; }; memcpy(output, input, len); out.icmphdr.type = ICMP_ECHOREPLY; out.icmphdr.checksum += ICMP_ECHO; // FIXME: not portable std::swap(out.iphdr.saddr, out.iphdr.daddr); write(fd, output, len); } } <file_sep>/python/throughput.py #!/usr/bin/python3 # A simple program to test TCP throughput, by sending 1GiB data. import socket, sys, time def report(name : str, total_bytes : int, elapsed_seconds : float): mbps = total_bytes / 1e6 / elapsed_seconds print('%s transferred %.3fMB in %.3fs, throughput %.3fMB/s %.3fMbits/s' % (name, total_bytes / 1e6, elapsed_seconds, mbps, mbps * 8)) def run_server(port : int): server_socket = socket.create_server(('', port)) # Requires Python 3.8 sock, client_addr = server_socket.accept() print('Got client from %s:%d' % client_addr) start = time.time() total = 0 while True: data = sock.recv(65536) if not data: break total += len(data) report('Receiver', total, time.time() - start) # This client has flaws. def run_client(server : str, port : int): sock = socket.create_connection((server, port)) buf = b'X' * 65536 n = 16384 start = time.time() for i in range(n): sock.sendall(buf) total = len(buf) * n report('Sender', total, time.time() - start) if __name__ == '__main__': if len(sys.argv) < 2: print('Usage: {0} -s or {0} server'.format(sys.argv[0])) elif sys.argv[1] == '-s': run_server(port=2009) else: run_client(sys.argv[1], port=2009) self_result=""" Raspberry Pi 4 running FreeBSD 13-RELEASE: Python: Receiver transferred 1073.742MB in 4.497s, throughput 238.789MB/s 1910.311Mbits/s Transferred 2529.821MB in 10.006s, throughput 252.818MB/s 2022.543Mbits/s, 38602 syscalls 65536.0 Bytes/syscall tcpperf: Transferred 3171.746MB 3024.812MiB in 10.006s, 48397 syscalls, 65536.0 Bytes/syscall 7.000 317.09MB/s 2536.8Mbits/s sndbuf=135.9K snd_cwnd=481.9K ssthresh=1048560.0K snd_wnd=3.2K rtt=281/437 iperf3: [ 5] 0.00-10.00 sec 2.32 GBytes 2.00 Gbits/sec receiver Raspberry Pi 4 running Raspbian GNU/Linux 10, kernel 5.10 Receiver transferred 1073.742MB in 1.783s, throughput 602.052MB/s 4816.417Mbits/s Raspberry Pi 4 running Ubuntu server 21.04 arm64, kernel 5.11 Receiver transferred 1073.742MB in 1.540s, throughput 697.363MB/s 5578.907Mbits/s Raspberry Pi 4 running Debian 11 arm64, kernel 5.10 Python: Receiver transferred 1073.742MB in 1.654s, throughput 649.204MB/s 5193.631Mbits/s Transferred 8186.823MB in 10.000s, throughput 818.647MB/s 6549.173Mbits/s, 125013 syscalls 65487.8 Bytes/syscall tcpperf: Transferred 10737.418MB 10240.000MiB in 7.804s, 163840 syscalls, 65536.0 Bytes/syscall 7.804 1375.92MB/s 11007.4Mbits/s sndbuf=2565.0K snd_cwnd=639.5K ssthresh=2097152.0K snd_wnd=3039.5K rtt=60/8 iperf3: [ 5] 0.00-10.00 sec 13.4 GBytes 11.5 Gbits/sec 0 sender Raspberry Pi 3 running Raspbian GNU/Linux 10, kernel 5.10 Receiver transferred 1073.742MB in 1.938s, throughput 554.156MB/s 4433.249Mbits/s Raspberry Pi 2 running Raspbian GNU/Linux 10, kernel 5.10 Receiver transferred 1073.742MB in 3.696s, throughput 290.500MB/s 2323.996Mbits/s ============================================================================== HP e8300, CPU i7-3770 linux$ iperf3 -c localhost -V iperf 3.9 Linux flute 5.10.0-6-amd64 #1 SMP Debian 5.10.28-1 (2021-04-09) x86_64 Control connection MSS 32768 Time: Sun, 23 May 2021 02:58:38 GMT Connecting to host localhost, port 5201 TCP MSS: 32768 (default) [ 5] local ::1 port 37764 connected to ::1 port 5201 Starting Test: protocol: TCP, 1 streams, 131072 byte blocks, omitting 0 seconds, 10 second test, tos 0 [ ID] Interval Transfer Bitrate Retr Cwnd [ 5] 0.00-1.00 sec 5.17 GBytes 44.4 Gbits/sec 0 959 KBytes [ 5] 1.00-2.00 sec 5.22 GBytes 44.9 Gbits/sec 0 1.25 MBytes [ 5] 2.00-3.00 sec 5.21 GBytes 44.8 Gbits/sec 0 1.25 MBytes [ 5] 3.00-4.00 sec 5.25 GBytes 45.1 Gbits/sec 0 1.25 MBytes [ 5] 4.00-5.00 sec 5.25 GBytes 45.1 Gbits/sec 0 1.25 MBytes [ 5] 5.00-6.00 sec 5.25 GBytes 45.1 Gbits/sec 0 1.25 MBytes [ 5] 6.00-7.00 sec 5.25 GBytes 45.1 Gbits/sec 0 1.25 MBytes [ 5] 7.00-8.00 sec 5.26 GBytes 45.2 Gbits/sec 0 1.25 MBytes [ 5] 8.00-9.00 sec 5.25 GBytes 45.1 Gbits/sec 0 1.25 MBytes [ 5] 9.00-10.00 sec 5.25 GBytes 45.1 Gbits/sec 0 1.25 MBytes - - - - - - - - - - - - - - - - - - - - - - - - - Test Complete. Summary Results: [ ID] Interval Transfer Bitrate Retr [ 5] 0.00-10.00 sec 52.4 GBytes 45.0 Gbits/sec 0 sender [ 5] 0.00-10.00 sec 52.4 GBytes 45.0 Gbits/sec receiver CPU Utilization: local/sender 100.0% (1.5%u/98.5%s), remote/receiver 69.0% (5.0%u/64.0%s) snd_tcp_congestion cubic rcv_tcp_congestion cubic iperf Done. throughput-bidi.py: Transferred 47299.953MB in 10.000s, throughput 4729.937MB/s 37839.492Mbits/s, 721740 syscalls 65536.0 Bytes/syscall tpc/tcpperf: Transferred 53370.749MB 50898.312MiB in 10.000s, 814373 syscalls, 65536.0 Bytes/syscall 10.000 5337.01MB/s 42696.1Mbits/s sndbuf=2565.0K snd_cwnd=639.5K ssthresh=2097152.0K snd_wnd=3039.5K rtt=19/8 freebsd% % iperf3 -c localhost -V iperf 3.9 FreeBSD freebsd 13.0-RELEASE FreeBSD 13.0-RELEASE #0 releng/13.0-n244733-ea31abc261f: Fri Apr 9 04:24:09 UTC 2021 <EMAIL>.freebsd.org:/usr/obj/usr/src/amd64.amd64/sys/GENERIC amd64 Control connection MSS 16344 Time: Sun, 23 May 2021 03:39:04 UTC Connecting to host 172.16.0.77, port 5201 TCP MSS: 16344 (default) [ 5] local 172.16.0.77 port 47020 connected to 172.16.0.77 port 5201 Starting Test: protocol: TCP, 1 streams, 131072 byte blocks, omitting 0 seconds, 10 second test, tos 0 [ ID] Interval Transfer Bitrate Retr Cwnd [ 5] 0.00-1.00 sec 7.99 GBytes 68.7 Gbits/sec 0 1021 KBytes [ 5] 1.00-2.00 sec 8.30 GBytes 71.3 Gbits/sec 0 1021 KBytes [ 5] 2.00-3.00 sec 8.29 GBytes 71.2 Gbits/sec 0 1021 KBytes [ 5] 3.00-4.00 sec 8.36 GBytes 71.8 Gbits/sec 0 1.21 MBytes [ 5] 4.00-5.00 sec 8.37 GBytes 71.9 Gbits/sec 0 1.21 MBytes [ 5] 5.00-6.00 sec 8.41 GBytes 72.2 Gbits/sec 0 1.21 MBytes [ 5] 6.00-7.00 sec 8.38 GBytes 72.0 Gbits/sec 0 1.21 MBytes [ 5] 7.00-8.00 sec 8.39 GBytes 72.0 Gbits/sec 0 1.21 MBytes [ 5] 8.00-9.00 sec 8.33 GBytes 71.5 Gbits/sec 0 1.25 MBytes [ 5] 9.00-10.00 sec 8.33 GBytes 71.6 Gbits/sec 0 1.25 MBytes - - - - - - - - - - - - - - - - - - - - - - - - - Test Complete. Summary Results: [ ID] Interval Transfer Bitrate Retr [ 5] 0.00-10.00 sec 83.2 GBytes 71.4 Gbits/sec 0 sender [ 5] 0.00-10.00 sec 83.2 GBytes 71.4 Gbits/sec receiver CPU Utilization: local/sender 98.3% (2.7%u/95.7%s), remote/receiver 78.2% (1.8%u/76.3%s) snd_tcp_congestion newreno rcv_tcp_congestion newreno iperf Done. throughput-bidi.py: Transferred 65850.835MB in 10.000s, throughput 6584.994MB/s 52679.952Mbits/s, 1004804 syscalls 65536.0 Bytes/syscall tpc/tcpperf: Transferred 83659.260MB 79783.688MiB in 10.000s, 1276539 syscalls, 65536.0 Bytes/syscall 10.000 8456.80MB/s 67654.4Mbits/s sndbuf=647.9K snd_cwnd=1387.7K ssthresh=1048560.0K snd_wnd=667.6K rtt=218/187 """ <file_sep>/basic/build.sh #!/bin/sh set -x mkdir -p bin g++ test.cc uint.cc -o bin/test-dbg -Wall -Wextra -g -O0 \ -DBOOST_TEST_DYN_LINK -lboost_unit_test_framework g++ test.cc uint.cc -o bin/test-opt -Wall -Wextra -g -O2 -DNDEBUG \ -DBOOST_TEST_DYN_LINK -lboost_unit_test_framework g++ bench.cc uint.cc -o bin/bench-dbg -Wall -Wextra -g -O0 g++ bench.cc uint.cc -o bin/bench-opt -Wall -Wextra -g -O2 -DNDEBUG g++ exact.cc uint.cc -o bin/exact-dbg -Wall -Wextra -g -O0 g++ factorial.cc uint.cc -o bin/factorial-opt -Wall -Wextra -g -O2 -DNDEBUG g++ fibonacci.cc uint.cc -o bin/fibonacci-opt -Wall -Wextra -g -O2 -DNDEBUG g++ combination.cc uint.cc -o bin/combination-opt -Wall -Wextra -g -O2 -DNDEBUG g++ partitions.cc uint.cc -o bin/partition-opt -Wall -Wextra -g -O2 -DNDEBUG g++ numheaps.cc uint.cc -o bin/numheaps-opt -std=c++0x -Wall -Wextra -g -O2 -DNDEBUG <file_sep>/protorpc/sudoku/Server.java package sudoku; import muduo.rpc.NewChannelCallback; import muduo.rpc.RpcChannel; import muduo.rpc.RpcServer; public class Server { public static void main(String[] args) { RpcServer server = new RpcServer(); server.registerService(Sudoku.SudokuService.newReflectiveService(new SudokuImpl())); server.setNewChannelCallback(new NewChannelCallback() { @Override public void run(RpcChannel channel) { // TODO call client } }); server.start(9981); } } <file_sep>/topk/gen.py #!/usr/bin/python3 import numpy words = 100*1000*1000 S = 1.0001 output = open('random_words', 'w') for x in range(words): output.write("%x\n" % numpy.random.zipf(S)) <file_sep>/protorpc/run_client.sh #!/bin/sh java -ea -server -Djava.ext.dirs=lib -cp bin echo.EchoClient $1 <file_sep>/python/tcprelay2.py #!/usr/bin/python import socket, thread, time def forward(source, destination): source_addr = source.getpeername() while True: # FIXME: error handling data = source.recv(4096) # Connection reset by peer if data: destination.sendall(data) # Broken pipe else: print 'disconnect', source_addr destination.shutdown(socket.SHUT_WR) break listensocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listensocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listensocket.bind(('', 2000)) listensocket.listen(5) while True: (serversocket, address) = listensocket.accept() print 'accepted', address clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientsocket.connect(('localhost', 3000)) print 'connected', clientsocket.getpeername() thread.start_new_thread(forward, (serversocket, clientsocket)) thread.start_new_thread(forward, (clientsocket, serversocket)) <file_sep>/ssl/client.cc #include "timer.h" #include "TlsConfig.h" #include "TlsStream.h" int main(int argc, char* argv[]) { TlsConfig config; config.setCaFile("ca.pem"); const char* hostport = "localhost:4433"; if (argc > 1) hostport = argv[1]; TlsStreamPtr stream = TlsStream::connect(&config, hostport, "Test Server Cert"); if (stream) { LOG_INFO << "OK"; char buf[16384] = { 0 }; int64_t total = 0; Timer t; t.start(); while (total < 1e10) { int nw = stream->sendSome(buf, sizeof buf); total += nw; } t.stop(); LOG_INFO << t.seconds(); // FIXME: getrusage() } } <file_sep>/faketcp/connectmany.cc #include "faketcp.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <linux/if_ether.h> void tcp_input(int fd, const void* input, const void* payload, int tot_len, bool passive) { const struct iphdr* iphdr = static_cast<const struct iphdr*>(input); const struct tcphdr* tcphdr = static_cast<const struct tcphdr*>(payload); const int iphdr_len = iphdr->ihl*4; const int tcp_seg_len = tot_len - iphdr_len; const int tcphdr_size = sizeof(*tcphdr); if (tcp_seg_len >= tcphdr_size && tcp_seg_len >= tcphdr->doff*4) { const int tcphdr_len = tcphdr->doff*4; const int payload_len = tot_len - iphdr_len - tcphdr_len; char source[INET_ADDRSTRLEN]; char dest[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &iphdr->saddr, source, INET_ADDRSTRLEN); inet_ntop(AF_INET, &iphdr->daddr, dest, INET_ADDRSTRLEN); printf("IP %s.%d > %s.%d: ", source, ntohs(tcphdr->source), dest, ntohs(tcphdr->dest)); printf("Flags [%c], seq %u, win %d, length %d\n", tcphdr->syn ? 'S' : (tcphdr->fin ? 'F' : '.'), ntohl(tcphdr->seq), ntohs(tcphdr->window), payload_len); union { unsigned char output[ETH_FRAME_LEN]; struct { struct iphdr iphdr; struct tcphdr tcphdr; } out; }; assert(sizeof(out) == sizeof(struct iphdr) + sizeof(struct tcphdr)); int output_len = sizeof(out); bzero(&out, output_len + 4); memcpy(output, input, sizeof(struct iphdr)); out.iphdr.tot_len = htons(output_len); std::swap(out.iphdr.saddr, out.iphdr.daddr); out.iphdr.check = 0; out.iphdr.check = in_checksum(output, sizeof(struct iphdr)); out.tcphdr.source = tcphdr->dest; out.tcphdr.dest = tcphdr->source; out.tcphdr.doff = sizeof(struct tcphdr) / 4; out.tcphdr.window = htons(5000); bool response = false; if (tcphdr->syn) { out.tcphdr.seq = htonl(passive ? 123456 : 123457); out.tcphdr.ack_seq = htonl(ntohl(tcphdr->seq)+1); if (passive) { out.tcphdr.syn = 1; } out.tcphdr.ack = 1; response = true; } else if (tcphdr->fin) { out.tcphdr.seq = htonl(123457); out.tcphdr.ack_seq = htonl(ntohl(tcphdr->seq)+1); out.tcphdr.fin = 1; out.tcphdr.ack = 1; response = true; } else if (payload_len > 0) { out.tcphdr.seq = htonl(123457); out.tcphdr.ack_seq = htonl(ntohl(tcphdr->seq)+payload_len); out.tcphdr.ack = 1; response = true; } unsigned char* pseudo = output + output_len; pseudo[0] = 0; pseudo[1] = IPPROTO_TCP; pseudo[2] = 0; pseudo[3] = sizeof(struct tcphdr); out.tcphdr.check = in_checksum(&out.iphdr.saddr, sizeof(struct tcphdr)+12); if (response) { write(fd, output, output_len); } } } bool connect_one(int fd, uint32_t daddr, int dport, uint32_t saddr, int sport) { { union { unsigned char output[ETH_FRAME_LEN]; struct { struct iphdr iphdr; struct tcphdr tcphdr; } out; }; bzero(&out, (sizeof out)+4); out.iphdr.version = IPVERSION; out.iphdr.ihl = sizeof(out.iphdr)/4; out.iphdr.tos = 0; out.iphdr.tot_len = htons(sizeof(out)); out.iphdr.id = 55564; out.iphdr.frag_off |= htons(IP_DF); out.iphdr.ttl = IPDEFTTL; out.iphdr.protocol = IPPROTO_TCP; out.iphdr.saddr = saddr; out.iphdr.daddr = daddr; out.iphdr.check = in_checksum(output, sizeof(struct iphdr)); out.tcphdr.source = sport; out.tcphdr.dest = dport; out.tcphdr.seq = htonl(123456); out.tcphdr.ack_seq = 0; out.tcphdr.doff = sizeof(out.tcphdr)/4; out.tcphdr.syn = 1; out.tcphdr.window = htons(4096); unsigned char* pseudo = output + sizeof out; pseudo[0] = 0; pseudo[1] = IPPROTO_TCP; pseudo[2] = 0; pseudo[3] = sizeof(struct tcphdr); out.tcphdr.check = in_checksum(&out.iphdr.saddr, sizeof(struct tcphdr)+12); write(fd, output, sizeof out); } union { unsigned char buf[ETH_FRAME_LEN]; struct iphdr iphdr; }; const int iphdr_size = sizeof iphdr; int nread = read(fd, buf, sizeof(buf)); if (nread < 0) { perror("read"); close(fd); exit(1); } // printf("read %d bytes from tunnel interface %s.\n", nread, ifname); if (nread >= iphdr_size && iphdr.version == 4 && iphdr.ihl*4 >= iphdr_size && iphdr.ihl*4 <= nread && iphdr.tot_len == htons(nread) && in_checksum(buf, iphdr.ihl*4) == 0) { const void* payload = buf + iphdr.ihl*4; if (iphdr.protocol == IPPROTO_ICMP) { icmp_input(fd, buf, payload, nread); } else if (iphdr.protocol == IPPROTO_TCP) { tcp_input(fd, buf, payload, nread, false); } } return true; } void connect_many(int fd, const char* ipstr, int port, int count) { uint32_t destip; inet_pton(AF_INET, ipstr, &destip); uint32_t srcip = ntohl(destip)+1; int srcport = 1024; for (int i = 0; i < count; ++i) { connect_one(fd, destip, htons(port), htonl(srcip), htons(srcport)); srcport++; if (srcport > 0xFFFF) { srcport = 1024; srcip++; } } } void usage() { } int main(int argc, char* argv[]) { if (argc < 4) { usage(); return 0; } char ifname[IFNAMSIZ] = "tun%d"; int fd = tun_alloc(ifname); if (fd < 0) { fprintf(stderr, "tunnel interface allocation failed\n"); exit(1); } const char* ip = argv[1]; int port = atoi(argv[2]); int count = atoi(argv[3]); printf("allocted tunnel interface %s\n", ifname); printf("press enter key to start connecting %s:%d\n", ip, port); getchar(); connect_many(fd, ip, port, count); for (;;) { union { unsigned char buf[ETH_FRAME_LEN]; struct iphdr iphdr; }; const int iphdr_size = sizeof iphdr; int nread = read(fd, buf, sizeof(buf)); if (nread < 0) { perror("read"); close(fd); exit(1); } printf("read %d bytes from tunnel interface %s.\n", nread, ifname); const int iphdr_len = iphdr.ihl*4; if (nread >= iphdr_size && iphdr.version == 4 && iphdr_len >= iphdr_size && iphdr_len <= nread && iphdr.tot_len == htons(nread) && in_checksum(buf, iphdr_len) == 0) { const void* payload = buf + iphdr_len; if (iphdr.protocol == IPPROTO_ICMP) { icmp_input(fd, buf, payload, nread); } else if (iphdr.protocol == IPPROTO_TCP) { tcp_input(fd, buf, payload, nread, true); } } else { printf("bad packet\n"); for (int i = 0; i < nread; ++i) { if (i % 4 == 0) printf("\n"); printf("%02x ", buf[i]); } printf("\n"); } } return 0; } <file_sep>/ssl/footprint-openssl.cc #include <openssl/aes.h> #include <openssl/conf.h> #include <openssl/err.h> #include <openssl/ssl.h> #include <malloc.h> #include <mcheck.h> #include <stdio.h> #include "timer.h" #include <string> #include <vector> void (*old_free_hook) (void *__ptr, const void *); void *(*old_malloc_hook)(size_t __size, const void *); void my_free_hook (void*, const void *); void* my_malloc_hook(size_t size, const void* caller) { void *result; /* Restore all old hooks */ __malloc_hook = old_malloc_hook; __free_hook = old_free_hook; /* Call recursively */ result = malloc (size); /* Save underlying hooks */ old_malloc_hook = __malloc_hook; old_free_hook = __free_hook; /* printf might call malloc, so protect it too. */ printf ("%p malloc (%u) returns %p\n", caller, (unsigned int) size, result); /* Restore our own hooks */ __malloc_hook = my_malloc_hook; __free_hook = my_free_hook; return result; } void my_free_hook (void *ptr, const void *caller) { if (!ptr) return; /* Restore all old hooks */ __malloc_hook = old_malloc_hook; __free_hook = old_free_hook; /* Call recursively */ free (ptr); /* Save underlying hooks */ old_malloc_hook = __malloc_hook; old_free_hook = __free_hook; /* printf might call free, so protect it too. */ printf ("freed %p\n", ptr); /* Restore our own hooks */ __malloc_hook = my_malloc_hook; __free_hook = my_free_hook; } void init_hook() { old_malloc_hook = __malloc_hook; old_free_hook = __free_hook; __malloc_hook = my_malloc_hook; __free_hook = my_free_hook; } int main(int argc, char* argv[]) { SSL_load_error_strings(); ERR_load_BIO_strings(); SSL_library_init(); OPENSSL_config(NULL); SSL_CTX* ctx = SSL_CTX_new(TLSv1_2_server_method()); SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION); EC_KEY* ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE); SSL_CTX_set_tmp_ecdh(ctx, ecdh); EC_KEY_free(ecdh); const char* CertFile = "server.pem"; // argv[1]; const char* KeyFile = "server.pem"; // argv[2]; SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM); SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM); if (!SSL_CTX_check_private_key(ctx)) abort(); SSL_CTX* ctx_client = SSL_CTX_new(TLSv1_2_client_method()); init_hook(); const int N = 10; SSL *ssl, *ssl_client; std::vector<SSL*> ssls; for (int i = 0; i < N; ++i) { printf("=============================================== BIO_new_bio_pair %d\n", i); BIO *client, *server; BIO_new_bio_pair(&client, 0, &server, 0); printf("=============================================== SSL_new server %d\n", i); ssl = SSL_new (ctx); printf("=============================================== SSL_new client %d\n", i); ssl_client = SSL_new (ctx_client); SSL_set_bio(ssl, server, server); SSL_set_bio(ssl_client, client, client); printf("=============================================== SSL_connect client %d\n", i); int ret = SSL_connect(ssl_client); printf("=============================================== SSL_accept server %d\n", i); int ret2 = SSL_accept(ssl); while (true) { printf("=============================================== SSL_handshake client %d\n", i); ret = SSL_do_handshake(ssl_client); printf("=============================================== SSL_handshake server %d\n", i); ret2 = SSL_do_handshake(ssl); if (ret == 1 && ret2 == 1) break; } if (i == 0) printf ("SSL connection using %s %s\n", SSL_get_version(ssl_client), SSL_get_cipher (ssl_client)); /* if (i != N-1) { printf("=============================================== SSL_free server %d\n", i); SSL_free (ssl); printf("=============================================== SSL_free client %d\n", i); SSL_free (ssl_client); } else */ { ssls.push_back(ssl); ssls.push_back(ssl_client); } } printf("=============================================== data \n"); double start2 = now(); const int M = 300; char buf[1024] = { 0 }; for (int i = 0; i < M*1024; ++i) { int nw = SSL_write(ssl_client, buf, sizeof buf); if (nw != sizeof buf) { printf("nw = %d\n", nw); } int nr = SSL_read(ssl, buf, sizeof buf); if (nr != sizeof buf) { printf("nr = %d\n", nr); } } double elapsed = now() - start2; printf("%.2f %.1f MiB/s\n", elapsed, M / elapsed); printf("=============================================== SSL_free\n"); for (int i = 0; i < ssls.size(); ++i) SSL_free(ssls[i]); printf("=============================================== SSL_CTX_free\n"); SSL_CTX_free (ctx); SSL_CTX_free (ctx_client); // OPENSSL_cleanup(); // only in 1.1.0 printf("=============================================== end\n"); } <file_sep>/puzzle/waterpour.cc #include <set> #include <vector> #include <assert.h> #include <stdio.h> #include <stdlib.h> struct State { int big; int small; State(int b = 0, int s = 0) : big(b), small(s) { } bool operator==(const State& rhs) const { return big == rhs.big && small == rhs.small; } bool operator!=(const State& rhs) const { return !(*this == rhs); } bool operator<(const State& rhs) const { return big < rhs.big || (big == rhs.big && small < rhs.small); } }; struct Step { State st; int parent; Step(const State& s, int p) : st(s), parent(p) { } }; // not used anymore bool exist(const std::vector<Step>& steps, int curr, State next) { while (curr >= 0) { assert(curr < steps.size()); if (next == steps[curr].st) return true; else curr = steps[curr].parent; } return false; } void print(const std::vector<Step>& steps, int curr) { while (curr >= 0) { printf("%d %d\n", steps[curr].st.big, steps[curr].st.small); curr = steps[curr].parent; } } int main(int argc, char* argv[]) { if (argc == 4) { const int kBig = atoi(argv[1]); const int kSmall = atoi(argv[2]); const State kFinal(atoi(argv[3]), 0); std::vector<Step> steps; std::set<State> seen; steps.push_back(Step(State(), -1)); int curr = 0; while (steps[curr].st != kFinal) { assert(curr < steps.size()); const int big = steps[curr].st.big; const int small = steps[curr].st.small; // printf("%d: %d %d\n", curr, big, small); assert(steps[curr].parent != curr); if (seen.insert(steps[curr].st).second) { if (big > 0) { State next(0, small); assert(steps[curr].st != next); // if (!exist(steps, curr, next)) if (seen.find(next) == seen.end()) steps.push_back(Step(next, curr)); } if (small > 0) { State next(big, 0); assert(steps[curr].st != next); // if (!exist(steps, curr, next)) if (seen.find(next) == seen.end()) steps.push_back(Step(next, curr)); } if (big < kBig) { State next(kBig, small); assert(steps[curr].st != next); // if (!exist(steps, curr, next)) if (seen.find(next) == seen.end()) steps.push_back(Step(next, curr)); } if (small < kSmall) { State next(big, kSmall); assert(steps[curr].st != next); // if (!exist(steps, curr, next)) if (seen.find(next) == seen.end()) steps.push_back(Step(next, curr)); } if (big > 0 && small < kSmall) { State next; int smallSpace = kSmall - small; if (big > smallSpace) next = State(big - smallSpace, small + smallSpace); else next = State(0, small + big); assert(big + small == next.big + next.small); assert(steps[curr].st != next); // if (!exist(steps, curr, next)) if (seen.find(next) == seen.end()) steps.push_back(Step(next, curr)); } if (big < kBig && small > 0) { State next; int bigSpace = kBig - big; if (small > bigSpace) next = State(kBig, small - bigSpace); else next = State(small + big, 0); assert(big + small == next.big + next.small); assert(steps[curr].st != next); // if (!exist(steps, curr, next)) if (seen.find(next) == seen.end()) steps.push_back(Step(next, curr)); } } else { // printf("seen\n"); } if (++curr >= steps.size()) break; } if (steps[curr].st == kFinal) { printf("Found! %zd %zd\n", steps.size(), seen.size()); print(steps, curr); } else { printf("Not Found! %zd %zd\n", steps.size(), seen.size()); } } else { printf("Usage: %s volumeA volumeB target\n", argv[0]); } } <file_sep>/java/bankqueue/tests/BankTest.java package bankqueue.tests; import java.io.StringWriter; import java.util.ArrayList; import java.util.Random; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import bankqueue.Bank; import bankqueue.customer.CustomerFactory; import bankqueue.customer.CustomerType; import bankqueue.customer.FastCustomer; import bankqueue.customer.NormalCustomer; import bankqueue.customer.VipCustomer; import bankqueue.event.CustomerArriveEvent; public class BankTest { ArrayList<CustomerArriveEvent> events; StringWriter sw; Bank bank; String concat(String... lines) { StringBuilder sb = new StringBuilder(); for (String line : lines) { sb.append(line).append("\n"); } return sb.toString(); } @Before public void setUp() { events = new ArrayList<CustomerArriveEvent>(); sw = new StringWriter(); bank = new Bank(); } @Test public void testGetCustomerType() { Random r = new Random(); final int numTotolCustomers = 100000; int numNormalCustomers = 0; int numFastCustomers = 0; int numVipCustomers = 0; for (int i = 0; i < numTotolCustomers; ++i) { CustomerType type = CustomerFactory.getCustomerType(r); switch (type) { case kNormal: ++numNormalCustomers; break; case kFast: ++numFastCustomers; break; case kVip: ++numVipCustomers; break; } } double delta = 0.01; assertEquals(0.6, 1.0 * numNormalCustomers / numTotolCustomers, delta); assertEquals(0.3, 1.0 * numFastCustomers / numTotolCustomers, delta); assertEquals(0.1, 1.0 * numVipCustomers / numTotolCustomers, delta); } @Test public void noCustomer() { bank.dryrun(events, sw); assertEquals("", sw.toString()); } @Test public void oneNormalCustomer() { events.add(new CustomerArriveEvent(0, new NormalCustomer(0, 5), bank)); bank.dryrun(events, sw); assertEquals(concat( "time 0 NormalCustomer( 0) arrives, service time = 5", "time 0 NormalCustomer( 0) sits at kNormal window, will leave at 5", "time 5 NormalCustomer( 0) leaves window kNormal", "time 5 spare window kNormal"), sw.toString()); } @Test public void oneFastCustomer() { events.add(new CustomerArriveEvent(0, new FastCustomer(0, 5), bank)); bank.dryrun(events, sw); assertEquals(concat( "time 0 FastCustomer( 0) arrives, service time = 5", "time 0 FastCustomer( 0) sits at kFast window, will leave at 5", "time 5 FastCustomer( 0) leaves window kFast", "time 5 spare window kFast"), sw.toString()); } @Test public void oneVipCustomer() { events.add(new CustomerArriveEvent(0, new VipCustomer(0, 5), bank)); bank.dryrun(events, sw); assertEquals(concat( "time 0 VipCustomer( 0) arrives, service time = 5", "time 0 VipCustomer( 0) sits at kVip window, will leave at 5", "time 5 VipCustomer( 0) leaves window kVip", "time 5 spare window kVip"), sw.toString()); } @Test public void twoFastCustomers() { events.add(new CustomerArriveEvent(0, new FastCustomer(0, 5), bank)); events.add(new CustomerArriveEvent(10, new FastCustomer(1, 8), bank)); bank.dryrun(events, sw); assertEquals(concat( "time 0 FastCustomer( 0) arrives, service time = 5", "time 0 FastCustomer( 0) sits at kFast window, will leave at 5", "time 5 FastCustomer( 0) leaves window kFast", "time 5 spare window kFast", "time 10 FastCustomer( 1) arrives, service time = 8", "time 10 FastCustomer( 1) sits at kFast window, will leave at 18", "time 18 FastCustomer( 1) leaves window kFast", "time 18 spare window kFast" ), sw.toString()); } @Test public void twoVipCustomers() { events.add(new CustomerArriveEvent(0, new VipCustomer(0, 10), bank)); events.add(new CustomerArriveEvent(5, new VipCustomer(1, 10), bank)); bank.dryrun(events, sw); assertEquals(concat( "time 0 VipCustomer( 0) arrives, service time = 10", "time 0 VipCustomer( 0) sits at kVip window, will leave at 10", "time 5 VipCustomer( 1) arrives, service time = 10", "time 5 VipCustomer( 1) waits in queue", "time 10 VipCustomer( 0) leaves window kVip", "time 10 VipCustomer( 1) found for spare window kVip", "time 10 VipCustomer( 1) sits at kVip window, will leave at 20", "time 20 VipCustomer( 1) leaves window kVip", "time 20 spare window kVip" ), sw.toString()); } @Test public void sixNormalCustomers() { events.add(new CustomerArriveEvent(0, new NormalCustomer(0, 10), bank)); events.add(new CustomerArriveEvent(1, new NormalCustomer(1, 10), bank)); events.add(new CustomerArriveEvent(2, new NormalCustomer(2, 10), bank)); events.add(new CustomerArriveEvent(3, new NormalCustomer(3, 10), bank)); events.add(new CustomerArriveEvent(4, new NormalCustomer(4, 10), bank)); events.add(new CustomerArriveEvent(5, new NormalCustomer(5, 10), bank)); bank.dryrun(events, sw); assertEquals(concat( "time 0 NormalCustomer( 0) arrives, service time = 10", "time 0 NormalCustomer( 0) sits at kNormal window, will leave at 10", "time 1 NormalCustomer( 1) arrives, service time = 10", "time 1 NormalCustomer( 1) sits at kNormal window, will leave at 11", "time 2 NormalCustomer( 2) arrives, service time = 10", "time 2 NormalCustomer( 2) sits at kNormal window, will leave at 12", "time 3 NormalCustomer( 3) arrives, service time = 10", "time 3 NormalCustomer( 3) sits at kNormal window, will leave at 13", "time 4 NormalCustomer( 4) arrives, service time = 10", "time 4 NormalCustomer( 4) sits at kFast window, will leave at 14", "time 5 NormalCustomer( 5) arrives, service time = 10", "time 5 NormalCustomer( 5) sits at kVip window, will leave at 15", "time 10 NormalCustomer( 0) leaves window kNormal", "time 10 spare window kNormal", "time 11 NormalCustomer( 1) leaves window kNormal", "time 11 spare window kNormal", "time 12 NormalCustomer( 2) leaves window kNormal", "time 12 spare window kNormal", "time 13 NormalCustomer( 3) leaves window kNormal", "time 13 spare window kNormal", "time 14 NormalCustomer( 4) leaves window kFast", "time 14 spare window kFast", "time 15 NormalCustomer( 5) leaves window kVip", "time 15 spare window kVip" ), sw.toString()); } @Test public void sevenCustomers() { events.add(new CustomerArriveEvent(0, new VipCustomer(0, 10), bank)); events.add(new CustomerArriveEvent(1, new NormalCustomer(1, 10), bank)); events.add(new CustomerArriveEvent(2, new NormalCustomer(2, 10), bank)); events.add(new CustomerArriveEvent(3, new NormalCustomer(3, 10), bank)); events.add(new CustomerArriveEvent(4, new NormalCustomer(4, 10), bank)); events.add(new CustomerArriveEvent(5, new NormalCustomer(5, 10), bank)); events.add(new CustomerArriveEvent(6, new NormalCustomer(6, 10), bank)); bank.dryrun(events, sw); assertEquals(concat( "time 0 VipCustomer( 0) arrives, service time = 10", "time 0 VipCustomer( 0) sits at kVip window, will leave at 10", "time 1 NormalCustomer( 1) arrives, service time = 10", "time 1 NormalCustomer( 1) sits at kNormal window, will leave at 11", "time 2 NormalCustomer( 2) arrives, service time = 10", "time 2 NormalCustomer( 2) sits at kNormal window, will leave at 12", "time 3 NormalCustomer( 3) arrives, service time = 10", "time 3 NormalCustomer( 3) sits at kNormal window, will leave at 13", "time 4 NormalCustomer( 4) arrives, service time = 10", "time 4 NormalCustomer( 4) sits at kNormal window, will leave at 14", "time 5 NormalCustomer( 5) arrives, service time = 10", "time 5 NormalCustomer( 5) sits at kFast window, will leave at 15", "time 6 NormalCustomer( 6) arrives, service time = 10", "time 6 NormalCustomer( 6) waits in queue", "time 10 VipCustomer( 0) leaves window kVip", "time 10 NormalCustomer( 6) found for spare window kVip", "time 10 NormalCustomer( 6) sits at kVip window, will leave at 20", "time 11 NormalCustomer( 1) leaves window kNormal", "time 11 spare window kNormal", "time 12 NormalCustomer( 2) leaves window kNormal", "time 12 spare window kNormal", "time 13 NormalCustomer( 3) leaves window kNormal", "time 13 spare window kNormal", "time 14 NormalCustomer( 4) leaves window kNormal", "time 14 spare window kNormal", "time 15 NormalCustomer( 5) leaves window kFast", "time 15 spare window kFast", "time 20 NormalCustomer( 6) leaves window kVip", "time 20 spare window kVip" ), sw.toString()); } @Test public void eightCustomers() { events.add(new CustomerArriveEvent(0, new VipCustomer(0, 10), bank)); events.add(new CustomerArriveEvent(1, new NormalCustomer(1, 10), bank)); events.add(new CustomerArriveEvent(2, new NormalCustomer(2, 10), bank)); events.add(new CustomerArriveEvent(3, new NormalCustomer(3, 10), bank)); events.add(new CustomerArriveEvent(4, new NormalCustomer(4, 10), bank)); events.add(new CustomerArriveEvent(5, new NormalCustomer(5, 10), bank)); events.add(new CustomerArriveEvent(6, new NormalCustomer(6, 10), bank)); events.add(new CustomerArriveEvent(7, new VipCustomer(7, 10), bank)); bank.dryrun(events, sw); assertEquals(concat( "time 0 VipCustomer( 0) arrives, service time = 10", "time 0 VipCustomer( 0) sits at kVip window, will leave at 10", "time 1 NormalCustomer( 1) arrives, service time = 10", "time 1 NormalCustomer( 1) sits at kNormal window, will leave at 11", "time 2 NormalCustomer( 2) arrives, service time = 10", "time 2 NormalCustomer( 2) sits at kNormal window, will leave at 12", "time 3 NormalCustomer( 3) arrives, service time = 10", "time 3 NormalCustomer( 3) sits at kNormal window, will leave at 13", "time 4 NormalCustomer( 4) arrives, service time = 10", "time 4 NormalCustomer( 4) sits at kNormal window, will leave at 14", "time 5 NormalCustomer( 5) arrives, service time = 10", "time 5 NormalCustomer( 5) sits at kFast window, will leave at 15", "time 6 NormalCustomer( 6) arrives, service time = 10", "time 6 NormalCustomer( 6) waits in queue", "time 7 VipCustomer( 7) arrives, service time = 10", "time 7 VipCustomer( 7) waits in queue", "time 10 VipCustomer( 0) leaves window kVip", "time 10 VipCustomer( 7) found for spare window kVip", "time 10 VipCustomer( 7) sits at kVip window, will leave at 20", "time 11 NormalCustomer( 1) leaves window kNormal", "time 11 NormalCustomer( 6) found for spare window kNormal", "time 11 NormalCustomer( 6) sits at kNormal window, will leave at 21", "time 12 NormalCustomer( 2) leaves window kNormal", "time 12 spare window kNormal", "time 13 NormalCustomer( 3) leaves window kNormal", "time 13 spare window kNormal", "time 14 NormalCustomer( 4) leaves window kNormal", "time 14 spare window kNormal", "time 15 NormalCustomer( 5) leaves window kFast", "time 15 spare window kFast", "time 20 VipCustomer( 7) leaves window kVip", "time 20 spare window kVip", "time 21 NormalCustomer( 6) leaves window kNormal", "time 21 spare window kNormal" ), sw.toString()); } } <file_sep>/pingpong/muduo/single_thread.sh #!/bin/sh killall pingpong_server timeout=${timeout:-100} bufsize=${bufsize:-16384} nothreads=1 for nosessions in 1 10 100 1000 10000; do sleep 5 echo "Bufsize: $bufsize Threads: $nothreads Sessions: $nosessions" taskset -c 1 bin/pingpong_server 0.0.0.0 33333 $nothreads $bufsize & srvpid=$! sleep 1 taskset -c 2 bin/pingpong_client 127.0.0.1 33333 $nothreads $bufsize $nosessions $timeout kill -9 $srvpid done <file_sep>/topk/split.cc #include <fstream> #include <memory> std::string getOutputName(int n) { char buf[256]; snprintf(buf, sizeof buf, "input-%03d", n); printf("%s\n", buf); return buf; } int main(int argc, char* argv[]) { std::ifstream in(argv[1]); std::string line; int count = 0; int size = 0; int64_t total = 0; std::unique_ptr<std::ofstream> out(new std::ofstream(getOutputName(count))); while (getline(in, line)) { line.append("\n"); size += line.size(); total += size; *out << line; if (size >= 1000'000'000) { ++count; out.reset(new std::ofstream(getOutputName(count))); size = 0; } } // out.reset(); } <file_sep>/java/bankqueue/WindowType.java package bankqueue; public enum WindowType { kNormal, kFast, kVip, kNumWindows } <file_sep>/puzzle/nqueens_mt.cc #include <algorithm> #include <atomic> #include <thread> #include <vector> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <sys/time.h> double now() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec / 1000000.0; } struct BackTracking { const static int kMaxQueens = 20; const int N; int64_t count; bool columns[kMaxQueens]; bool diagnoal[2*kMaxQueens], antidiagnoal[2*kMaxQueens]; BackTracking(int nqueens) : N(nqueens), count(0) { assert(0 < N && N <= kMaxQueens); bzero(columns, sizeof columns); bzero(diagnoal, sizeof diagnoal); bzero(antidiagnoal, sizeof antidiagnoal); } void search(const int row) { for (int i = 0; i < N; ++i) { const int d = N + row - i; if (!(columns[i] || antidiagnoal[row + i] || diagnoal[d])) { if (row == N - 1) ++count; else { columns[i] = true; antidiagnoal[row + i] = true; diagnoal[d] = true; search(row+1); columns[i] = false; antidiagnoal[row + i] = false; diagnoal[d] = false; } } } } }; int64_t backtrackingsub(int N, int i) { const int row = 0; const int d = N + row - i; BackTracking bt(N); bt.columns[i] = true; bt.antidiagnoal[row + i] = true; bt.diagnoal[d] = true; bt.search(row+1); return bt.count; } // verify task splitting int64_t backtracking(int N) { int64_t total = 0; for (int i = 0; i < N/2; ++i) { total += backtrackingsub(N, i); } total *= 2; if (N % 2 == 1) { total += backtrackingsub(N, N/2); } return total; } void backtracking_thr(std::atomic<int64_t>* total, int N, int i) { // printf("%d %d\n", i, backtrackingsub(N, i)); if (N % 2 == 1 && i == N / 2) { total->fetch_add(backtrackingsub(N, i)); } else { total->fetch_add(2*backtrackingsub(N, i)); } } int64_t backtracking_mt(int N) { std::atomic<int64_t> total(0); std::vector<std::thread> threads; for (int i = 0; i < N/2; ++i) { threads.push_back(std::thread(backtracking_thr, &total, N, i)); } if (N % 2 == 1) { threads.push_back(std::thread(backtracking_thr, &total, N, N/2)); } for (auto& thr : threads) { thr.join(); } return total; } int main(int argc, char* argv[]) { int nqueens = argc > 1 ? atoi(argv[1]) : 8; double start = now(); int64_t solutions = backtracking_mt(nqueens); double end = now(); printf("%ld solutions of %d queens puzzle.\n", solutions, nqueens); printf("%f seconds.\n", end - start); } <file_sep>/algorithm/permutation.cc #include <algorithm> #include <iostream> #include <iterator> #include <vector> int main() { int elements[] = { 1, 2, 3, 4 }; const size_t N = sizeof(elements)/sizeof(elements[0]); std::vector<int> vec(elements, elements + N); int count = 0; do { std::cout << ++count << ": "; std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, ", ")); std::cout << std::endl; } while (next_permutation(vec.begin(), vec.end())); } <file_sep>/basic/tutorial/factorial.cc #include <assert.h> #include <stdio.h> #include <vector> // each element < 10000 // LSB first, ie. little endian typedef std::vector<int> BigInt; BigInt factorial(int n) { // 9999 * 9999 < 10000 * 10000 = 100000000 < 1073741824 = 2 ** 30 assert(n >= 0 && n <= 10000); BigInt result; result.push_back(1); for (int factor = 1; factor <= n; ++factor) { int carry = 0; for (auto& item : result) { int product = item * factor + carry; item = product % 10000; carry = product / 10000; } if (carry > 0) { result.push_back(carry); } } return result; } void printBigInt(const BigInt& number) { if (number.empty()) { printf("0\n"); // compiles to puts() } else { printf("%d", number.back()); for (auto it = number.rbegin()+1; it != number.rend(); ++it) printf("%04d", *it); printf("\n"); } } int main() { /* for (int i = 0; i <= 10000; ++i) { BigInt result = factorial(i); printf("%d: ", i); printBigInt(result); } */ BigInt result = factorial(10000); printBigInt(result); } <file_sep>/tpc/include/InetAddress.h #pragma once #include "Common.h" #include <string> #include <vector> #include <netinet/in.h> #include <sys/socket.h> class InetAddress : copyable { public: // Invalid address InetAddress() { addr_.sin_family = AF_UNSPEC; } // for connecting InetAddress(StringArg ip, uint16_t port); // for listening explicit InetAddress(uint16_t port, bool ipv6 = false); // interface with Sockets API explicit InetAddress(const struct sockaddr& saddr); // default copy/assignment are Okay sa_family_t family() const { return addr_.sin_family; } uint16_t port() const { return ntohs(addr_.sin_port); } void setPort(uint16_t port) { addr_.sin_port = htons(port); } std::string toIp() const; std::string toIpPort() const; // Interface with Sockets API const struct sockaddr* get_sockaddr() const { return reinterpret_cast<const struct sockaddr*>(&addr6_); } socklen_t length() const { return family() == AF_INET6 ? sizeof addr6_ : sizeof addr_; } bool operator==(const InetAddress& rhs) const; // Resolves hostname to IP address. // Returns true on success. // Thread safe. static bool resolve(StringArg hostname, uint16_t port, InetAddress*); static std::vector<InetAddress> resolveAll(StringArg hostname, uint16_t port = 0); private: union { struct sockaddr_in addr_; struct sockaddr_in6 addr6_; }; }; <file_sep>/utility/codesize.py #!/usr/bin/env python3 import collections, os, sys SOURCE_EXTS = set([".cc", ".c", ".h", ".S"]) class CodeSize: def __init__(self): self.self_bytes = 0 self.self_lines = 0 self.self_files = 0 self.all_bytes = 0 self.all_lines = 0 self.all_files = 0 def __repr__(self): if self.is_file(): return "%d" % self.self_lines if self.self_lines == self.all_lines: return "%d %d" % (self.all_files, self.all_lines) return "%d %d %d" % (self.all_files, self.all_lines, self.self_lines) def is_file(self): return self.all_files == 0 def is_dir(self): return self.all_files > 0 sizes = collections.defaultdict(CodeSize) def accumulate(fullname, content): parent = '' lines = content.count('\n') sizes[parent].all_lines += lines sizes[parent].all_files += 1 # a/b/c -> a/b, c for part in os.path.split(fullname): parent = os.path.join(parent, part) sizes[parent].self_bytes += len(content) sizes[parent].self_lines += lines sizes[parent].self_files += 1 # a/b/c -> a, b, c parent = '' for part in fullname.split(os.path.sep)[:-1]: parent = os.path.join(parent, part) sizes[parent].all_bytes += len(content) sizes[parent].all_lines += lines sizes[parent].all_files += 1 def walk(path): for root, dirs, files in os.walk(path): # skip hidden directories dirs[:] = [x for x in dirs if not x.startswith('.')] for filename in files: if os.path.splitext(filename)[1] in SOURCE_EXTS: fullname = os.path.join(root, filename) with open(fullname) as f: try: content = f.read() accumulate(fullname, content) except: print("ERROR:", fullname) class Directory: def __init__(self, name, size: CodeSize): self.name = name self.size = size self.dirs = [] self.files = [] def __repr__(self): return "%s/ %s" % (self.name, self.size) def AddDir(self, d): self.dirs.append(d) def AddFile(self, name, size: CodeSize): self.files.append((os.path.basename(name), size.self_lines)) def Print(self, indent): print("%*s%s/ %d" % (indent*2, "", self.name, self.size.all_lines)) for f in self.files: print("%*s%s %d" % (indent*2 + 2, "", f[0], f[1])) for d in sorted(self.dirs, key=lambda d: d.size.all_lines, reverse=True): d.Print(indent + 1) def PrintHTML(self, out, indent): out.write("%*s<li>%s/ [%s]<ul>\n" % (indent*2, "", self.name, '{:,}'.format(self.size.all_lines))) for d in sorted(self.dirs, key=lambda d: d.size.all_lines, reverse=True): d.PrintHTML(out, indent + 1) for f in self.files: out.write("""%*s<li data-jstree='{"type":"file"}'>%s [%s]</li>\n""" % (indent*2 + 2, "", f[0], '{:,}'.format(f[1]))) out.write("%*s</ul></li>\n" % (indent*2, "")) def main(argv): if len(argv) > 1: for path in argv[1:]: walk(path) else: walk(".") ''' for k in sorted(sizes): if sizes[k].is_dir() > 0: print(k, sizes[k]) print('==========') ''' dirs = {} #root = Directory('', CodeSize()) #dirs[''] = root for k in sorted(sizes): v = sizes[k] if v.is_dir(): dirs[k] = Directory(os.path.basename(k), v) if not k: continue parent = os.path.split(k)[0] if v.is_dir(): dirs[parent].AddDir(dirs[k]) else: dirs[parent].AddFile(k, v) # dirs[''].Print(0) with open('call_tree.html', 'w') as out: out.write('''<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>jsTree test</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" /> </head> <body> <input type="text" value="" id="demo_q" style="width: 450px;" placeholder="Search" /> <div id="jstree"> <ul> ''') dirs[''].PrintHTML(out, 0) out.write(''' </ul> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script> <script> $(function () { var to = false; $('#demo_q').keyup(function () { if(to) { clearTimeout(to); } to = setTimeout(function () { var v = $('#demo_q').val(); $('#jstree').jstree(true).search(v); }, 250); }); $('#jstree').jstree({ "types": { "default": { "icon": "jstree-folder" }, "file": { "icon": "jstree-file" } }, "plugins" : ["checkbox", "search", "types"] }); }); </script> </body> </html>'''); if __name__ == '__main__': main(sys.argv) <file_sep>/ssl/loop-libressl.cc #include "timer.h" #include "thread/Thread.h" #include <boost/bind.hpp> #include <assert.h> #include <fcntl.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <tls.h> struct tls* client(int sockfd) { struct tls_config* cfg = tls_config_new(); assert(cfg != NULL); tls_config_set_ca_file(cfg, "ca.pem"); // tls_config_insecure_noverifycert(cfg); // tls_config_insecure_noverifyname(cfg); struct tls* ctx = tls_client(); assert(ctx != NULL); int ret = tls_configure(ctx, cfg); assert(ret == 0); ret = tls_connect_socket(ctx, sockfd, "Test Server Cert"); assert(ret == 0); return ctx; } struct tls* server(int sockfd) { struct tls_config* cfg = tls_config_new(); assert(cfg != NULL); int ret = tls_config_set_cert_file(cfg, "server.pem"); assert(ret == 0); ret = tls_config_set_key_file(cfg, "server.pem"); assert(ret == 0); ret = tls_config_set_ecdhecurve(cfg, "prime256v1"); assert(ret == 0); // tls_config_verify_client_optional(cfg); struct tls* ctx = tls_server(); assert(ctx != NULL); ret = tls_configure(ctx, cfg); assert(ret == 0); struct tls* sctx = NULL; ret = tls_accept_socket(ctx, &sctx, sockfd); assert(ret == 0 && sctx != NULL); return sctx; } // only works for non-blocking sockets bool handshake(struct tls* cctx, struct tls* sctx) { int client_done = false, server_done = false; while (!(client_done && server_done)) { if (!client_done) { int ret = tls_handshake(cctx); // printf("c %d\n", ret); if (ret == 0) client_done = true; else if (ret == -1) { printf("client handshake failed: %s\n", tls_error(cctx)); break; } } if (!server_done) { int ret = tls_handshake(sctx); // printf("s %d\n", ret); if (ret == 0) server_done = true; else if (ret == -1) { printf("server handshake failed: %s\n", tls_error(sctx)); break; } } } return client_done && server_done; } void setBlockingIO(int fd) { int flags = fcntl(fd, F_GETFL, 0); if (flags > 0) { printf("set blocking IO for %d\n", fd); fcntl(fd, F_SETFL, flags & ~O_NONBLOCK); } } const int N = 500; struct Trial { int blocks, block_size; }; void client_thread(struct tls* ctx) { Timer t; t.start(); for (int i = 0; i < N; ++i) { int ret = tls_handshake(ctx); if (ret != 0) printf("client err = %d\n", ret); } t.stop(); printf("client %f secs, %f handshakes/sec\n", t.seconds(), N / t.seconds()); while (true) { Trial trial = { 0, 0 }; int nr = tls_read(ctx, &trial, sizeof trial); if (nr == 0) break; assert(nr == sizeof trial); // printf("client read bs %d nb %d\n", trial.block_size, trial.blocks); if (trial.block_size == 0) break; char* buf = new char[trial.block_size]; for (int i = 0; i < trial.blocks; ++i) { nr = tls_read(ctx, buf, trial.block_size); assert(nr == trial.block_size); } int64_t ack = static_cast<int64_t>(trial.blocks) * trial.block_size; int nw = tls_write(ctx, &ack, sizeof ack); assert(nw == sizeof ack); delete[] buf; } printf("client done\n"); tls_close(ctx); tls_free(ctx); } void send(int block_size, struct tls* ctx) { double start = now(); int total = 0; int blocks = 1024; char* message = new char[block_size]; bzero(message, block_size); Timer t; while (now() - start < 10) { Trial trial = { blocks, block_size }; int nw = tls_write(ctx, &trial, sizeof trial); assert(nw == sizeof trial); t.start(); for (int i = 0; i < blocks; ++i) { nw = tls_write(ctx, message, block_size); if (nw != block_size) printf("bs %d nw %d\n", block_size, nw); assert(nw == block_size); } t.stop(); int64_t ack = 0; int nr = tls_read(ctx, &ack, sizeof ack); assert(nr == sizeof ack); assert(ack == static_cast<int64_t>(blocks) * block_size); total += blocks; blocks *= 2; } double secs = now() - start; printf("bs %5d sec %.3f tot %d thr %.1fKB/s wr cpu %.3f\n", block_size, secs, total, block_size / secs * total / 1024, t.seconds()); delete[] message; } int main(int argc, char* argv[]) { int ret = tls_init(); assert(ret == 0); int fds[2]; socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0, fds); struct tls* cctx = client(fds[0]); struct tls* sctx = server(fds[1]); if (handshake(cctx, sctx)) printf("cipher %s\n", tls_conn_cipher(cctx)); else return -1; setBlockingIO(fds[0]); setBlockingIO(fds[1]); muduo::Thread thr(boost::bind(client_thread, cctx), "clientThread"); thr.start(); { Timer t; t.start(); for (int i = 0; i < N; ++i) { int ret = tls_handshake(sctx); if (ret != 0) printf("server err = %d\n", ret); } t.stop(); printf("server %f secs, %f handshakes/sec\n", t.seconds(), N / t.seconds()); } for (int i = 1024 * 16; i >= 1; i /= 4) { send(i, sctx); } tls_close(sctx); shutdown(fds[1], SHUT_RDWR); tls_free(sctx); thr.join(); } <file_sep>/puzzle/poker/poker_test.py #!/usr/bin/python import unittest import poker, poker2 class TestPoker(unittest.TestCase): def setUp(self): self.sf6 = "2H 3H 4H 5H 6H".split() # straight flush self.sf5 = "2H 3H 4H 5H AH".split() self.sfA = "TH JH QH KH AH".split() self.fk9 = "9D 9H 9S 9C 7D".split() # four of a kind self.fhT = "TD TC TH 7C 7D".split() # full house self.fh7 = "TD TC 7H 7C 7D".split() # full house self.fl = "2H 3H 4H 5H 7H".split() # flush self.st = "2H 3H 4H 5H 6D".split() # straight self.tk = "9D 9H 9S 8C 7D".split() # three of a kind self.tp = "5S 5D 9H 9C 6S".split() # two pairs self.op = "5S 5D 9H 8C 6S".split() # one pair self.hc = "5S 4D 9H 8C 6S".split() # high card def test_get_ranks(self): self.assertEqual([6, 5, 4, 3, 2], poker.get_ranks(self.sf6)) self.assertEqual([5, 4, 3, 2, 1], poker.get_ranks(self.sf5)) self.assertEqual([14, 13, 12, 11, 10], poker.get_ranks(self.sfA)) def test_flush(self): self.assertTrue(poker.flush(self.sf6)) self.assertFalse(poker.flush(self.fk9)) def test_straigh(self): self.assertTrue(poker.flush(self.sf6)) self.assertTrue(poker.flush(self.sf5)) self.assertTrue(poker.flush(self.sfA)) self.assertFalse(poker.flush(self.fk9)) def test_kind(self): self.assertEqual(9, poker.kind(4, poker.get_ranks(self.fk9))) self.assertEqual(10, poker.kind(3, poker.get_ranks(self.fhT))) self.assertEqual(7, poker.kind(2, poker.get_ranks(self.fhT))) self.assertEqual(9, poker.kind(2, poker.get_ranks(self.tp))) self.assertEqual(5, poker.kind(2, list(reversed(poker.get_ranks(self.tp))))) def test_score2(self): print poker2.score2(self.sf6) print poker2.score2(self.fk9) print poker2.score2(self.fhT) print poker2.score2(self.fh7) print poker2.score2(self.fl) print poker2.score2(self.st) print poker2.score2(self.tk) print poker2.score2(self.tp) print poker2.score2(self.op) print poker2.score2(self.hc) if __name__ == '__main__': unittest.main() <file_sep>/faketcp/faketcp.h #include <algorithm> // std::swap #include <boost/static_assert.hpp> #include <assert.h> #include <stdint.h> #include <string.h> #include <arpa/inet.h> // inet_ntop #include <net/if.h> struct SocketAddr { uint32_t saddr, daddr; uint16_t sport, dport; bool operator==(const SocketAddr& rhs) const { return saddr == rhs.saddr && daddr == rhs.daddr && sport == rhs.sport && dport == rhs.dport; } bool operator<(const SocketAddr& rhs) const { BOOST_STATIC_ASSERT(sizeof(SocketAddr) == 12); return memcmp(this, &rhs, sizeof(rhs)) < 0; } }; int tun_alloc(char dev[IFNAMSIZ], bool offload = false); uint16_t in_checksum(const void* buf, int len); void icmp_input(int fd, const void* input, const void* payload, int len); <file_sep>/topk/word_freq.cc // sort word by frequency, in-memory version. #include <algorithm> #include <iostream> #include <unordered_map> #include <vector> typedef std::unordered_map<std::string, int> WordCount; int main() { WordCount counts; std::string word; while (std::cin >> word) { counts[word]++; } std::vector<std::pair<int, WordCount::const_iterator>> freq; freq.reserve(counts.size()); for (auto it = counts.cbegin(); it != counts.cend(); ++it) { freq.push_back(make_pair(it->second, it)); } std::sort(freq.begin(), freq.end(), [](const std::pair<int, WordCount::const_iterator>& lhs, // const auto& lhs in C++14 const std::pair<int, WordCount::const_iterator>& rhs) { return lhs.first > rhs.first; }); // printf("%zd\n", sizeof(freq[0])); for (auto item : freq) { std::cout << item.first << '\t' << item.second->first << '\n'; } } <file_sep>/basic/int128.h #pragma once #include <stdint.h> // __int128 is a built-in type on amd64, though. struct uint128 { uint64_t low, high; uint128(int32_t l) : low(l), high(l < 0 ? -1 : 0) { } uint128(uint64_t l = 0) : low(l), high(0) { } uint128(uint64_t h, uint64_t l) : low(l), high(h) { } uint128& add(uint128 rhs) { #if __x86_64__ asm ("addq\t%2, %0\n\t" "adcq\t%3, %1" : "+r"(low), "+r"(high) : "r"(rhs.low), "r"(rhs.high) ); #else // http://stackoverflow.com/questions/6659414/efficient-128-bit-addition-using-carry-flag low += rhs.low; high += rhs.high + (low < rhs.low); // GCC needs to fix http://gcc.gnu.org/bugzilla/show_bug.cgi?id=51839 #endif return *this; } uint128& multiply(uint64_t rhs) { uint64_t h = high * rhs; *this = multiply128(low, rhs); high += h; return *this; } uint128& multiply(uint128 rhs) // __attribute__ ((noinline)) { uint64_t h = low * rhs.high + high * rhs.low; *this = multiply128(low, rhs.low); high += h; return *this; } static uint128 multiply128(uint64_t x, uint64_t y) // __attribute__ ((noinline)) { #if __x86_64__ uint128 prod(x); // MULX is only available in Haswell and later, use old MUL // RAX = prod.low # in-out // MULQ y # RDX:RAX = RAX * y // prod.high = RDX # out asm ("mulq\t%2\n\t" : "+a"(prod.low), "=d"(prod.high) : "r"(y) ); #else uint32_t a = x & 0xFFFFFFFF; uint32_t c = x >> 32; uint32_t b = y & 0xFFFFFFFF; uint32_t d = y >> 32; uint64_t ab = (uint64_t)a * b; uint64_t bc = (uint64_t)b * c; uint64_t ad = (uint64_t)a * d; uint64_t cd = (uint64_t)c * d; uint64_t low = ab + (bc << 32); uint64_t high = cd + (bc >> 32) + (ad >> 32) + (low < ab); low += (ad << 32); high += (low < (ad << 32)); uint128 prod(high, low); #endif return prod; } } __attribute__ ((aligned (16))); <file_sep>/python/echo-iterative.py #!/usr/bin/python import socket def handle(client_socket, client_address): while True: data = client_socket.recv(4096) if data: sent = client_socket.send(data) # sendall? else: print "disconnect", client_address client_socket.close() break if __name__ == "__main__": listen_address = ("0.0.0.0", 2007) server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(listen_address) server_socket.listen(5) while True: (client_socket, client_address) = server_socket.accept() print "got connection from", client_address handle(client_socket, client_address) <file_sep>/puzzle/nqueens_dl.cc #include <assert.h> #include <stdlib.h> #include <string.h> #include <iostream> // Dancing links algorithm by <NAME> // www-cs-faculty.stanford.edu/~uno/papers/dancing-color.ps.gz struct Node; typedef Node Column; struct Node { Node* left; Node* right; Node* up; Node* down; Column* col; int name; int size; }; const int kMaxQueens = 20; const int kMaxColumns = kMaxQueens * 6; const int kMaxNodes = 1 + kMaxColumns + kMaxQueens * kMaxQueens * 4; class QueenSolver { public: QueenSolver(int N) : root_(new_column()) { assert(N <= kMaxQueens); root_->left = root_->right = root_; memset(columns_, 0, sizeof(columns_)); // TODO: try organ pipe ordering for (int i = 0; i < N; ++i) { append_column(i); append_column(N+i); } for (int j = 0; j < 2*N; ++j) { int n = 2*N+j; assert(columns_[n] == NULL); Column* c = new_column(n); columns_[n] = c; n = 4*N+j; assert(columns_[n] == NULL); c = new_column(n); columns_[n] = c; } for (int col = 0; col < N; ++col) { for (int row = 0; row < N; ++row) { Node* n0 = new_row(col); Node* n1 = new_row(N+row); Node* n2 = new_row(2*N+row+col); Node* n3 = new_row(5*N+row-col); put_left(n0, n1); put_left(n0, n2); put_left(n0, n3); } } } void solve() { if (root_->left == root_) { ++count_; return; } Column* const col = get_min_column(); cover(col); for (Node* row = col->down; row != col; row = row->down) { for (Node* j = row->right; j != row; j = j->right) { cover(j->col); } solve(); for (Node* j = row->left; j != row; j = j->left) { uncover(j->col); } } uncover(col); } int64_t count() const { return count_; } private: int64_t count_ = 0; int cur_node_ = 0; Column* root_; Column* columns_[kMaxColumns]; Node nodes_[kMaxNodes]; Column* new_column(int n = 0) { assert(cur_node_ < kMaxNodes); Column* c = &nodes_[cur_node_++]; memset(c, 0, sizeof(Column)); c->left = c; c->right = c; c->up = c; c->down = c; c->col = c; c->name = n; return c; } void append_column(int n) { assert(columns_[n] == NULL); Column* c = new_column(n); put_left(root_, c); columns_[n] = c; } Node* new_row(int col) { assert(columns_[col] != NULL); assert(cur_node_ < kMaxNodes); Node* r = &nodes_[cur_node_++]; memset(r, 0, sizeof(Node)); r->left = r; r->right = r; r->up = r; r->down = r; r->name = col; r->col = columns_[col]; put_up(r->col, r); return r; } Column* get_min_column() { Column* c = root_->right; int min_size = c->size; if (min_size > 1) { for (Column* cc = c->right; cc != root_; cc = cc->right) { if (min_size > cc->size) { c = cc; min_size = cc->size; if (min_size <= 1) break; } } } return c; } void cover(Column* c) { c->right->left = c->left; c->left->right = c->right; for (Node* row = c->down; row != c; row = row->down) { for (Node* j = row->right; j != row; j = j->right) { j->down->up = j->up; j->up->down = j->down; j->col->size--; } } } void uncover(Column* c) { for (Node* row = c->up; row != c; row = row->up) { for (Node* j = row->left; j != row; j = j->left) { j->col->size++; j->down->up = j; j->up->down = j; } } c->right->left = c; c->left->right = c; } void put_left(Column* old, Column* nnew) { nnew->left = old->left; nnew->right = old; old->left->right = nnew; old->left = nnew; } void put_up(Column* old, Node* nnew) { nnew->up = old->up; nnew->down = old; old->up->down = nnew; old->up = nnew; old->size++; nnew->col = old; } }; int main(int argc, char* argv[]) { int N = argc > 1 ? atoi(argv[1]) : 8; QueenSolver solver(N); solver.solve(); std::cout << solver.count() << '\n'; } <file_sep>/puzzle/buysell.cc #include <assert.h> #include <stdio.h> #include <vector> int buysell(const std::vector<int>& prices) { assert(!prices.empty()); size_t lowestBuy = 0; size_t lowestBuySoFar = 0; size_t highestSell = 0; int maxGain = 0; for (size_t day = 1; day < prices.size(); ++day) { int todayPrice = prices[day]; int gain = todayPrice - prices[lowestBuySoFar]; if (gain > maxGain) { lowestBuy = lowestBuySoFar; highestSell = day; maxGain = gain; } if (todayPrice < prices[lowestBuySoFar]) { lowestBuySoFar = day; } } printf("buy %zd day at %d, sell %zd day at %d\n", lowestBuy, prices[lowestBuy], highestSell, prices[highestSell]); assert(lowestBuy <= highestSell); return maxGain; } template<int N> std::vector<int> toVec(int (&arr)[N]) { return std::vector<int>(arr, arr+N); } int main() { int test1[] = { 1, 2 }; int test2[] = { 1, 2, 3 }; int test3[] = { 2, 1, 3 }; int test4[] = { 3, 2, 1 }; int test5[] = { 2, 3, 1 }; int test6[] = { 2, 3, 1, 3 }; int test7[] = { 4, 5, 2, 3, 2, 4 }; printf("max gain %d\n", buysell(toVec(test1))); printf("max gain %d\n", buysell(toVec(test2))); printf("max gain %d\n", buysell(toVec(test3))); printf("max gain %d\n", buysell(toVec(test4))); printf("max gain %d\n", buysell(toVec(test5))); printf("max gain %d\n", buysell(toVec(test6))); printf("max gain %d\n", buysell(toVec(test7))); } <file_sep>/protobuf/codec_test.cc #include "codec.h" #include "query.pb.h" #include <stdio.h> void print(const std::string& buf) { printf("encoded to %zd bytes\n", buf.size()); for (size_t i = 0; i < buf.size(); ++i) { printf("%2zd: 0x%02x %c\n", i, (unsigned char)buf[i], isgraph(buf[i]) ? buf[i] : ' '); } } void testQuery() { muduo::Query query; query.set_id(1); query.set_questioner("<NAME>"); query.add_question("Running?"); std::string transport = encode(query); print(transport); int32_t be32 = 0; std::copy(transport.begin(), transport.begin() + sizeof be32, reinterpret_cast<char*>(&be32)); int32_t len = ::ntohl(be32); assert(len == transport.size() - sizeof(be32)); // network library decodes length header and get the body of message std::string buf = transport.substr(sizeof(int32_t)); assert(len == buf.size()); muduo::Query* newQuery = dynamic_cast<muduo::Query*>(decode(buf)); assert(newQuery != NULL); newQuery->PrintDebugString(); assert(newQuery->DebugString() == query.DebugString()); delete newQuery; buf[buf.size() - 6]++; // oops, some data is corrupted muduo::Query* badQuery = dynamic_cast<muduo::Query*>(decode(buf)); assert(badQuery == NULL); } void testEmpty() { muduo::Empty empty; std::string transport = encode(empty); print(transport); std::string buf = transport.substr(sizeof(int32_t)); muduo::Empty* newEmpty = dynamic_cast<muduo::Empty*>(decode(buf)); assert(newEmpty != NULL); newEmpty->PrintDebugString(); assert(newEmpty->DebugString() == empty.DebugString()); delete newEmpty; } void testAnswer() { muduo::Answer answer; answer.set_id(1); answer.set_questioner("<NAME>"); answer.set_answerer("blog.csdn.net/Solstice"); answer.add_solution("Jump!"); answer.add_solution("Win!"); std::string transport = encode(answer); print(transport); int32_t be32 = 0; std::copy(transport.begin(), transport.begin() + sizeof be32, reinterpret_cast<char*>(&be32)); int32_t len = ::ntohl(be32); assert(len == transport.size() - sizeof(be32)); // network library decodes length header and get the body of message std::string buf = transport.substr(sizeof(int32_t)); assert(len == buf.size()); muduo::Answer* newAnswer = dynamic_cast<muduo::Answer*>(decode(buf)); assert(newAnswer != NULL); newAnswer->PrintDebugString(); assert(newAnswer->DebugString() == answer.DebugString()); delete newAnswer; buf[buf.size() - 6]++; // oops, some data is corrupted muduo::Answer* badAnswer = dynamic_cast<muduo::Answer*>(decode(buf)); assert(badAnswer == NULL); } int main() { GOOGLE_PROTOBUF_VERIFY_VERSION; testQuery(); puts(""); testAnswer(); puts(""); testEmpty(); puts(""); puts("All pass!!!"); google::protobuf::ShutdownProtobufLibrary(); } <file_sep>/algorithm/partition.cc #include <algorithm> #include <iostream> #include <iterator> bool isOdd(int x) { return x % 2 != 0; // x % 2 == 1 is WRONG } void moveOddsBeforeEvens() { int oddeven[] = { 1, 2, 3, 4, 5, 6 }; std::partition(oddeven, oddeven+6, &isOdd); std::copy(oddeven, oddeven+6, std::ostream_iterator<int>(std::cout, ", ")); std::cout << std::endl; } int main() { moveOddsBeforeEvens(); int oddeven[] = { 1, 2, 3, 4, 5, 6 }; std::stable_partition(oddeven, oddeven+6, &isOdd); std::copy(oddeven, oddeven+6, std::ostream_iterator<int>(std::cout, ", ")); std::cout << std::endl; } <file_sep>/esort/sort11.cc // version 11: sort 100M integers // sort by chunks, then merge // overlap output and merge with threads. #include <boost/noncopyable.hpp> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <datetime/Timestamp.h> #include <thread/ThreadPool.h> #include <thread/BlockingQueue.h> #include <algorithm> #include <vector> #include <assert.h> #include <stdio.h> #include <sys/resource.h> using muduo::Timestamp; struct Source { const std::vector<int64_t>* data; int first, last; bool read(int64_t* value) { if (first < last) { *value = (*data)[first]; ++first; return true; } else { return false; } } }; struct Record { int64_t value; Source* source; Record(Source& src) : source(&src) { next(); } bool next() { return source->read(&value); } bool operator<(const Record& rhs) const { return value > rhs.value; } }; class OutputFile : boost::noncopyable { public: OutputFile(const char* filename) : file_(fopen(filename, "wb")) { assert(file_); setbuffer(file_, buffer_, sizeof buffer_); } ~OutputFile() { fflush(file_); fdatasync(fileno(file_)); fclose(file_); } void writeRecord(int64_t x) { fwrite_unlocked(&x, 1, sizeof x, file_); } void sync() { fdatasync(fileno(file_)); } private: FILE* file_; char buffer_[4*1024*1024]; }; typedef std::vector<int64_t> Batch; typedef boost::shared_ptr<Batch> BatchPtr; void output(muduo::BlockingQueue<BatchPtr>* queueOut, muduo::BlockingQueue<BatchPtr>* queueIn) { OutputFile out("output"); while (BatchPtr batch = queueOut->take()) { Timestamp start = Timestamp::now(); printf("%s write %zd records\n", start.toString().c_str(), batch->size()); for (Batch::iterator it = batch->begin(); it != batch->end(); ++it) { out.writeRecord(*it); } out.sync(); queueIn->put(batch); } printf("flushing\n"); } void merge(const std::vector<int64_t>& data, const int kChunkSize) { const int nChunks = (data.size() + kChunkSize - 1) / kChunkSize; printf("merge %d chunks\n", nChunks); std::vector<Source> sources; sources.reserve(nChunks); std::vector<Record> keys; keys.reserve(nChunks); size_t first = 0; for (first = 0; first + kChunkSize <= data.size(); first += kChunkSize) { Source src = { &data, first, first + kChunkSize }; sources.push_back(src); Record rec(sources.back()); keys.push_back(rec); } if (first < data.size()) { assert(data.size() - first < kChunkSize); Source src = { &data, first, data.size()}; sources.push_back(src); Record rec(sources.back()); keys.push_back(rec); } assert(sources.size() == nChunks); muduo::BlockingQueue<BatchPtr> queueOut, queueIn; muduo::ThreadPool threadPool; threadPool.start(1); threadPool.run(boost::bind(output, &queueOut, &queueIn)); const int batchSize = 1000 * 1000 * 10; { BatchPtr batch(new Batch); batch->reserve(batchSize); queueIn.put(batch); } { BatchPtr batch(new Batch); batch->reserve(batchSize); queueIn.put(batch); } { BatchPtr batch(new Batch); batch->reserve(batchSize); queueIn.put(batch); } BatchPtr batch(new Batch); batch->reserve(batchSize); std::make_heap(keys.begin(), keys.end()); int64_t current = keys.front().value; while (!keys.empty()) { std::pop_heap(keys.begin(), keys.end()); assert(current <= keys.back().value); if (current > keys.back().value) { abort(); } batch->push_back(keys.back().value); if (batch->size() >= batchSize) { queueOut.put(batch); batch = queueIn.take(); batch->clear(); } if (keys.back().next()) { std::push_heap(keys.begin(), keys.end()); } else { keys.pop_back(); } } queueOut.put(batch); queueOut.put(BatchPtr()); printf("flushing\n"); } int main(int argc, char* argv[]) { { // set max virtual memory to 3GB. size_t kOneGB = 1024*1024*1024; rlimit rl = { 3.0*kOneGB, 3.0*kOneGB }; setrlimit(RLIMIT_AS, &rl); } std::vector<int64_t> data; Timestamp start = Timestamp::now(); { data.resize(1000*1000*100); for (std::vector<int64_t>::iterator it = data.begin(); it != data.end(); ++it) { *it = lrand48(); } } Timestamp readDone = Timestamp::now(); printf("%zd\nread %f\n", data.size(), timeDifference(readDone, start)); int kChunkSize = atoi(argv[1]); printf("sort %zd records with chunk size %d\n", data.size(), kChunkSize); int i = 0; for (i = 0; i + kChunkSize <= data.size(); i += kChunkSize) { std::sort(data.begin() + i, data.begin() + i + kChunkSize); } printf("%d\n%zd\n", i, data.size()); std::sort(data.begin() + i, data.end()); Timestamp sortDone = Timestamp::now(); printf("sort %f\n", timeDifference(sortDone, readDone)); merge(data, kChunkSize); Timestamp mergeDone = Timestamp::now(); printf("merge %f\n", timeDifference(mergeDone, sortDone)); printf("sort & merge %f\n", timeDifference(mergeDone, readDone)); // getchar(); } <file_sep>/protobuf/dispatcher_lite.cc #include "query.pb.h" #include <boost/function.hpp> #include <iostream> using namespace std; class ProtobufDispatcherLite { public: typedef boost::function<void (google::protobuf::Message* message)> ProtobufMessageCallback; explicit ProtobufDispatcherLite(const ProtobufMessageCallback& defaultCb) : defaultCallback_(defaultCb) { } void onMessage(google::protobuf::Message* message) const { CallbackMap::const_iterator it = callbacks_.find(message->GetDescriptor()); if (it != callbacks_.end()) { it->second(message); } else { defaultCallback_(message); } } void registerMessageCallback(const google::protobuf::Descriptor* desc, const ProtobufMessageCallback& callback) { callbacks_[desc] = callback; } private: typedef std::map<const google::protobuf::Descriptor*, ProtobufMessageCallback> CallbackMap; CallbackMap callbacks_; ProtobufMessageCallback defaultCallback_; }; void onQuery(google::protobuf::Message* message) { cout << "onQuery: " << message->GetTypeName() << endl; muduo::Query* query = dynamic_cast<muduo::Query*>(message); assert(query != NULL); } void onAnswer(google::protobuf::Message* message) { cout << "onAnswer: " << message->GetTypeName() << endl; muduo::Answer* answer = dynamic_cast<muduo::Answer*>(message); assert(answer != NULL); } void onUnknownMessageType(google::protobuf::Message* message) { cout << "Discarding " << message->GetTypeName() << endl; } int main() { GOOGLE_PROTOBUF_VERIFY_VERSION; ProtobufDispatcherLite dispatcher(onUnknownMessageType); dispatcher.registerMessageCallback(muduo::Query::descriptor(), onQuery); dispatcher.registerMessageCallback(muduo::Answer::descriptor(), onAnswer); muduo::Query q; muduo::Answer a; muduo::Empty e; dispatcher.onMessage(&q); dispatcher.onMessage(&a); dispatcher.onMessage(&e); google::protobuf::ShutdownProtobufLibrary(); } <file_sep>/ssl/hook.py #!/usr/bin/python import re, sys # 0x4460e2 malloc (17408) returns 0xd96fe0 M = re.compile('.* malloc \((\\d+)\) returns (.*)') F = re.compile('freed (.*)') S = re.compile('========+ (.*)') alloc = {} section = '' def dump(): sections = {} for addr in alloc: sec = alloc[addr][1] if sec in sections: sections[sec] += alloc[addr][0] else: sections[sec] = alloc[addr][0] print section for key in sorted(sections): print " ", key, sections[key] hook = 'hook' if len(sys.argv) > 1: hook = sys.argv[1] with open(hook) as f: for line in f: m = M.search(line) if m: # print 'alloc', m.group(1) alloc[m.group(2)] = (int(m.group(1)), section) continue m = F.match(line) if m: if m.group(1) in alloc: del alloc[m.group(1)] else: # print 'free', m.group(1) pass continue m = S.match(line) if m: dump() section = m.group(1) print alloc # after handshaking 0 # {'SSL_handshake client': 7518, 'BIO_new_bio_pair 0': 35136, 'SSL_new client': 2128, 'SSL_handshake server': 146, 'SSL_new server': 3092, 'SSL_connect': 33680, 'SSL_accept': 36755} # client 7518 + 2128 + 33680 = 43326 # server 146 + 3092 + 36755 = 39993 # after handshaking 1 # {'SSL_connect 0': 35432, 'SSL_accept 0': 40400, 'SSL_new server 0': 112, 'SSL_new server 1': 2964, 'BIO_new_bio_pair 1': 35152, 'SSL_connect 1': 405, 'SSL_accept 1': 760, 'SSL_new client 1': 2360, 'SSL_handshake server 1': 1792, 'SSL_handshake client 1': 8924, 'SSL_handshake client 0': 112} # client 2360 + 405 + 8924 = 11689 # server 2964 + 760 + 1792 = 5516 <file_sep>/tpc/bin/sender.cc #include "Acceptor.h" #include "InetAddress.h" #include "TcpStream.h" #include <thread> #include <unistd.h> void sender(const char* filename, TcpStreamPtr stream) { FILE* fp = fopen(filename, "rb"); if (!fp) return; printf("Sleeping 10 seconds.\n"); sleep(10); printf("Start sending file %s\n", filename); char buf[8192]; size_t nr = 0; while ( (nr = fread(buf, 1, sizeof buf, fp)) > 0) { stream->sendAll(buf, nr); } fclose(fp); printf("Finish sending file %s\n", filename); // Safe close connection printf("Shutdown write and read until EOF\n"); stream->shutdownWrite(); while ( (nr = stream->receiveSome(buf, sizeof buf)) > 0) { // do nothing } printf("All done.\n"); // TcpStream destructs here, close the TCP socket. } int main(int argc, char* argv[]) { if (argc < 3) { printf("Usage:\n %s filename port\n", argv[0]); return 0; } int port = atoi(argv[2]); Acceptor acceptor((InetAddress(port))); printf("Accepting... Ctrl-C to exit\n"); int count = 0; while (true) { TcpStreamPtr tcpStream = acceptor.accept(); printf("accepted no. %d client\n", ++count); std::thread thr(sender, argv[1], std::move(tcpStream)); thr.detach(); } } <file_sep>/reactor/Makefile SUBDIRS = s00 s01 s02 s03 s04 s05 s06 s07 s08 s09 s10 all: $(SUBDIRS) clean: for d in $(SUBDIRS); do cd $$d && make clean && cd ..; done $(SUBDIRS): cd $@ && make .PHONY: all clean $(SUBDIRS) <file_sep>/topk/benchmark.cc #include "file.h" #include "input.h" #include "timer.h" #include "absl/container/flat_hash_set.h" int main(int argc, char* argv[]) { setlocale(LC_NUMERIC, ""); bool combine = false; bool sequential = false; int buffer_size = kBufferSize; int opt; while ((opt = getopt(argc, argv, "b:cs")) != -1) { switch (opt) { case 'b': buffer_size = atoi(optarg); break; case 'c': combine = true; break; case 's': sequential = true; break; } } LOG_INFO << "Reading " << argc - optind << (combine ? " segment " : "") << " files " << (sequential ? "sequentially" : "randomly") << ", buffer size " << buffer_size; Timer timer; int64_t total = 0; int64_t lines = 0; int64_t count = 0; if (combine) { std::vector<std::unique_ptr<SegmentInput>> inputs; inputs.reserve(argc - optind); for (int i = optind; i < argc; ++i) { inputs.emplace_back(new SegmentInput(argv[i], buffer_size)); } if (sequential) { for (const auto& input : inputs) { Timer t; //std::string line; while (input->next()) { count += input->current_count(); ++lines; } int64_t len = input->tell(); LOG_INFO << "Done " << input->filename() << " " << t.report(len); total += len; } } else { } } else { std::vector<std::unique_ptr<InputFile>> files; files.reserve(argc - optind); for (int i = optind; i < argc; ++i) { files.emplace_back(new InputFile(argv[i], buffer_size)); } if (sequential) { for (const auto& file : files) { Timer t; std::string line; while (file->getline(&line)) { ++lines; } int64_t len = file->tell(); LOG_DEBUG << "Done " << file->filename() << " " << t.report(len); total += len; } } else { std::string line; absl::flat_hash_set<InputFile*> toRemove; while (!files.empty()) { toRemove.clear(); // read one line from each file for (const auto& file : files) { if (file->getline(&line)) { ++lines; } else { toRemove.insert(file.get()); } } if (!toRemove.empty()) { for (auto* f : toRemove) { total += f->tell(); LOG_DEBUG << "Done " << f->filename(); } // std::partition? auto it = std::remove_if(files.begin(), files.end(), [&toRemove] (const auto& f) { return toRemove.count(f.get()) > 0; }); assert(files.end() - it == toRemove.size()); files.erase(it, files.end()); } } } } LOG_INFO << "All done " << timer.report(total) << " " << muduo::Fmt("%'ld", lines) << " lines " << muduo::Fmt("%'ld", count) << " count"; } <file_sep>/ssl/build.sh #!/bin/bash set -x LIBRESSL=$HOME/code/libressl-2.5.1/install CXXFLAGS="-Wall -Wextra -Wno-unused-parameter -I $LIBRESSL/include/ -I $HOME/muduo -O2 -g" LDFLAGS="-L $LIBRESSL/lib/ -l tls -l ssl -l crypto -lrt" LIB="TlsAcceptor.cc TlsConfig.cc TlsStream.cc ../tpc/lib/InetAddress.cc ../tpc/lib/Socket.cc ../logging/Logging.cc ../logging/LogStream.cc ../datetime/Timestamp.cc ../thread/Thread.cc" g++ $CXXFLAGS -iquote ../tpc/include -I../ -std=c++11 -pthread $LIB server.cc -o server $LDFLAGS g++ $CXXFLAGS -iquote ../tpc/include -I../ -std=c++11 -pthread $LIB client.cc -o client $LDFLAGS g++ $CXXFLAGS benchmark-libressl.cc -o benchmark-libressl $LDFLAGS -pthread g++ -Wall -O2 -g benchmark-openssl.cc -o benchmark-openssl -lssl -lcrypto -lrt g++ -Wall -Wno-deprecated-declarations -O2 -g footprint-openssl.cc -o footprint-openssl -lssl -lcrypto -lrt g++ -Wall -Wno-deprecated-declarations -O2 -g footprint-openssl2.cc -o footprint-openssl2 -lssl -lcrypto -lrt g++ $CXXFLAGS loop-libressl.cc -o loop-libressl -iquote ../ -pthread $LDFLAGS ../thread/Thread.cc <file_sep>/topk/word_freq_sort.cc /* sort word by frequency, sorting while counting version. 1. read input files, do counting, when count map > 10M keys, output to segment files word \t count -- sorted by word 2. read all segment files, do merging & counting, when count map > 10M keys, output to count files, each word goes to one count file only. count \t word -- sorted by count 3. read all count files, do merging and output */ #include <algorithm> #include <fstream> #include <iostream> #include <map> #include <memory> #include <unordered_map> #include <vector> #ifdef STD_STRING #warning "STD STRING" #include <string> using std::string; #else #include <ext/vstring.h> typedef __gnu_cxx::__sso_string string; #endif #include <sys/time.h> #include <unistd.h> const size_t kMaxSize = 10 * 1000 * 1000; inline double now() { struct timeval tv = { 0, 0 }; gettimeofday(&tv, nullptr); return tv.tv_sec + tv.tv_usec / 1000000.0; } int input(int argc, char* argv[]) { int count = 0; double t = now(); for (int i = 1; i < argc; ++i) { std::cout << " processing input file " << argv[i] << std::endl; std::map<string, int64_t> counts; std::ifstream in(argv[i]); while (in && !in.eof()) { double tt = now(); counts.clear(); string word; while (in >> word) { counts[word]++; if (counts.size() > kMaxSize) { std::cout << " split " << now() - tt << " sec" << std::endl; break; } } tt = now(); char buf[256]; snprintf(buf, sizeof buf, "segment-%05d", count); std::ofstream out(buf); ++count; for (const auto& kv : counts) { out << kv.first << '\t' << kv.second << '\n'; } std::cout << " writing " << buf << " " << now() - tt << " sec" << std::endl; } } std::cout << "reading done " << count << " segments " << now() - t << " sec" << std::endl; return count; } // ======= combine ======= class Segment // copyable { public: string word; int64_t count = 0; explicit Segment(std::istream* in) : in_(in) { } bool next() { string line; if (getline(*in_, line)) { size_t tab = line.find('\t'); if (tab != string::npos) { word = line.substr(0, tab); count = strtol(line.c_str() + tab, NULL, 10); return true; } } return false; } bool operator<(const Segment& rhs) const { return word > rhs.word; } private: std::istream* in_; }; void output(int i, const std::unordered_map<string, int64_t>& counts) { double t = now(); std::vector<std::pair<int64_t, string>> freq; for (const auto& entry : counts) { freq.push_back(make_pair(entry.second, entry.first)); } std::sort(freq.begin(), freq.end()); std::cout << " sorting " << now() - t << " sec" << std::endl; t = now(); char buf[256]; snprintf(buf, sizeof buf, "count-%05d", i); std::ofstream out(buf); for (auto it = freq.rbegin(); it != freq.rend(); ++it) { out << it->first << '\t' << it->second << '\n'; } std::cout << " writing " << buf << " " << now() - t << " sec" << std::endl; } int combine(int count) { std::vector<std::unique_ptr<std::ifstream>> inputs; std::vector<Segment> keys; double t = now(); for (int i = 0; i < count; ++i) { char buf[256]; snprintf(buf, sizeof buf, "segment-%05d", i); inputs.emplace_back(new std::ifstream(buf)); Segment rec(inputs.back().get()); if (rec.next()) { keys.push_back(rec); } ::unlink(buf); } // std::cout << keys.size() << '\n'; int m = 0; string last; std::unordered_map<string, int64_t> counts; std::make_heap(keys.begin(), keys.end()); double tt = now(); while (!keys.empty()) { std::pop_heap(keys.begin(), keys.end()); if (keys.back().word != last) { last = keys.back().word; if (counts.size() > kMaxSize) { std::cout << " split " << now() - tt << " sec" << std::endl; output(m++, counts); tt = now(); counts.clear(); } } counts[keys.back().word] += keys.back().count; if (keys.back().next()) { std::push_heap(keys.begin(), keys.end()); } else { keys.pop_back(); } } if (!counts.empty()) { std::cout << " split " << now() - tt << " sec" << std::endl; output(m++, counts); } std::cout << "combining done " << m << " count files " << now() - t << " sec" << std::endl; return m; } // ======= merge ======= class Source // copyable { public: explicit Source(std::istream* in) : in_(in) { } bool next() { string line; if (getline(*in_, line)) { size_t tab = line.find('\t'); if (tab != string::npos) { count_ = strtol(line.c_str(), NULL, 10); if (count_ > 0) { word_ = line.substr(tab+1); return true; } } } return false; } bool operator<(const Source& rhs) const { return count_ < rhs.count_; } void outputTo(std::ostream& out) const { out << count_ << '\t' << word_ << '\n'; } private: std::istream* in_; int64_t count_ = 0; string word_; }; void merge(int m) { std::vector<std::unique_ptr<std::ifstream>> inputs; std::vector<Source> keys; double t = now(); for (int i = 0; i < m; ++i) { char buf[256]; snprintf(buf, sizeof buf, "count-%05d", i); inputs.emplace_back(new std::ifstream(buf)); Source rec(inputs.back().get()); if (rec.next()) { keys.push_back(rec); } ::unlink(buf); } std::ofstream out("output"); std::make_heap(keys.begin(), keys.end()); while (!keys.empty()) { std::pop_heap(keys.begin(), keys.end()); keys.back().outputTo(out); if (keys.back().next()) { std::push_heap(keys.begin(), keys.end()); } else { keys.pop_back(); } } std::cout << "merging done " << now() - t << " sec\n"; } int main(int argc, char* argv[]) { int count = input(argc, argv); int m = combine(count); merge(m); } <file_sep>/esort/sort01.cc // version 01: only be able to sort 1GB file // sort with keys // 30% faster than sort(1) for 1GB file. #include <boost/noncopyable.hpp> #include <datetime/Timestamp.h> #include <algorithm> #include <string> #include <ext/vstring.h> #include <vector> #include <assert.h> #include <stdio.h> #include <string.h> #include <sys/resource.h> // typedef std::string string; typedef __gnu_cxx::__sso_string string; using muduo::Timestamp; class InputFile : boost::noncopyable { public: InputFile(const char* filename) : file_(fopen(filename, "rb")) { assert(file_); setbuffer(file_, buffer_, sizeof buffer_); } ~InputFile() { fclose(file_); } bool readLine(string* line) { char buf[256]; if (fgets_unlocked(buf, sizeof buf, file_)) { line->assign(buf); return true; } else { return false; } } int read(char* buf, int size) { return fread_unlocked(buf, 1, size, file_); } private: FILE* file_; char buffer_[64*1024]; }; class OutputFile : boost::noncopyable { public: OutputFile(const char* filename) : file_(fopen(filename, "wb")) { assert(file_); setbuffer(file_, buffer_, sizeof buffer_); } ~OutputFile() { fclose(file_); } void writeLine(const string& line) { if (line.empty()) { fwrite_unlocked("\n", 1, 1, file_); } else if (line[line.size() - 1] == '\n') { fwrite_unlocked(line.c_str(), 1, line.size(), file_); } else { fwrite_unlocked(line.c_str(), 1, line.size(), file_); fwrite_unlocked("\n", 1, 1, file_); } } private: FILE* file_; char buffer_[64*1024]; }; const int kRecordSize = 100; const int kKeySize = 10; const bool kUseReadLine = false; void readInput(const char* filename, std::vector<string>* data) { InputFile in(filename); string line; int64_t totalSize = 0; data->reserve(10000000); if (kUseReadLine) { while (in.readLine(&line)) { totalSize += line.size(); data->push_back(line); } } else { char buf[kRecordSize]; while (int n = in.read(buf, sizeof buf)) { totalSize += n; line.assign(buf, n); data->push_back(line); } } } struct Key { char key[kKeySize]; int index; Key(const string& record, int idx) : index(idx) { memcpy(key, record.data(), sizeof key); } bool operator<(const Key& rhs) const { return memcmp(key, rhs.key, sizeof key) < 0; } }; void sort(const std::vector<string>& data, std::vector<Key>* keys) { Timestamp start = Timestamp::now(); keys->reserve(data.size()); for (size_t i = 0; i < data.size(); ++i) { keys->push_back(Key(data[i], i)); } printf("make keys %f\n", timeDifference(Timestamp::now(), start)); std::sort(keys->begin(), keys->end()); } int main(int argc, char* argv[]) { bool kSortDummyData = false; { // set max virtual memory to 3GB. size_t kOneGB = 1024*1024*1024; rlimit rl = { 3.0*kOneGB, 3.0*kOneGB }; setrlimit(RLIMIT_AS, &rl); } std::vector<int> dummyData; if (kSortDummyData) { dummyData.resize(10000000); for (std::vector<int>::iterator it = dummyData.begin(); it != dummyData.end(); ++it) { *it = rand(); } } Timestamp start = Timestamp::now(); std::vector<string> data; // read readInput(argv[1], &data); Timestamp readDone = Timestamp::now(); printf("%zd\nread %f\n", data.size(), timeDifference(readDone, start)); // sort std::vector<Key> keys; sort(data, &keys); Timestamp sortDone = Timestamp::now(); printf("sort %f\n", timeDifference(sortDone, readDone)); // output // char dummyBuf[256]; { OutputFile out("output"); for (std::vector<Key>::iterator it = keys.begin(); it != keys.end(); ++it) { // memcpy(dummyBuf, data[it->index].data(), 100); out.writeLine(data[it->index]); } } Timestamp writeDone = Timestamp::now(); printf("write %f\n", timeDifference(writeDone, sortDone)); printf("total %f\n", timeDifference(writeDone, start)); } <file_sep>/protobuf/dispatcher.cc #include "query.pb.h" #include <boost/function.hpp> #include <boost/noncopyable.hpp> #include <boost/shared_ptr.hpp> #include <iostream> using namespace std; class Callback : boost::noncopyable { public: virtual ~Callback() {}; virtual void onMessage(google::protobuf::Message* message) const = 0; }; template <typename T> class CallbackT : public Callback { public: typedef boost::function<void (T* message)> ProtobufMessageCallback; CallbackT(const ProtobufMessageCallback& callback) : callback_(callback) { } virtual void onMessage(google::protobuf::Message* message) const { T* t = dynamic_cast<T*>(message); assert(t != NULL); callback_(t); } private: ProtobufMessageCallback callback_; }; void discardProtobufMessage(google::protobuf::Message* message) { cout << "Discarding " << message->GetTypeName() << endl; } class ProtobufDispatcher { public: ProtobufDispatcher() : defaultCallback_(discardProtobufMessage) { } void onMessage(google::protobuf::Message* message) const { CallbackMap::const_iterator it = callbacks_.find(message->GetDescriptor()); if (it != callbacks_.end()) { it->second->onMessage(message); } else { defaultCallback_(message); } } template<typename T> void registerMessageCallback(const typename CallbackT<T>::ProtobufMessageCallback& callback) { boost::shared_ptr<CallbackT<T> > pd(new CallbackT<T>(callback)); callbacks_[T::descriptor()] = pd; } typedef std::map<const google::protobuf::Descriptor*, boost::shared_ptr<Callback> > CallbackMap; CallbackMap callbacks_; boost::function<void (google::protobuf::Message* message)> defaultCallback_; }; // // test // void onQuery(muduo::Query* query) { cout << "onQuery: " << query->GetTypeName() << endl; } void onAnswer(muduo::Answer* answer) { cout << "onAnswer: " << answer->GetTypeName() << endl; } int main() { ProtobufDispatcher dispatcher; dispatcher.registerMessageCallback<muduo::Query>(onQuery); dispatcher.registerMessageCallback<muduo::Answer>(onAnswer); muduo::Query q; muduo::Answer a; muduo::Empty e; dispatcher.onMessage(&q); dispatcher.onMessage(&a); dispatcher.onMessage(&e); google::protobuf::ShutdownProtobufLibrary(); } <file_sep>/tpc/bin/ttcp.cc #include "Acceptor.h" #include "InetAddress.h" #include "TcpStream.h" #include <iostream> #include <boost/program_options.hpp> #include <sys/time.h> struct Options { uint16_t port; int length; int number; bool transmit, receive, nodelay; std::string host; Options() : port(0), length(0), number(0), transmit(false), receive(false), nodelay(false) { } }; struct SessionMessage { int32_t number; int32_t length; } __attribute__ ((__packed__)); struct PayloadMessage { int32_t length; char data[0]; }; double now() { struct timeval tv = { 0, 0 }; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec / 1000000.0; } // FIXME: rewrite with getopt(3). bool parseCommandLine(int argc, char* argv[], Options* opt) { namespace po = boost::program_options; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "Help") ("port,p", po::value<uint16_t>(&opt->port)->default_value(5001), "TCP port") ("length,l", po::value<int>(&opt->length)->default_value(65536), "Buffer length") ("number,n", po::value<int>(&opt->number)->default_value(8192), "Number of buffers") ("trans,t", po::value<std::string>(&opt->host), "Transmit") ("recv,r", "Receive") ("nodelay,D", "set TCP_NODELAY") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); opt->transmit = vm.count("trans"); opt->receive = vm.count("recv"); opt->nodelay = vm.count("nodelay"); if (vm.count("help")) { std::cout << desc << std::endl; return false; } if (opt->transmit == opt->receive) { printf("either -t or -r must be specified.\n"); return false; } printf("port = %d\n", opt->port); if (opt->transmit) { printf("buffer length = %d\n", opt->length); printf("number of buffers = %d\n", opt->number); } else { printf("accepting...\n"); } return true; } void transmit(const Options& opt) { InetAddress addr; if (!InetAddress::resolve(opt.host.c_str(), opt.port, &addr)) { printf("Unable to resolve %s\n", opt.host.c_str()); return; } printf("connecting to %s\n", addr.toIpPort().c_str()); TcpStreamPtr stream(TcpStream::connect(addr)); if (!stream) { printf("Unable to connect %s\n", addr.toIpPort().c_str()); perror(""); return; } if (opt.nodelay) { stream->setTcpNoDelay(true); } printf("connected\n"); double start = now(); struct SessionMessage sessionMessage = { 0, 0 }; sessionMessage.number = htonl(opt.number); sessionMessage.length = htonl(opt.length); if (stream->sendAll(&sessionMessage, sizeof(sessionMessage)) != sizeof(sessionMessage)) { perror("write SessionMessage"); return; } const int total_len = sizeof(int32_t) + opt.length; PayloadMessage* payload = static_cast<PayloadMessage*>(::malloc(total_len)); std::unique_ptr<PayloadMessage, void (*)(void*)> freeIt(payload, ::free); assert(payload); payload->length = htonl(opt.length); for (int i = 0; i < opt.length; ++i) { payload->data[i] = "0123456789ABCDEF"[i % 16]; } double total_mb = 1.0 * opt.length * opt.number / 1024 / 1024; printf("%.3f MiB in total\n", total_mb); for (int i = 0; i < opt.number; ++i) { int nw = stream->sendAll(payload, total_len); assert(nw == total_len); int ack = 0; int nr = stream->receiveAll(&ack, sizeof(ack)); assert(nr == sizeof(ack)); ack = ntohl(ack); assert(ack == opt.length); } double elapsed = now() - start; printf("%.3f seconds\n%.3f MiB/s\n", elapsed, total_mb / elapsed); } void receive(const Options& opt) { Acceptor acceptor(InetAddress(opt.port)); TcpStreamPtr stream(acceptor.accept()); if (!stream) { return; } struct SessionMessage sessionMessage = { 0, 0 }; if (stream->receiveAll(&sessionMessage, sizeof(sessionMessage)) != sizeof(sessionMessage)) { perror("read SessionMessage"); return; } sessionMessage.number = ntohl(sessionMessage.number); sessionMessage.length = ntohl(sessionMessage.length); printf("receive buffer length = %d\nreceive number of buffers = %d\n", sessionMessage.length, sessionMessage.number); double total_mb = 1.0 * sessionMessage.number * sessionMessage.length / 1024 / 1024; printf("%.3f MiB in total\n", total_mb); const int total_len = sizeof(int32_t) + sessionMessage.length; PayloadMessage* payload = static_cast<PayloadMessage*>(::malloc(total_len)); std::unique_ptr<PayloadMessage, void (*)(void*)> freeIt(payload, ::free); assert(payload); double start = now(); for (int i = 0; i < sessionMessage.number; ++i) { payload->length = 0; if (stream->receiveAll(&payload->length, sizeof(payload->length)) != sizeof(payload->length)) { perror("read length"); return; } payload->length = ntohl(payload->length); assert(payload->length == sessionMessage.length); if (stream->receiveAll(payload->data, payload->length) != payload->length) { perror("read payload data"); return; } int32_t ack = htonl(payload->length); if (stream->sendAll(&ack, sizeof(ack)) != sizeof(ack)) { perror("write ack"); return; } } double elapsed = now() - start; printf("%.3f seconds\n%.3f MiB/s\n", elapsed, total_mb / elapsed); } int main(int argc, char* argv[]) { Options options; if (parseCommandLine(argc, argv, &options)) { if (options.transmit) { transmit(options); } else if (options.receive) { receive(options); } else { assert(0); } } } <file_sep>/ssl/footprint-openssl2.cc #include <openssl/aes.h> #include <openssl/conf.h> #include <openssl/err.h> #include <openssl/ssl.h> #include <malloc.h> #include <mcheck.h> #include <stdio.h> #include <sys/socket.h> #include "timer.h" #include <string> #include <vector> using std::string; string readStatus() { string result; FILE* fp = fopen("/proc/self/status", "r"); char buf[8192]; int nr = fread(buf, 1, sizeof buf, fp); result.append(buf, nr); return result; } int main(int argc, char* argv[]) { SSL_load_error_strings(); ERR_load_BIO_strings(); SSL_library_init(); OPENSSL_config(NULL); SSL_CTX* ctx = SSL_CTX_new(TLSv1_2_server_method()); SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION); EC_KEY* ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE); SSL_CTX_set_tmp_ecdh(ctx, ecdh); EC_KEY_free(ecdh); const char* CertFile = "server.pem"; // argv[1]; const char* KeyFile = "server.pem"; // argv[2]; SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM); SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM); if (!SSL_CTX_check_private_key(ctx)) abort(); SSL_CTX* ctx_client = SSL_CTX_new(TLSv1_2_client_method()); string st0 = readStatus(); double start = now(); const int N = 1000; struct mallinfo mi0 = mallinfo(); std::vector<SSL*> ssls; for (int i = 0; i < N; ++i) { int fds[2]; if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0, fds) != 0) abort(); SSL* ssl = SSL_new (ctx); SSL* ssl_client = SSL_new (ctx_client); SSL_set_fd(ssl, fds[0]); SSL_set_fd(ssl_client, fds[1]); int ret = SSL_connect(ssl_client); int ret2 = SSL_accept(ssl); while (true) { ret = SSL_do_handshake(ssl_client); ret2 = SSL_do_handshake(ssl); if (ret == 1 && ret2 == 1) break; } if (i == 0) printf ("SSL connection using %s %s\n", SSL_get_version(ssl_client), SSL_get_cipher (ssl_client)); ssls.push_back(ssl); ssls.push_back(ssl_client); } double elapsed = now() - start; printf("%.2fs %.1f handshakes/s\n", elapsed, N / elapsed); struct mallinfo mi1 = mallinfo(); string st1 = readStatus(); printf("%s\n", st0.c_str()); printf("%s\n", st1.c_str()); for (int i = 0; i < ssls.size(); ++i) SSL_free(ssls[i]); // string st2 = readStatus(); struct mallinfo mi2 = mallinfo(); SSL_CTX_free (ctx); SSL_CTX_free (ctx_client); // string st3 = readStatus(); struct mallinfo mi3 = mallinfo(); // printf("after SSL_free\n%s\n", st2.c_str()); // printf("after SSL_CTX_free\n%s\n", st3.c_str()); // OPENSSL_cleanup(); // only in 1.1.0 printf("\n"); } <file_sep>/topk/timer.h #pragma once #include <sys/time.h> #include "absl/strings/str_format.h" #include "muduo/base/ProcessInfo.h" #include "muduo/base/Timestamp.h" class Timer { public: Timer() : start_(now()), start_cpu_(muduo::ProcessInfo::cpuTime()) { } std::string report(int64_t bytes) const { muduo::ProcessInfo::CpuTime end_cpu(muduo::ProcessInfo::cpuTime()); double seconds = now() - start_; char buf[64]; snprintf(buf, sizeof buf, "%'zd", bytes); return absl::StrFormat("%.2fs real %.2fs cpu %6.2f MiB/s %s bytes", seconds, end_cpu.total() - start_cpu_.total(), bytes / seconds / 1024 / 1024, buf); } static double now() { struct timeval tv = { 0, 0 }; gettimeofday(&tv, nullptr); return tv.tv_sec + tv.tv_usec / 1000000.0; } private: const double start_; const muduo::ProcessInfo::CpuTime start_cpu_; }; <file_sep>/topk/sha1all.cc #include <assert.h> #include <fcntl.h> #include <stdio.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/time.h> #include <unistd.h> #include <openssl/sha.h> inline double now() { struct timeval tv = { 0, 0 }; gettimeofday(&tv, nullptr); return tv.tv_sec + tv.tv_usec / 1000000.0; } int main(int argc, char* argv[]) { int64_t total = 0; double start = now(); SHA_CTX ctx_; SHA1_Init(&ctx_); for (int i = 1; i < argc; ++i) { int fd = open(argv[i], O_RDONLY); struct stat st; fstat(fd, &st); size_t len = st.st_size; total += len; if (len < 1024*1024*1024) { void* mapped = mmap(NULL, len, PROT_READ, MAP_PRIVATE, fd, 0); assert(mapped != MAP_FAILED); SHA1_Update(&ctx_, mapped, len); munmap(mapped, len); } else { char buf[128*1024]; ssize_t nr; while ( (nr = read(fd, buf, sizeof buf)) > 0) { SHA1_Update(&ctx_, buf, nr); } } ::close(fd); } unsigned char result[SHA_DIGEST_LENGTH]; SHA1_Final(result, &ctx_); for (int i = 0; i < SHA_DIGEST_LENGTH; ++i) { printf("%02x", result[i]); } printf("\n"); double sec = now() - start; printf("%ld bytes %.3f sec %.2f MiB/s\n", total, sec, total / sec / 1024 / 1024); } <file_sep>/logging/AsyncLoggingQueue.h #ifndef MUDUO_BASE_ASYNCLOGGINGQUEUE_H #define MUDUO_BASE_ASYNCLOGGINGQUEUE_H #include "LogFile.h" #include "thread/BlockingQueue.h" #include "thread/BoundedBlockingQueue.h" #include "thread/CountDownLatch.h" #include "thread/Thread.h" #include <string> #include <boost/bind.hpp> #include <boost/noncopyable.hpp> #include <boost/scoped_ptr.hpp> namespace muduo { // proof of conecpt async logging. // use Intel TBB concurrent_queue if performance is desired. template<typename MSG, template <typename> class QUEUE> class AsyncLoggingT : boost::noncopyable { public: AsyncLoggingT(const string& basename, // FIXME: StringPiece size_t rollSize) : running_(false), basename_(basename), rollSize_(rollSize), thread_(boost::bind(&AsyncLoggingT::threadFunc, this), "Logging"), latch_(1) { } AsyncLoggingT(const string& basename, // FIXME: StringPiece size_t rollSize, int queueSize) : running_(false), basename_(basename), rollSize_(rollSize), thread_(boost::bind(&AsyncLoggingT::threadFunc, this), "Logging"), latch_(1), queue_(queueSize) { } ~AsyncLoggingT() { if (running_) { stop(); } } void append(const char* logline, int len) { queue_.put(MSG(logline, len)); } void start() { running_ = true; thread_.start(); latch_.wait(); } void stop() { running_ = false; queue_.put(MSG()); thread_.join(); } private: void threadFunc() { assert(running_ == true); latch_.countDown(); LogFile output(basename_, rollSize_, false); time_t lastFlush = time(NULL); while (true) { MSG msg(queue_.take()); if (msg.empty()) { assert(running_ == false); break; } output.append(msg.data(), msg.length()); } output.flush(); } bool running_; string basename_; size_t rollSize_; muduo::Thread thread_; muduo::CountDownLatch latch_; QUEUE<MSG> queue_; }; // FIXME: use detach-able log buffers and move semantics typedef AsyncLoggingT<string, muduo::BlockingQueue> AsyncLoggingUnboundedQueue; typedef AsyncLoggingT<string, muduo::BoundedBlockingQueue> AsyncLoggingBoundedQueue; // demonstrate premature optimization is BAD struct LogMessage { LogMessage(const char* msg, int len) : length_(len) { assert(length_ <= sizeof data_); ::memcpy(data_, msg, length_); } LogMessage() : length_(0) { } LogMessage(const LogMessage& rhs) : length_(rhs.length_) { assert(length_ <= sizeof data_); ::memcpy(data_, rhs.data_, length_); } LogMessage& operator=(const LogMessage& rhs) { length_ = rhs.length_; assert(length_ <= sizeof data_); ::memcpy(data_, rhs.data_, length_); } const char* data() const { return data_; } int length() const { return length_; } bool empty() const { return length_ == 0; } char data_[4000]; size_t length_; }; typedef AsyncLoggingT<LogMessage, muduo::BlockingQueue> AsyncLoggingUnboundedQueueL; typedef AsyncLoggingT<LogMessage, muduo::BoundedBlockingQueue> AsyncLoggingBoundedQueueL; } #endif // MUDUO_BASE_ASYNCLOGGINGQUEUE_H <file_sep>/benchmark/bm_memory.cc #include <string.h> #include "benchmark/benchmark.h" /* // memory read bandwidth static void BM_memchr(benchmark::State& state) { int64_t len = state.range(0); void* buf = ::malloc(len); ::memset(buf, 0, len); benchmark::DoNotOptimize(buf); for (auto _ : state) ::memchr(buf, 1, len); state.SetBytesProcessed(len * state.iterations()); ::free(buf); } BENCHMARK(BM_memchr)->Range(8, 1 << 30); */ // memory write bandwidth static void BM_memset(benchmark::State& state) { int64_t len = state.range(0); void* buf = ::malloc(len); for (auto _ : state) { ::memset(buf, 0, len); benchmark::DoNotOptimize(buf); benchmark::ClobberMemory(); } state.SetBytesProcessed(len * state.iterations()); state.SetItemsProcessed(state.iterations()); ::free(buf); } BENCHMARK(BM_memset)->Range(8, 1 << 30); // memory write bandwidth static void BM_memcpy(benchmark::State& state) { int64_t len = state.range(0); void* src = ::malloc(len); ::memset(src, 0, len); void* dst = ::malloc(len); for (auto _ : state) { ::memcpy(dst, src, len); benchmark::DoNotOptimize(dst); benchmark::ClobberMemory(); } state.SetBytesProcessed(len * state.iterations()); state.SetItemsProcessed(state.iterations()); ::free(dst); ::free(src); } BENCHMARK(BM_memcpy)->Range(8, 1 << 30); <file_sep>/faketcp/icmpecho.cc #include "faketcp.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <netinet/ip.h> #include <linux/if_ether.h> int main() { char ifname[IFNAMSIZ] = "tun%d"; int fd = tun_alloc(ifname); if (fd < 0) { fprintf(stderr, "tunnel interface allocation failed\n"); exit(1); } printf("allocted tunnel interface %s\n", ifname); sleep(1); for (;;) { union { unsigned char buf[ETH_FRAME_LEN]; struct iphdr iphdr; }; const int iphdr_size = sizeof iphdr; int nread = read(fd, buf, sizeof(buf)); if (nread < 0) { perror("read"); close(fd); exit(1); } printf("read %d bytes from tunnel interface %s.\n", nread, ifname); const int iphdr_len = iphdr.ihl*4; if (nread >= iphdr_size && iphdr.version == 4 && iphdr_len >= iphdr_size && iphdr_len <= nread && iphdr.tot_len == htons(nread) && in_checksum(buf, iphdr_len) == 0) { const void* payload = buf + iphdr_len; if (iphdr.protocol == IPPROTO_ICMP) { icmp_input(fd, buf, payload, nread); } } else { printf("bad packet\n"); for (int i = 0; i < nread; ++i) { if (i % 4 == 0) printf("\n"); printf("%02x ", buf[i]); } printf("\n"); } } return 0; } <file_sep>/pingpong/libevent/single_thread.sh #!/bin/sh killall server timeout=${timeout:-100} bufsize=${bufsize:-16384} nothreads=1 for nosessions in 1 10 100 1000 10000; do sleep 5 echo "Bufsize: $bufsize Threads: $nothreads Sessions: $nosessions" taskset -c 1 ./server 2> /dev/null & srvpid=$! sleep 1 taskset -c 2 ./client 9876 $bufsize $nosessions $timeout kill -9 $srvpid done <file_sep>/ssl/TlsAcceptor.h #pragma once #include "Common.h" #include "Socket.h" #include "TlsContext.h" #include <memory> class InetAddress; class TlsStream; typedef std::unique_ptr<TlsStream> TlsStreamPtr; class TlsAcceptor : noncopyable { public: TlsAcceptor(TlsConfig* config, const InetAddress& listenAddr); ~TlsAcceptor() = default; TlsAcceptor(TlsAcceptor&&) = default; TlsAcceptor& operator=(TlsAcceptor&&) = default; // thread safe TlsStreamPtr accept(); private: TlsContext context_; Socket listenSock_; }; <file_sep>/thread/test/destruct.cc #include "../Mutex.h" #include <string> using std::string; muduo::MutexLock g_mutex; string g_str = "Hello"; int32_t g_int32 = 123; int64_t g_int64 = 4321; string getString() { muduo::MutexLockGuard lock(g_mutex); return g_str; } int32_t getInt32() { muduo::MutexLockGuard lock(g_mutex); return g_int32; } int64_t getInt64() { muduo::MutexLockGuard lock(g_mutex); return g_int64; } int main() { getString(); getInt32(); getInt64(); } <file_sep>/tpc/Makefile CXXFLAGS = -Wall -std=c++11 -pthread -O2 -g -iquote include/ -I../ -I/usr/local/include LDFLAGS = -L lib/ -L/usr/local/lib -ltpc LIB_HEADERS := $(wildcard include/*.h) ../datetime/Timestamp.h ../thread/Atomic.h LIB_SRCS := $(wildcard lib/*.cc) ../datetime/Timestamp.cc LIB_OBJS := $(LIB_SRCS:.cc=.o) LIB := lib/libtpc.a BIN_SRCS := $(wildcard bin/*.cc) BINS := $(BIN_SRCS:.cc=) all: $(BINS) lib: $(LIB) $(LIB_OBJS) : Makefile $(LIB_HEADERS) $(LIB): $(LIB_OBJS) ar rcs $@ $^ $(BINS): $(LIB) bin/ttcp: LDLIBS += -lboost_program_options clean: rm -f $(LIB_OBJS) $(LIB) $(BINS) <file_sep>/esort/build.sh #!/bin/sh set -x CXXFLAGS="-O2 -g -Wall" export CXXFLAGS g++ -I .. $CXXFLAGS -o sort00 sort00.cc ../datetime/Timestamp.cc g++ -I .. $CXXFLAGS -o sort01 sort01.cc ../datetime/Timestamp.cc g++ -I .. $CXXFLAGS -o sort02 sort02.cc ../datetime/Timestamp.cc g++ -I .. $CXXFLAGS -o sort03 sort03.cc ../datetime/Timestamp.cc ../thread/Thread.cc ../thread/ThreadPool.cc ../thread/Exception.cc -lpthread g++ -I .. $CXXFLAGS -o sort04 sort04.cc ../datetime/Timestamp.cc ../thread/Thread.cc ../thread/ThreadPool.cc ../thread/Exception.cc -lpthread g++ -I .. $CXXFLAGS -o sort10 sort10.cc ../datetime/Timestamp.cc g++ -I .. $CXXFLAGS -o sort11 sort11.cc ../datetime/Timestamp.cc ../thread/Thread.cc ../thread/ThreadPool.cc ../thread/Exception.cc -lpthread g++ -I .. $CXXFLAGS -o sort12 sort12.cc ../datetime/Timestamp.cc ../thread/Thread.cc ../thread/ThreadPool.cc ../thread/Exception.cc -lpthread <file_sep>/ssl/TlsStream.cc #include "TlsStream.h" TlsStreamPtr TlsStream::connect(TlsConfig* config, const char* hostport, const char* servername) { TlsStreamPtr stream; TlsContext context(TlsContext::kClient, config); if (context.connect(hostport, servername)) { LOG_ERROR << context.error(); return stream; } if (context.handshake()) { LOG_ERROR << context.error(); return stream; } stream.reset(new TlsStream(std::move(context))); return stream; } int TlsStream::receiveSome(void* buf, int len) { return context_.read(buf, len); } int TlsStream::sendSome(const void* buf, int len) { return context_.write(buf, len); } <file_sep>/puzzle/poker/poker.py #!/usr/bin/python import sys def get_ranks(hand): ranks = ['--23456789TJQKA'.index(r) for r, s in hand] ranks.sort(reverse = True) if ranks == [14, 5, 4, 3, 2]: ranks = [5, 4, 3, 2, 1] return ranks def straight(ranks): return len(set(ranks)) == 5 and (max(ranks) - min(ranks) == 4) def flush(hand): suits = [s for r, s in hand] return len(set(suits)) == 1 def kind(n, ranks): for r in ranks: if ranks.count(r) == n: return r return None def two_pair(ranks): pair = kind(2, ranks) lowpair = kind(2, list(reversed(ranks))) if pair and lowpair != pair: return (pair, lowpair) else: return None def score(hand): assert len(hand) == 5 ranks = get_ranks(hand) if straight(ranks) and flush(hand): return (8, max(ranks)) elif kind(4, ranks): return (7, kind(4, ranks), kind(1, ranks)) elif kind(3, ranks) and kind(2, ranks): return (6, kind(3, ranks), kind(2, ranks)) elif flush(hand): return (5, ranks) elif straight(ranks): return (4, max(ranks)) elif kind(3, ranks): return (3, kind(3, ranks), ranks) elif two_pair(ranks): return (2, two_pair(ranks), ranks) elif kind(2, ranks): return (1, kind(2, ranks), ranks) else: return (0, ranks) if __name__ == '__main__': hand = sys.argv[1:] print score(hand) <file_sep>/java/billing/DefaultRule.java package billing; public class DefaultRule extends Rule { private final String name; public DefaultRule(String name) { this.name = name; } @Override public long getMoneyInPips(UserMonthUsage input) { throw new RuntimeException("Rule " + name + " not implemented"); } } <file_sep>/protobuf/codec.h // excerpts from http://code.google.com/p/muduo/ // // Use of this source code is governed by a BSD-style license // that can be found in the License file. // // Author: <NAME> (giantchen at gmail dot com) #ifndef PROTOBUF_CODEC_H #define PROTOBUF_CODEC_H #include <google/protobuf/descriptor.h> #include <google/protobuf/message.h> #include <zlib.h> // adler32 #include <string> #include <arpa/inet.h> // htonl, ntohl #include <stdint.h> // struct ProtobufTransportFormat __attribute__ ((__packed__)) // { // int32_t len; // int32_t nameLen; // char typeName[nameLen]; // char protobufData[len-nameLen-8]; // int32_t checkSum; // adler32 of nameLen, typeName and protobufData // } const int kHeaderLen = sizeof(int32_t); /// /// Encode protobuf Message to transport format defined above /// returns a std::string. /// /// returns a empty string if message.AppendToString() fails. /// inline std::string encode(const google::protobuf::Message& message) { std::string result; result.resize(kHeaderLen); const std::string& typeName = message.GetTypeName(); int32_t nameLen = static_cast<int32_t>(typeName.size()+1); int32_t be32 = ::htonl(nameLen); result.append(reinterpret_cast<char*>(&be32), sizeof be32); result.append(typeName.c_str(), nameLen); bool succeed = message.AppendToString(&result); if (succeed) { const char* begin = result.c_str() + kHeaderLen; int32_t checkSum = adler32(1, reinterpret_cast<const Bytef*>(begin), result.size()-kHeaderLen); int32_t be32 = ::htonl(checkSum); result.append(reinterpret_cast<char*>(&be32), sizeof be32); int32_t len = ::htonl(result.size() - kHeaderLen); std::copy(reinterpret_cast<char*>(&len), reinterpret_cast<char*>(&len) + sizeof len, result.begin()); } else { result.clear(); } return result; } inline google::protobuf::Message* createMessage(const std::string& type_name) { google::protobuf::Message* message = NULL; const google::protobuf::Descriptor* descriptor = google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(type_name); if (descriptor) { const google::protobuf::Message* prototype = google::protobuf::MessageFactory::generated_factory()->GetPrototype(descriptor); if (prototype) { message = prototype->New(); } } return message; } inline int32_t asInt32(const char* buf) { int32_t be32 = 0; ::memcpy(&be32, buf, sizeof(be32)); return ::ntohl(be32); } /// /// Decode protobuf Message from transport format defined above. /// returns a Message* /// /// returns NULL if fails. /// inline google::protobuf::Message* decode(const std::string& buf) { google::protobuf::Message* result = NULL; int32_t len = static_cast<int32_t>(buf.size()); if (len >= 10) { int32_t expectedCheckSum = asInt32(buf.c_str() + buf.size() - kHeaderLen); const char* begin = buf.c_str(); int32_t checkSum = adler32(1, reinterpret_cast<const Bytef*>(begin), len-kHeaderLen); if (checkSum == expectedCheckSum) { int32_t nameLen = asInt32(buf.c_str()); if (nameLen >= 2 && nameLen <= len - 2*kHeaderLen) { std::string typeName(buf.begin() + kHeaderLen, buf.begin() + kHeaderLen + nameLen - 1); google::protobuf::Message* message = createMessage(typeName); if (message) { const char* data = buf.c_str() + kHeaderLen + nameLen; int32_t dataLen = len - nameLen - 2*kHeaderLen; if (message->ParseFromArray(data, dataLen)) { result = message; } else { // parse error delete message; } } else { // unknown message type } } else { // invalid name len } } else { // check sum error } } return result; } #endif // PROTOBUF_CODEC_H <file_sep>/string/test.cc #include "StringEager.h" #define BOOST_TEST_MAIN #ifdef BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #else #include <boost/test/included/unit_test.hpp> #endif typedef muduo::StringEager String; BOOST_AUTO_TEST_CASE(testEmptyString) { String s1; BOOST_CHECK_EQUAL(s1.empty(), true); BOOST_CHECK_EQUAL(s1.size(), 0); BOOST_CHECK_EQUAL(s1.capacity(), 0); BOOST_CHECK_EQUAL(s1.begin(), s1.end()); BOOST_CHECK_EQUAL(strcmp(s1.c_str(), ""), 0); const String s2; BOOST_CHECK_EQUAL(s2.empty(), true); BOOST_CHECK_EQUAL(s2.size(), 0); BOOST_CHECK_EQUAL(s2.capacity(), 0); BOOST_CHECK_EQUAL(s2.begin(), s2.end()); BOOST_CHECK_EQUAL(strcmp(s2.c_str(), ""), 0); } BOOST_AUTO_TEST_CASE(testCopyAndAssignment) { String empty; String s1(empty); BOOST_CHECK_EQUAL(s1.empty(), true); BOOST_CHECK_EQUAL(s1.size(), 0); BOOST_CHECK_EQUAL(s1.capacity(), 0); BOOST_CHECK_EQUAL(s1.begin(), s1.end()); BOOST_CHECK_EQUAL(strcmp(s1.c_str(), ""), 0); String s2("chenshuo"); BOOST_CHECK_EQUAL(s2.empty(), false); BOOST_CHECK_EQUAL(s2.size(), 8); BOOST_CHECK_EQUAL(s2.capacity(), 15); BOOST_CHECK_EQUAL(s2.end() - s2.begin(), 8); BOOST_CHECK_EQUAL(strcmp(s2.c_str(), "chenshuo"), 0); String s3(s2); BOOST_CHECK(s2.data() != s3.data()); BOOST_CHECK_EQUAL(s3.empty(), false); BOOST_CHECK_EQUAL(s3.size(), 8); BOOST_CHECK_EQUAL(s3.capacity(), 15); BOOST_CHECK_EQUAL(s3.end() - s3.begin(), 8); BOOST_CHECK_EQUAL(strcmp(s3.c_str(), "chenshuo"), 0); String s4 = s2; BOOST_CHECK(s2.data() != s4.data()); BOOST_CHECK_EQUAL(s4.empty(), false); BOOST_CHECK_EQUAL(s4.size(), 8); BOOST_CHECK_EQUAL(s4.capacity(), 15); BOOST_CHECK_EQUAL(s4.end() - s4.begin(), 8); BOOST_CHECK_EQUAL(strcmp(s4.c_str(), "chenshuo"), 0); const char* olds3 = s3.data(); s3 = empty; BOOST_CHECK_EQUAL(s3.data(), olds3); BOOST_CHECK_EQUAL(s3.empty(), true); BOOST_CHECK_EQUAL(s3.size(), 0); BOOST_CHECK_EQUAL(s3.capacity(), 15); BOOST_CHECK_EQUAL(s3.end() - s3.begin(), 0); BOOST_CHECK_EQUAL(strcmp(s3.c_str(), ""), 0); s3 = s2; BOOST_CHECK(s2.data() != s3.data()); BOOST_CHECK_EQUAL(s3.data(), olds3); BOOST_CHECK_EQUAL(s3.empty(), false); BOOST_CHECK_EQUAL(s3.size(), 8); BOOST_CHECK_EQUAL(s3.capacity(), 15); BOOST_CHECK_EQUAL(s3.end() - s3.begin(), 8); BOOST_CHECK_EQUAL(strcmp(s3.c_str(), "chenshuo"), 0); s3 = s3; BOOST_CHECK_EQUAL(s3.data(), olds3); BOOST_CHECK_EQUAL(s3.empty(), false); BOOST_CHECK_EQUAL(s3.size(), 8); BOOST_CHECK_EQUAL(s3.capacity(), 15); BOOST_CHECK_EQUAL(s3.end() - s3.begin(), 8); BOOST_CHECK_EQUAL(strcmp(s3.c_str(), "chenshuo"), 0); s3 = "muduo"; BOOST_CHECK_EQUAL(s3.data(), olds3); BOOST_CHECK_EQUAL(s3.empty(), false); BOOST_CHECK_EQUAL(s3.size(), 5); BOOST_CHECK_EQUAL(s3.capacity(), 15); BOOST_CHECK_EQUAL(s3.end() - s3.begin(), 5); BOOST_CHECK_EQUAL(strcmp(s3.c_str(), "muduo"), 0); s3 = "chenshuo.com"; BOOST_CHECK_EQUAL(s3.data(), olds3); BOOST_CHECK_EQUAL(s3.empty(), false); BOOST_CHECK_EQUAL(s3.size(), 12); BOOST_CHECK_EQUAL(s3.capacity(), 15); BOOST_CHECK_EQUAL(s3.end() - s3.begin(), 12); BOOST_CHECK_EQUAL(strcmp(s3.c_str(), "chenshuo.com"), 0); s3 = "https://github.com/chenshuo/documents/downloads"; BOOST_CHECK(s3.data() != olds3); BOOST_CHECK_EQUAL(s3.empty(), false); BOOST_CHECK_EQUAL(s3.size(), 47); BOOST_CHECK_EQUAL(s3.capacity(), 47); BOOST_CHECK_EQUAL(s3.end() - s3.begin(), 47); BOOST_CHECK_EQUAL(strcmp(s3.c_str(), "https://github.com/chenshuo/documents/downloads"), 0); const char* olds4 = s4.data(); s4 = "muduo network library"; BOOST_CHECK(s4.data() != olds4); BOOST_CHECK_EQUAL(s4.empty(), false); BOOST_CHECK_EQUAL(s4.size(), 21); BOOST_CHECK_EQUAL(s4.capacity(), 30); BOOST_CHECK_EQUAL(s4.end() - s4.begin(), 21); BOOST_CHECK_EQUAL(strcmp(s4.c_str(), "muduo network library"), 0); s3 = s4; BOOST_CHECK_EQUAL(s3.empty(), false); BOOST_CHECK_EQUAL(s3.size(), 21); BOOST_CHECK_EQUAL(s3.capacity(), 47); BOOST_CHECK_EQUAL(s3.end() - s3.begin(), 21); BOOST_CHECK_EQUAL(strcmp(s3.c_str(), "muduo network library"), 0); s3 = "https://github.com/chenshuo/documents/downloads/"; s4 = s3; BOOST_CHECK_EQUAL(s4.empty(), false); BOOST_CHECK_EQUAL(s4.size(), 48); BOOST_CHECK_EQUAL(s4.capacity(), 60); BOOST_CHECK_EQUAL(s4.end() - s4.begin(), 48); BOOST_CHECK_EQUAL(strcmp(s4.c_str(), "https://github.com/chenshuo/documents/downloads/"), 0); #ifdef __GXX_EXPERIMENTAL_CXX0X__ String s5(std::move(s3)); BOOST_CHECK_EQUAL(s3.data(), (const char*)NULL); BOOST_CHECK_EQUAL(s5.empty(), false); BOOST_CHECK_EQUAL(s5.size(), 48); BOOST_CHECK_EQUAL(s5.capacity(), 94); BOOST_CHECK_EQUAL(s5.end() - s5.begin(), 48); s5 = std::move(s2); BOOST_CHECK_EQUAL(s5.empty(), false); BOOST_CHECK_EQUAL(s5.size(), 8); BOOST_CHECK_EQUAL(s5.capacity(), 15); BOOST_CHECK_EQUAL(s5.end() - s5.begin(), 8); BOOST_CHECK_EQUAL(strcmp(s5.c_str(), "chenshuo"), 0); #endif } BOOST_AUTO_TEST_CASE(testPushBack) { String s1; s1.push_back('a'); BOOST_CHECK_EQUAL(s1.empty(), false); BOOST_CHECK_EQUAL(s1.size(), 1); BOOST_CHECK_EQUAL(s1.capacity(), 15); BOOST_CHECK_EQUAL(s1.end() - s1.begin(), 1); BOOST_CHECK_EQUAL(strcmp(s1.c_str(), "a"), 0); s1.push_back('b'); BOOST_CHECK_EQUAL(s1.empty(), false); BOOST_CHECK_EQUAL(s1.size(), 2); BOOST_CHECK_EQUAL(s1.capacity(), 15); BOOST_CHECK_EQUAL(s1.end() - s1.begin(), 2); BOOST_CHECK_EQUAL(strcmp(s1.c_str(), "ab"), 0); String s2 = "hello"; s2.push_back('C'); BOOST_CHECK_EQUAL(s2.empty(), false); BOOST_CHECK_EQUAL(s2.size(), 6); BOOST_CHECK_EQUAL(s2.capacity(), 15); BOOST_CHECK_EQUAL(strcmp(s2.c_str(), "helloC"), 0); s2 = "OctoberDecember"; BOOST_CHECK_EQUAL(s2.size(), 15); BOOST_CHECK_EQUAL(s2.capacity(), 15); s2.push_back('X'); BOOST_CHECK_EQUAL(s2.size(), 16); BOOST_CHECK_EQUAL(s2.capacity(), 30); BOOST_CHECK_EQUAL(strcmp(s2.c_str(), "OctoberDecemberX"), 0); } BOOST_AUTO_TEST_CASE(testAppendAndAssign) { String s1; s1.append("hello"); BOOST_CHECK_EQUAL(s1.size(), 5); BOOST_CHECK_EQUAL(s1.capacity(), 15); BOOST_CHECK_EQUAL(strcmp(s1.c_str(), "hello"), 0); s1.append("world"); BOOST_CHECK_EQUAL(s1.size(), 10); BOOST_CHECK_EQUAL(s1.capacity(), 15); BOOST_CHECK_EQUAL(strcmp(s1.c_str(), "helloworld"), 0); s1.append("solstice"); BOOST_CHECK_EQUAL(s1.size(), 18); BOOST_CHECK_EQUAL(s1.capacity(), 30); BOOST_CHECK_EQUAL(strcmp(s1.c_str(), "helloworldsolstice"), 0); s1.append(s1.data(), 5); BOOST_CHECK_EQUAL(s1.size(), 23); BOOST_CHECK_EQUAL(s1.capacity(), 30); BOOST_CHECK_EQUAL(strcmp(s1.c_str(), "helloworldsolsticehello"), 0); s1.append(s1.data()+10, 8); BOOST_CHECK_EQUAL(s1.size(), 31); BOOST_CHECK_EQUAL(s1.capacity(), 60); BOOST_CHECK_EQUAL(strcmp(s1.c_str(), "helloworldsolsticehellosolstice"), 0); String s2; s2.assign(s1.c_str(), s1.size()); BOOST_CHECK_EQUAL(s2.size(), 31); BOOST_CHECK_EQUAL(s2.capacity(), 31); BOOST_CHECK_EQUAL(strcmp(s2.c_str(), "helloworldsolsticehellosolstice"), 0); s2.assign("muduo", 4); BOOST_CHECK_EQUAL(s2.size(), 4); BOOST_CHECK_EQUAL(s2.capacity(), 31); BOOST_CHECK_EQUAL(strcmp(s2.c_str(), "mudu"), 0); s2.assign(s2.data()+1, 2); BOOST_CHECK_EQUAL(s2.size(), 2); BOOST_CHECK_EQUAL(s2.capacity(), 31); BOOST_CHECK_EQUAL(strcmp(s2.c_str(), "ud"), 0); } <file_sep>/basic/counted_ptr.h #pragma once // A simple reference counted smart pointer. // make use of GCC atomic builtins and C++ move semantics template<typename T> class counted_ptr { typedef int* counted_ptr::*bool_type; public: counted_ptr(T* p = nullptr) : ptr_(p), count_(p ? new int(1) : nullptr) { } counted_ptr(const counted_ptr& rhs) noexcept : ptr_(rhs.ptr_), count_(rhs.count_) { if (count_) __atomic_fetch_add(count_, 1, __ATOMIC_SEQ_CST); } counted_ptr(counted_ptr&& rhs) noexcept : ptr_(rhs.ptr_), count_(rhs.count_) { rhs.ptr_ = nullptr; rhs.count_ = nullptr; } ~counted_ptr() { reset(); } counted_ptr& operator=(counted_ptr rhs) { swap(rhs); return *this; } T* get() const noexcept { return ptr_; } void reset() { static_assert(sizeof(T) > 0, "T must be complete type"); if (count_) { if (__atomic_sub_fetch(count_, 1, __ATOMIC_SEQ_CST) == 0) { delete ptr_; delete count_; } ptr_ = nullptr; count_ = nullptr; } } void swap(counted_ptr& rhs) noexcept { T* tp = ptr_; ptr_ = rhs.ptr_; rhs.ptr_ = tp; int* tc = count_; count_ = rhs.count_; rhs.count_ = tc; } T* operator->() const noexcept { // assert(ptr_); return ptr_; } T& operator*() const noexcept { // assert(ptr_); return *ptr_; } operator bool_type() const noexcept { return ptr_ ? &counted_ptr::count_ : nullptr; } int use_count() const noexcept { return count_ ? __atomic_load_n(count_, __ATOMIC_SEQ_CST) : 0; } private: T* ptr_; int* count_; }; <file_sep>/tpc/bin/nodelay_server.cc #include "Acceptor.h" #include "InetAddress.h" #include "TcpStream.h" #include <thread> #include <vector> #include <assert.h> #include <string.h> #include <sys/time.h> double now() { struct timeval tv = { 0, 0 }; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec / 1000000.0; } // an interative request-response server int main(int argc, char* argv[]) { InetAddress listenAddr(3210); Acceptor acceptor(listenAddr); printf("Accepting... Ctrl-C to exit\n"); int count = 0; bool nodelay = argc > 1 && strcmp(argv[1], "-D") == 0; while (true) { TcpStreamPtr tcpStream = acceptor.accept(); printf("accepted no. %d client\n", ++count); if (nodelay) tcpStream->setTcpNoDelay(true); while (true) { int len = 0; int nr = tcpStream->receiveAll(&len, sizeof len); if (nr <= 0) break; printf("%f received header %d bytes, len = %d\n", now(), nr, len); assert(nr == sizeof len); std::vector<char> payload(len); nr = tcpStream->receiveAll(payload.data(), len); printf("%f received payload %d bytes\n", now(), nr); assert(nr == len); int nw = tcpStream->sendAll(&len, sizeof len); assert(nw == sizeof len); } printf("no. %d client ended.\n", count); } } <file_sep>/java/bankqueue/customer/CustomerFactory.java package bankqueue.customer; import java.util.Random; public class CustomerFactory { private static final int kMinServiceTime = 30; // half a minute private static final int kMaxServiceTime = 5 * 60; // five minutes public static Customer newCustomer(int id, Random r) { CustomerType type = CustomerFactory.getCustomerType(r); int serviceTime = CustomerFactory.getServiceTime(r, type); switch (type) { case kNormal: return new NormalCustomer(id, serviceTime); case kFast: return new FastCustomer(id, serviceTime); case kVip: return new VipCustomer(id, serviceTime); } return null; } public static CustomerType getCustomerType(Random r) { int rand = r.nextInt(10); if (rand % 10 == 0) return CustomerType.kVip; else if (rand < 4) return CustomerType.kFast; else return CustomerType.kNormal; } private static int getServiceTime(Random r, CustomerType type) { int serviceTime; if (type == CustomerType.kFast) { serviceTime = kMinServiceTime; } else { serviceTime = kMinServiceTime + r.nextInt(kMaxServiceTime - kMinServiceTime + 1); } return serviceTime; } } <file_sep>/puzzle/typoglycemia.cc // answer to http://blog.zhaojie.me/2012/11/how-to-generate-typoglycemia-text.html #include <algorithm> #include <iostream> #include <string> #include <assert.h> #include <ctype.h> using std::string; void randomizeWord(char* str, int len) { const char first = *str; const char last = str[len-1]; assert(isalpha(first)); assert(isalpha(last)); std::random_shuffle(str+1, str+len-1); assert(first == *str); assert(last == str[len-1]); } void randomize(string& text) { string::iterator start = text.begin(); while (start < text.end()) { start = std::find_if(start, text.end(), isalpha); if (start != text.end()) { string::iterator end = std::find_if(start, text.end(), std::not1(std::ptr_fun(isalpha))); if (end - start > 3) { randomizeWord(&*start, end - start); } start = end; } } } int main() { string text; while (getline(std::cin, text)) { randomize(text); std::cout << text << std::endl; } } <file_sep>/tpc/bin/netcat.cc #include "Acceptor.h" #include "InetAddress.h" #include "TcpStream.h" #include <thread> #include <string.h> #include <unistd.h> int write_n(int fd, const void* buf, int length) { int written = 0; while (written < length) { int nw = ::write(fd, static_cast<const char*>(buf) + written, length - written); if (nw > 0) { written += nw; } else if (nw == 0) { break; // EOF } else if (errno != EINTR) { perror("write"); break; } } return written; } void run(TcpStreamPtr stream) { // Caution: a bad example for closing connection std::thread thr([&stream] () { char buf[8192]; int nr = 0; while ( (nr = stream->receiveSome(buf, sizeof(buf))) > 0) { int nw = write_n(STDOUT_FILENO, buf, nr); if (nw < nr) { break; } } ::exit(0); // should somehow notify main thread instead }); char buf[8192]; int nr = 0; while ( (nr = ::read(STDIN_FILENO, buf, sizeof(buf))) > 0) { int nw = stream->sendAll(buf, nr); if (nw < nr) { break; } } stream->shutdownWrite(); thr.join(); } int main(int argc, const char* argv[]) { if (argc < 3) { printf("Usage:\n %s hostname port\n %s -l port\n", argv[0], argv[0]); return 0; } int port = atoi(argv[2]); if (strcmp(argv[1], "-l") == 0) { std::unique_ptr<Acceptor> acceptor(new Acceptor(InetAddress(port))); TcpStreamPtr stream(acceptor->accept()); if (stream) { acceptor.reset(); // stop listening run(std::move(stream)); } else { perror("accept"); } } else { InetAddress addr; const char* hostname = argv[1]; if (InetAddress::resolve(hostname, port, &addr)) { TcpStreamPtr stream(TcpStream::connect(addr)); if (stream) { run(std::move(stream)); } else { printf("Unable to connect %s\n", addr.toIpPort().c_str()); perror(""); } } else { printf("Unable to resolve %s\n", hostname); } } } <file_sep>/ssl/TlsConfig.cc #include "TlsConfig.h" #include "TlsStream.h" int TlsConfig::initialized = tls_init() + 1; <file_sep>/python/tcprelay.py #!/usr/bin/python import socket, thread, time listen_port = 3007 connect_addr = ('localhost', 2007) sleep_per_byte = 0.0001 def forward(source, destination): source_addr = source.getpeername() while True: data = source.recv(4096) if data: for i in data: destination.sendall(i) time.sleep(sleep_per_byte) else: print 'disconnect', source_addr destination.shutdown(socket.SHUT_WR) break serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serversocket.bind(('', listen_port)) serversocket.listen(5) while True: (clientsocket, address) = serversocket.accept() print 'accepted', address sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(connect_addr) print 'connected', sock.getpeername() thread.start_new_thread(forward, (clientsocket, sock)) thread.start_new_thread(forward, (sock, clientsocket)) <file_sep>/reactor/s01/Makefile LIB_SRC = Channel.cc EventLoop.cc Poller.cc BINARIES = test1 test2 test3 all: $(BINARIES) include ../reactor.mk test1: test1.cc test2: test2.cc test3: test3.cc <file_sep>/python/logviewer.py #!/usr/bin/python3 import io, os, re, sys from http import HTTPStatus, server FILE = None INDEX = """<!DOCTYPE html> <meta charset="utf-8"> <title>Log Viewer</title> <script> var logBox = null; var lastOffset = 0; function initialize() { logBox = document.getElementById('log'); lastOffset = 0; update(); } function update() { fetch('/get?offset=' + lastOffset).then(function(response) { if (response.ok) { return response.text(); } }).then(function(text) { lastOffset += text.length; logBox.value += text; // FIXME: escape logBox.scrollTop = logBox.scrollHeight; // Scroll to bottom setTimeout(update, 3000); }); } </script> <body onLoad="initialize();"> <textarea id="log" wrap="off" cols="120" rows="50" readonly="readonly"> </textarea> """ # INDEX = None # Dev mode class HTTPRequestHandler(server.BaseHTTPRequestHandler): def do_GET(self): if self.path == '/': self.send_OK("text/html", INDEX.encode()) elif self.path.startswith('/get?'): # TODO: convert query string to a dict m = re.search('offset=(\\d+)', self.path) offset = int(m.group(1)) if m else 0 m = re.search('length=(\\d+)', self.path) length = int(m.group(1)) if m else -1 FILE.seek(offset) body = FILE.read(length) self.send_OK("text/plain", body) else: self.send_error(HTTPStatus.NOT_FOUND, "File not found") def send_OK(self, content_type, body): self.send_response(HTTPStatus.OK) self.send_header("Content-Type", content_type) self.send_header('Content-Length', int(len(body))) self.end_headers() self.wfile.write(body) def main(argv): global FILE, INDEX FILE = open(argv[1], 'rb') if not INDEX: INDEX = open(os.path.splitext(argv[0])[0] + '.html').read() server.test(HandlerClass=HTTPRequestHandler) if __name__ == '__main__': main(sys.argv) <file_sep>/ssl/TlsAcceptor.cc #include "TlsAcceptor.h" #include "TlsStream.h" #include <stdio.h> #include <sys/socket.h> TlsAcceptor::TlsAcceptor(TlsConfig* config, const InetAddress& listenAddr) : context_(TlsContext::kServer, config), listenSock_(Socket::createTCP(AF_INET)) { listenSock_.setReuseAddr(true); listenSock_.bindOrDie(listenAddr); listenSock_.listenOrDie(); } TlsStreamPtr TlsAcceptor::accept() { // FIXME: use accept4 int sockfd = ::accept(listenSock_.fd(), NULL, NULL); if (sockfd >= 0) { TlsContext context = context_.accept(sockfd); if (context.handshake()) { LOG_ERROR << context.error(); return TlsStreamPtr(); } return TlsStreamPtr(new TlsStream(std::move(context))); } else { perror("TlsAcceptor::accept"); return TlsStreamPtr(); } } <file_sep>/tpc/bin/chargen.cc #include "thread/Atomic.h" #include "datetime/Timestamp.h" #include "Acceptor.h" #include "InetAddress.h" #include "TcpStream.h" #include <string.h> #include <thread> muduo::AtomicInt64 g_bytes; std::string getMessage() { std::string line; for (int i = 33; i < 127; ++i) { line.push_back(char(i)); } line += line; std::string message; for (size_t i = 0; i < 127-33; ++i) { message += line.substr(i, 72) + '\n'; } return message; } void measure() { muduo::Timestamp start = muduo::Timestamp::now(); while (true) { struct timespec ts = { 1, 0 }; ::nanosleep(&ts, NULL); // unfortunately, those two assignments are not atomic int64_t bytes = g_bytes.getAndSet(0); muduo::Timestamp end = muduo::Timestamp::now(); double elapsed = timeDifference(end, start); start = end; if (bytes) { printf("%.3f MiB/s\n", bytes / (1024.0 * 1024) / elapsed); } } } void chargen(TcpStreamPtr stream) { std::string message = getMessage(); while (true) { int nw = stream->sendAll(message.data(), message.size()); g_bytes.add(nw); if (nw < static_cast<int>(message.size())) { break; } } } // a thread-per-connection current chargen server and client int main(int argc, char* argv[]) { if (argc < 3) { printf("Usage:\n %s hostname port\n %s -l port\n", argv[0], argv[0]); std::string message = getMessage(); printf("message size = %zd\n", message.size()); return 0; } std::thread(measure).detach(); int port = atoi(argv[2]); if (strcmp(argv[1], "-l") == 0) { InetAddress listenAddr(port); Acceptor acceptor(listenAddr); printf("Accepting... Ctrl-C to exit\n"); int count = 0; while (true) { TcpStreamPtr tcpStream = acceptor.accept(); printf("accepted no. %d client\n", ++count); std::thread thr(chargen, std::move(tcpStream)); thr.detach(); } } else { InetAddress addr; const char* hostname = argv[1]; if (InetAddress::resolve(hostname, port, &addr)) { TcpStreamPtr stream(TcpStream::connect(addr)); if (stream) { chargen(std::move(stream)); } else { printf("Unable to connect %s\n", addr.toIpPort().c_str()); perror(""); } } else { printf("Unable to resolve %s\n", hostname); } } } <file_sep>/java/run.sh #!/bin/sh CLASSPATH=lib/junit-4.8.2.jar:\ lib/joda-time-1.6.2.jar:\ lib/groovy-1.7.10.jar:\ lib/asm-3.2.jar:\ lib/antlr-2.7.7.jar:\ ./bin export CLASSPATH mkdir bin javac -d bin billing/*.java billing/test/*.java java -ea org.junit.runner.JUnitCore billing.test.VipCustomerTest billing.test.NormalCustomerTest <file_sep>/protorpc/build.sh #!/bin/sh mkdir -p bin javac -extdirs lib -d bin echo/*.java <file_sep>/topk/word_freq_shards_basic.cc /* sort word by frequency, sharding version. 1. read input file, shard to N files: word 2. assume each shard file fits in memory, read each shard file, count words and sort by count, then write to N count files: count \t word 3. merge N count files using heap. Limits: each shard must fit in memory. */ #include <assert.h> #include "file.h" #include "merge.h" #include "timer.h" #include "absl/container/flat_hash_map.h" #include "absl/hash/hash.h" #include "absl/strings/str_format.h" #include "muduo/base/Logging.h" #include "muduo/base/ThreadPool.h" #include <algorithm> #include <memory> #include <string> #include <unordered_map> #include <vector> #include <fcntl.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> using absl::string_view; using std::string; using std::vector; using std::unique_ptr; int kShards = 10, kThreads = 4; bool g_verbose = false, g_keep = false; const char* shard_dir = "."; const char* g_output = "output"; class Sharder // : boost::noncopyable { public: Sharder() : files_(kShards) { for (int i = 0; i < kShards; ++i) { char name[256]; snprintf(name, sizeof name, "%s/shard-%05d-of-%05d", shard_dir, i, kShards); files_[i].reset(new OutputFile(name)); } assert(files_.size() == static_cast<size_t>(kShards)); } void output(string_view word) { size_t shard = hash(word) % files_.size(); files_[shard]->appendRecord(word); } void finish() { int shard = 0; for (const auto& file : files_) { // if (g_verbose) printf(" shard %d: %ld bytes, %ld items\n", shard, file->tell(), file->items()); ++shard; file->close(); } } private: absl::Hash<string_view> hash; vector<unique_ptr<OutputFile>> files_; }; int64_t shard_(int argc, char* argv[]) { Sharder sharder; Timer timer; int64_t total = 0; for (int i = optind; i < argc; ++i) { LOG_INFO << "Processing input file " << argv[i]; double t = Timer::now(); string line; InputFile input(argv[i]); while (input.getline(&line)) { sharder.output(line); } size_t len = input.tell(); total += len; double sec = Timer::now() - t; LOG_INFO << "Done file " << argv[i] << absl::StrFormat(" %.3f sec %.2f MiB/s", sec, len / sec / 1024 / 1024); } sharder.finish(); LOG_INFO << "Sharding done " << timer.report(total); return total; } // ======= count_shards ======= void count_shard(int shard, int fd, size_t len) { Timer timer; double t = Timer::now(); LOG_INFO << absl::StrFormat("counting shard %d: input file size %ld", shard, len); { void* mapped = mmap(NULL, len, PROT_READ, MAP_PRIVATE, fd, 0); assert(mapped != MAP_FAILED); const uint8_t* const start = static_cast<const uint8_t*>(mapped); const uint8_t* const end = start + len; // std::unordered_map<string_view, uint64_t> items; absl::flat_hash_map<string_view, uint64_t> items; int64_t count = 0; for (const uint8_t* p = start; p < end;) { string_view s((const char*)p+1, *p); items[s]++; p += 1 + *p; ++count; } LOG_INFO << "items " << count << " unique " << items.size(); if (g_verbose) printf(" count %.3f sec %ld items\n", Timer::now() - t, items.size()); t = Timer::now(); vector<std::pair<size_t, string_view>> counts; for (const auto& it : items) { if (it.second > 1) counts.push_back(std::make_pair(it.second, it.first)); } if (g_verbose) printf(" select %.3f sec %ld\n", Timer::now() - t, counts.size()); t = Timer::now(); std::sort(counts.begin(), counts.end()); if (g_verbose) printf(" sort %.3f sec\n", Timer::now() - t); t = Timer::now(); int64_t out_len = 0; { char buf[256]; snprintf(buf, sizeof buf, "count-%05d", shard); OutputFile output(buf); for (auto it = counts.rbegin(); it != counts.rend(); ++it) { output.write(absl::StrFormat("%d\t%s\n", it->first, it->second)); } for (const auto& it : items) { if (it.second == 1) { output.write(absl::StrFormat("1\t%s\n", it.first)); } } out_len = output.tell(); } if (g_verbose) printf(" output %.3f sec %lu\n", Timer::now() - t, out_len); if (munmap(mapped, len)) perror("munmap"); } ::close(fd); LOG_INFO << "shard " << shard << " done " << timer.report(len); } void count_shards(int shards) { assert(shards <= kShards); Timer timer; int64_t total = 0; muduo::ThreadPool threadPool; threadPool.setMaxQueueSize(2*kThreads); threadPool.start(kThreads); for (int shard = 0; shard < shards; ++shard) { char buf[256]; snprintf(buf, sizeof buf, "%s/shard-%05d-of-%05d", shard_dir, shard, kShards); int fd = open(buf, O_RDONLY); assert(fd >= 0); if (!g_keep) ::unlink(buf); struct stat st; if (::fstat(fd, &st) == 0) { size_t len = st.st_size; total += len; threadPool.run([shard, fd, len]{ count_shard(shard, fd, len); }); } } while (threadPool.queueSize() > 0) { LOG_DEBUG << "waiting for ThreadPool " << threadPool.queueSize(); muduo::CurrentThread::sleepUsec(1000*1000); } threadPool.stop(); LOG_INFO << "Counting done "<< timer.report(total); } // ======= merge ======= int main(int argc, char* argv[]) { /* int fd = open("shard-00000-of-00010", O_RDONLY); double t = Timer::now(); int64_t len = count_shard(0, fd); double sec = Timer::now() - t; printf("count_shard %.3f sec %.2f MB/s\n", sec, len / sec / 1e6); */ setlocale(LC_NUMERIC, ""); int opt; int count_only = 0; int merge_only = 0; while ((opt = getopt(argc, argv, "c:km:o:p:s:t:v")) != -1) { switch (opt) { case 'c': count_only = atoi(optarg); break; case 'k': g_keep = true; break; case 'm': merge_only = atoi(optarg); break; case 'o': g_output = optarg; break; case 'p': // Path for temp shard files shard_dir = optarg; break; case 's': kShards = atoi(optarg); break; case 't': kThreads = atoi(optarg); break; case 'v': g_verbose = true; break; } } if (count_only > 0 || merge_only) { g_keep = true; //g_verbose = true; count_only = std::min(count_only, kShards); if (count_only > 0) { count_shards(count_only); } if (merge_only > 0) { merge(merge_only); } } else { // Run all three steps Timer timer; LOG_INFO << argc - optind << " input files, " << kShards << " shards, " << "output " << g_output <<" , temp " << shard_dir; int64_t input = 0; input = shard_(argc, argv); count_shards(kShards); int64_t output_size = merge(kShards); LOG_INFO << "All done " << timer.report(input) << " output " << output_size; } } <file_sep>/tpc/lib/Socket.cc #include "Socket.h" #include "InetAddress.h" #include <assert.h> #include <unistd.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/socket.h> Socket::Socket(int sockfd) : sockfd_(sockfd) { assert(sockfd_ >= 0); } Socket::~Socket() { if (sockfd_ >= 0) { int ret = ::close(sockfd_); assert(ret == 0); (void)ret; } } void Socket::bindOrDie(const InetAddress& addr) { int ret = ::bind(sockfd_, addr.get_sockaddr(), addr.length()); if (ret) { perror("Socket::bindOrDie"); abort(); } } void Socket::listenOrDie() { int ret = ::listen(sockfd_, SOMAXCONN); if (ret) { perror("Socket::listen"); abort(); } } int Socket::connect(const InetAddress& addr) { return ::connect(sockfd_, addr.get_sockaddr(), addr.length()); } void Socket::shutdownWrite() { if (::shutdown(sockfd_, SHUT_WR) < 0) { perror("Socket::shutdownWrite"); } } void Socket::setReuseAddr(bool on) { int optval = on ? 1 : 0; if (::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval) < 0) { perror("Socket::setReuseAddr"); } } void Socket::setTcpNoDelay(bool on) { int optval = on ? 1 : 0; if (::setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, &optval, static_cast<socklen_t>(sizeof optval)) < 0) { perror("Socket::setTcpNoDelay"); } } InetAddress Socket::getLocalAddr() const { struct sockaddr_storage localaddr; socklen_t addrlen = sizeof localaddr; struct sockaddr* addr = reinterpret_cast<struct sockaddr*>(&localaddr); if (::getsockname(sockfd_, addr, &addrlen) < 0) { perror("Socket::getLocalAddr"); } return InetAddress(*addr); } InetAddress Socket::getPeerAddr() const { struct sockaddr_storage peeraddr; socklen_t addrlen = sizeof peeraddr; struct sockaddr* addr = reinterpret_cast<struct sockaddr*>(&peeraddr); if (::getpeername(sockfd_, addr, &addrlen) < 0) { perror("Socket::getPeerAddr"); } return InetAddress(*addr); } int Socket::recv(void* buf, int len) { #ifdef TEMP_FAILURE_RETRY return TEMP_FAILURE_RETRY(::recv(sockfd_, buf, len, 0)); #else return ::recv(sockfd_, buf, len, 0); #endif } int Socket::send(const void* buf, int len) { #ifdef TEMP_FAILURE_RETRY return TEMP_FAILURE_RETRY(::send(sockfd_, buf, len, 0)); #else return ::send(sockfd_, buf, len, 0); #endif } Socket Socket::createTCP(sa_family_t family) { int sockfd = ::socket(family, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP); assert(sockfd >= 0); return Socket(sockfd); } Socket Socket::createUDP(sa_family_t family) { int sockfd = ::socket(family, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP); assert(sockfd >= 0); return Socket(sockfd); } <file_sep>/basic/tutorial/sieve.cc #include <vector> #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { size_t N = argc > 1 ? atol(argv[1]) : 100; int count = 1; std::vector<bool> sieve(N, true); printf("2\n"); for (size_t i = 1; i < sieve.size(); ++i) { if (sieve[i]) { size_t p = 2*i + 1; ++count; printf("%zd\n", p); size_t q = 3 * p; size_t j = (q-1) / 2; while (j < sieve.size()) { sieve[j] = false; q += 2 * p; j = (q-1) / 2; } } } //printf("count = %d\n", count); } <file_sep>/puzzle/latin_square.cc #include <assert.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> int N = 4; int board[10][10]; uint32_t xmask[10], ymask[10]; int64_t count = 0; void backtrack(int x, int y) { assert(x < N && y < N); uint32_t mask = xmask[x] | ymask[y]; uint32_t avail = ~mask - 1; while (avail) { int i = __builtin_ctz(avail); // counting trailing zeros avail &= avail-1; if (i > N) break; uint32_t needle = 1 << i; board[x][y] = i; uint32_t oldxmask = xmask[x]; uint32_t oldymask = ymask[y]; assert((oldxmask & needle) == 0); assert((oldymask & needle) == 0); xmask[x] |= needle; ymask[y] |= needle; if (x == N-1 && y == N-1) ++count; else if (x == N-1) backtrack(1, y+1); else backtrack(x+1, y); xmask[x] = oldxmask; ymask[y] = oldymask; } } void put(int x, int y, int i) { board[x][y] = i; xmask[x] |= 1 << i; ymask[y] |= 1 << i; } int main(int argc, char* argv[]) { N = argc > 1 ? atoi(argv[1]) : 4; for (int i = 0; i < N; ++i) { put(i, 0, i+1); put(0, i, i+1); } backtrack(1, 1); printf("%zd\n", count); } <file_sep>/faketcp/discardall.cc #include "faketcp.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <linux/if_ether.h> void tcp_input(int fd, const void* input, const void* payload, int tot_len) { const struct iphdr* iphdr = static_cast<const struct iphdr*>(input); const struct tcphdr* tcphdr = static_cast<const struct tcphdr*>(payload); const int iphdr_len = iphdr->ihl*4; const int tcp_seg_len = tot_len - iphdr_len; const int tcphdr_size = sizeof(*tcphdr); if (tcp_seg_len >= tcphdr_size && tcp_seg_len >= tcphdr->doff*4) { const int tcphdr_len = tcphdr->doff*4; const int payload_len = tot_len - iphdr_len - tcphdr_len; char source[INET_ADDRSTRLEN]; char dest[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &iphdr->saddr, source, INET_ADDRSTRLEN); inet_ntop(AF_INET, &iphdr->daddr, dest, INET_ADDRSTRLEN); printf("IP %s.%d > %s.%d: ", source, ntohs(tcphdr->source), dest, ntohs(tcphdr->dest)); printf("Flags [%c], seq %u, win %d, length %d%s\n", tcphdr->syn ? 'S' : (tcphdr->fin ? 'F' : '.'), ntohl(tcphdr->seq), ntohs(tcphdr->window), payload_len, tcphdr_len > sizeof(struct tcphdr) ? " <>" : ""); union { unsigned char output[ETH_FRAME_LEN]; struct { struct iphdr iphdr; struct tcphdr tcphdr; } out; }; static_assert(sizeof(out) == sizeof(struct iphdr) + sizeof(struct tcphdr), ""); int output_len = sizeof(out); bzero(&out, output_len + 4); memcpy(output, input, sizeof(struct iphdr)); out.tcphdr.source = tcphdr->dest; out.tcphdr.dest = tcphdr->source; out.tcphdr.doff = sizeof(struct tcphdr) / 4; out.tcphdr.window = htons(65000); bool response = false; const uint32_t seq = ntohl(tcphdr->seq); const uint32_t isn = 123456; if (tcphdr->syn) { out.tcphdr.seq = htonl(isn); out.tcphdr.ack_seq = htonl(seq+1); out.tcphdr.syn = 1; out.tcphdr.ack = 1; // set mss=1000 unsigned char* mss = output + output_len; *mss++ = 2; *mss++ = 4; *mss++ = 0x03; *mss++ = 0xe8; // 1000 == 0x03e8 out.tcphdr.doff += 1; output_len += 4; response = true; } else if (tcphdr->fin) { out.tcphdr.seq = htonl(isn+1); out.tcphdr.ack_seq = htonl(seq+1); out.tcphdr.fin = 1; out.tcphdr.ack = 1; response = true; } else if (payload_len > 0) { out.tcphdr.seq = htonl(isn+1); out.tcphdr.ack_seq = htonl(seq+payload_len); out.tcphdr.ack = 1; response = true; } // build IP header out.iphdr.tot_len = htons(output_len); std::swap(out.iphdr.saddr, out.iphdr.daddr); out.iphdr.check = 0; out.iphdr.check = in_checksum(output, sizeof(struct iphdr)); unsigned char* pseudo = output + output_len; pseudo[0] = 0; pseudo[1] = IPPROTO_TCP; pseudo[2] = 0; pseudo[3] = output_len - sizeof(struct iphdr); out.tcphdr.check = in_checksum(&out.iphdr.saddr, output_len - 8); if (response) { write(fd, output, output_len); } } } int main(int argc, char* argv[]) { char ifname[IFNAMSIZ] = "tun%d"; bool offload = argc > 1 && strcmp(argv[1], "-K") == 0; int fd = tun_alloc(ifname, offload); if (fd < 0) { fprintf(stderr, "tunnel interface allocation failed\n"); exit(1); } printf("allocted tunnel interface %s\n", ifname); sleep(1); for (;;) { union { unsigned char buf[IP_MAXPACKET]; struct iphdr iphdr; }; const int iphdr_size = sizeof iphdr; int nread = read(fd, buf, sizeof(buf)); if (nread < 0) { perror("read"); close(fd); exit(1); } else if (nread == sizeof(buf)) { printf("possible message truncated.\n"); } printf("read %d bytes from tunnel interface %s.\n", nread, ifname); const int iphdr_len = iphdr.ihl*4; // FIXME: check nread >= sizeof iphdr before accessing iphdr.ihl. if (nread >= iphdr_size && iphdr.version == 4 && iphdr_len >= iphdr_size && iphdr_len <= nread && iphdr.tot_len == htons(nread) && in_checksum(buf, iphdr_len) == 0) { const void* payload = buf + iphdr_len; if (iphdr.protocol == IPPROTO_ICMP) { icmp_input(fd, buf, payload, nread); } else if (iphdr.protocol == IPPROTO_TCP) { tcp_input(fd, buf, payload, nread); } } else if (iphdr.version == 4) { printf("bad packet\n"); for (int i = 0; i < nread; ++i) { if (i % 4 == 0) printf("\n"); printf("%02x ", buf[i]); } printf("\n"); } } return 0; } <file_sep>/sudoku/sudoku.h #ifndef SUDOKU_H #define SUDOKU_H const bool DEBUG_MODE = false; enum { ROW=9, COL=9, N = 81, NEIGHBOR = 20 }; const int NUM = 9; extern int neighbors[N][NEIGHBOR]; extern int board[N]; extern int spaces[N]; extern int nspaces; extern int (*chess)[COL]; void init_neighbors(); void input(const char in[N]); void init_cache(); bool available(int guess, int cell); bool solve_sudoku_basic(int which_space); bool solve_sudoku_min_arity(int which_space); bool solve_sudoku_min_arity_cache(int which_space); bool solve_sudoku_dancing_links(int unused); bool solved(); #endif <file_sep>/benchmark/bm_ipc.cc #include <fcntl.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include "benchmark/benchmark.h" void readwrite(int fds[], void* buf, int len) { int nw = write(fds[1], buf, len); if (nw != len) { perror("write"); printf("%d != %d\n", nw, len); assert(0); } int nr = read(fds[0], buf, len); assert(nr == len); } void do_benchmark(benchmark::State& state, int fds[], int len) { void* buf = ::malloc(len); memset(buf, 0, len); for (auto _ : state) { readwrite(fds, buf, len); } state.SetBytesProcessed(len * state.iterations()); state.SetItemsProcessed(state.iterations()); ::free(buf); } const int bufsize = 128 * 1024; static void BM_pipe(benchmark::State& state) { static int fds[2] = { 0, 0 }; if (fds[0] == 0) { if (pipe(fds) < 0) { perror("pipe"); assert(0); } fcntl(fds[0], F_SETPIPE_SZ, bufsize); } int64_t len = state.range(0); do_benchmark(state, fds, len); } BENCHMARK(BM_pipe)->Range(8, 1 << 17); static void BM_unix(benchmark::State& state) { static int fds[2] = { 0, 0 }; if (fds[0] == 0) { if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) { perror("socketpair"); assert(0); } } int64_t len = state.range(0); do_benchmark(state, fds, len); } BENCHMARK(BM_unix)->Range(8, 1 << 17); static void BM_tcp(benchmark::State& state) { static int fds[2]; if (fds[0] == 0) { int listenfd = socket(AF_INET, SOCK_STREAM, 0); listen(listenfd, 5); struct sockaddr_storage saddr; socklen_t addr_len = sizeof saddr; getsockname(listenfd, (struct sockaddr*)&saddr, &addr_len); fds[0] = socket(AF_INET, SOCK_STREAM, 0); connect(fds[0], (struct sockaddr*)&saddr, addr_len); fds[1] = accept(listenfd, NULL, NULL); close(listenfd); int one = 1; setsockopt(fds[1], IPPROTO_TCP, TCP_NODELAY, &one, sizeof one); setsockopt(fds[1], SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof bufsize); setsockopt(fds[0], SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof bufsize); } int64_t len = state.range(0); do_benchmark(state, fds, len); } BENCHMARK(BM_tcp)->Range(8, 1 << 17); <file_sep>/digest/test_oop.cc #include "DigestOOP.h" void print(const std::string& d) { for (int i = 0; i < d.size(); ++i) { printf("%02x", (unsigned char)d[i]); } printf("\n"); } int main(int argc, char* argv[]) { auto md5 = oop::Digest::create(oop::Digest::MD5); print(md5->digest()); auto sha1 = oop::Digest::create(oop::Digest::SHA1); print(sha1->digest()); auto sha256 = oop::Digest::create(oop::Digest::SHA256); print(sha256->digest()); } <file_sep>/logging/AsyncLoggingDoubleBuffering.h #ifndef MUDUO_BASE_ASYNCLOGGINGDOUBLEBUFFERING_H #define MUDUO_BASE_ASYNCLOGGINGDOUBLEBUFFERING_H #include "LogStream.h" #include "thread/BlockingQueue.h" #include "thread/BoundedBlockingQueue.h" #include "thread/CountDownLatch.h" #include "thread/Mutex.h" #include "thread/Thread.h" #include <boost/bind.hpp> #include <boost/noncopyable.hpp> #include <boost/scoped_ptr.hpp> #include <boost/ptr_container/ptr_vector.hpp> namespace muduo { class AsyncLoggingDoubleBuffering : boost::noncopyable { public: typedef muduo::detail::FixedBuffer<muduo::detail::kLargeBuffer> Buffer; typedef boost::ptr_vector<Buffer> BufferVector; typedef BufferVector::auto_type BufferPtr; AsyncLoggingDoubleBuffering(const string& basename, // FIXME: StringPiece size_t rollSize, int flushInterval = 3) : flushInterval_(flushInterval), running_(false), basename_(basename), rollSize_(rollSize), thread_(boost::bind(&AsyncLoggingDoubleBuffering::threadFunc, this), "Logging"), latch_(1), mutex_(), cond_(mutex_), currentBuffer_(new Buffer), nextBuffer_(new Buffer), buffers_() { currentBuffer_->bzero(); nextBuffer_->bzero(); buffers_.reserve(16); } ~AsyncLoggingDoubleBuffering() { if (running_) { stop(); } } void append(const char* logline, int len) { muduo::MutexLockGuard lock(mutex_); if (currentBuffer_->avail() > len) { currentBuffer_->append(logline, len); } else { buffers_.push_back(currentBuffer_.release()); if (nextBuffer_) { currentBuffer_ = boost::ptr_container::move(nextBuffer_); } else { currentBuffer_.reset(new Buffer); // Rarely happens } currentBuffer_->append(logline, len); cond_.notify(); } } void start() { running_ = true; thread_.start(); latch_.wait(); } void stop() { running_ = false; cond_.notify(); thread_.join(); } private: void threadFunc() { assert(running_ == true); latch_.countDown(); LogFile output(basename_, rollSize_, false); BufferPtr newBuffer1(new Buffer); BufferPtr newBuffer2(new Buffer); newBuffer1->bzero(); newBuffer2->bzero(); boost::ptr_vector<Buffer> buffersToWrite; buffersToWrite.reserve(16); while (running_) { assert(newBuffer1 && newBuffer1->length() == 0); assert(newBuffer2 && newBuffer2->length() == 0); assert(buffersToWrite.empty()); { muduo::MutexLockGuard lock(mutex_); if (!buffers_.empty()) { cond_.waitForSeconds(flushInterval_); } buffers_.push_back(currentBuffer_.release()); currentBuffer_ = boost::ptr_container::move(newBuffer1); buffersToWrite.swap(buffers_); if (!nextBuffer_) { nextBuffer_ = boost::ptr_container::move(newBuffer2); } } assert(!buffersToWrite.empty()); if (buffersToWrite.size() > 25) { const char* dropMsg = "Dropped log messages\n"; fprintf(stderr, "%s", dropMsg); output.append(dropMsg, strlen(dropMsg)); buffersToWrite.erase(buffersToWrite.begin(), buffersToWrite.end() - 2); } for (size_t i = 0; i < buffersToWrite.size(); ++i) { // FIXME: use unbuffered stdio FILE ? or use ::writev ? output.append(buffersToWrite[i].data(), buffersToWrite[i].length()); } if (buffersToWrite.size() > 2) { // drop non-bzero-ed buffers, avoid trashing buffersToWrite.resize(2); } if (!newBuffer1) { assert(!buffersToWrite.empty()); newBuffer1 = buffersToWrite.pop_back(); newBuffer1->reset(); } if (!newBuffer2) { assert(!buffersToWrite.empty()); newBuffer2 = buffersToWrite.pop_back(); newBuffer2->reset(); } buffersToWrite.clear(); output.flush(); } output.flush(); } const int flushInterval_; bool running_; string basename_; size_t rollSize_; muduo::Thread thread_; muduo::CountDownLatch latch_; muduo::MutexLock mutex_; muduo::Condition cond_; BufferPtr currentBuffer_; BufferPtr nextBuffer_; BufferVector buffers_; }; } #endif // MUDUO_BASE_ASYNCLOGGINGDOUBLEBUFFERING_H <file_sep>/reactor/s03/Makefile LIB_SRC = Channel.cc EventLoop.cc EventLoopThread.cc Poller.cc Timer.cc TimerQueue.cc BINARIES = test1 test2 test3 test4 test5 test6 all: $(BINARIES) include ../reactor.mk test1: test1.cc test2: test2.cc test3: test3.cc test4: test4.cc test5: test5.cc test6: test6.cc <file_sep>/protorpc/run_server.sh #!/bin/sh java -ea -server -Djava.ext.dirs=lib -cp bin echo.EchoServer <file_sep>/benchmark/format.h #include <string> std::string formatSI(size_t n); std::string formatIEC(size_t n); <file_sep>/tpc/bin/footprint.cc #include <stdio.h> #include <sys/time.h> #include <unistd.h> #include "Acceptor.h" #include "InetAddress.h" #include "Socket.h" #include "TcpStream.h" void dump(const char* filename) { char buf[65536]; FILE* fp = fopen(filename, "r"); if (fp) { ssize_t nr; while ( (nr = fread(buf, 1, sizeof buf, fp)) > 0) fwrite(buf, 1, nr, stdout); fclose(fp); } } void snapshot(const char* name, int N) { printf("===== %d %s =====\n", N, name); dump("/proc/meminfo"); dump("/proc/slabinfo"); } int main(int argc, char* argv[]) { const int N = argc > 1 ? atoi(argv[1]) : 1000; snapshot("started", N); InetAddress listenAddr(2222); Acceptor acceptor(listenAddr); snapshot("acceptor created", 1); InetAddress serverAddr("127.0.0.1", 2222); std::vector<Socket> clients; clients.reserve(N); for (int i = 0; i < N; ++i) clients.push_back(Socket::createTCP(serverAddr.family())); snapshot("clients created", N); std::vector<Socket> servers; servers.reserve(N); for (int i = 0; i < N; ++i) { char buf[64]; const int ports_per_ip = 16384; int clientIP = i / ports_per_ip; snprintf(buf, sizeof buf, "127.1.%d.%d", clientIP / 128, clientIP % 128); InetAddress localAddr(buf, 10000 + i % ports_per_ip); clients[i].bindOrDie(localAddr); if (i % 10000 == 0) { struct timeval tv; gettimeofday(&tv, NULL); fprintf(stderr, "%ld.%06ld Client %d bind to %s\n", tv.tv_sec, tv.tv_usec, i, buf); } if (clients[i].connect(serverAddr)) { perror("connect"); break; } servers.push_back(acceptor.acceptSocketOrDie()); } snapshot("clients connected", N); // TODO: epoll servers.clear(); snapshot("servers disconnected", N); clients.clear(); snapshot("clients disconnected", N); } <file_sep>/ssl/server.cc #include "timer.h" #include "InetAddress.h" #include "TlsAcceptor.h" #include "TlsConfig.h" #include "TlsStream.h" int main(int argc, char* argv[]) { TlsConfig config; // config.setCaFile("ca.pem"); config.setCertFile("server.pem"); config.setKeyFile("server.pem"); InetAddress listenAddr(4433); TlsAcceptor acceptor(&config, listenAddr); TlsStreamPtr stream = acceptor.accept(); if (stream) { LOG_INFO << "OK"; int64_t total = 0; char buf[20 * 1024]; int nr = 0; Timer t; t.start(); while ( (nr = stream->receiveSome(buf, sizeof buf)) > 0) { // LOG_INFO << "nr = " << nr; total += nr; } // LOG_INFO << "nr = " << nr; t.stop(); LOG_INFO << "DONE " << total << " " << (total / t.seconds() / 1e6) << " MB/s"; } } <file_sep>/python/echo-poll.py #!/usr/bin/python import socket import select server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(('', 2007)) server_socket.listen(5) # server_socket.setblocking(0) poll = select.poll() # epoll() should work the same poll.register(server_socket.fileno(), select.POLLIN) connections = {} while True: events = poll.poll(10000) # 10 seconds for fileno, event in events: if fileno == server_socket.fileno(): (client_socket, client_address) = server_socket.accept() print "got connection from", client_address # client_socket.setblocking(0) poll.register(client_socket.fileno(), select.POLLIN) connections[client_socket.fileno()] = client_socket elif event & select.POLLIN: client_socket = connections[fileno] data = client_socket.recv(4096) if data: client_socket.send(data) # sendall() partial? else: poll.unregister(fileno) client_socket.close() del connections[fileno] <file_sep>/ssl/TlsStream.h #pragma once #include "TlsContext.h" class InetAddress; class TlsStream; typedef std::unique_ptr<TlsStream> TlsStreamPtr; // A blocking TLS stream class TlsStream : noncopyable { public: explicit TlsStream(TlsContext&& context) : context_(std::move(context)) // must be established { LOG_INFO << context_.cipher(); } ~TlsStream() = default; TlsStream(TlsStream&&) = default; // TlsStream& operator=(TlsStream&&) = default; static TlsStreamPtr connect(TlsConfig* config, const char* hostport, const char* servername = nullptr); // NOT thread safe int receiveAll(void* buf, int len); // read len bytes, unless error happens int receiveSome(void* buf, int len); // read len or less bytes int sendAll(const void* buf, int len); // send len bytes, unless error happens int sendSome(const void* buf, int len); // send len or less bytes private: TlsContext context_; }; <file_sep>/string/build.sh #!/bin/sh set -x g++ StringEager.cc main.cc -Wall -m64 -o e64 && ./e64 g++ StringEager.cc main.cc -Wall -m32 -o e32 && ./e32 g++ StringEager.cc main.cc -Wall -m64 -std=c++0x -o f64 && ./f64 g++ StringEager.cc main.cc -Wall -m32 -std=c++0x -o f32 && ./f32 g++ StringEager.cc test.cc -Wall -DBOOST_TEST_DYN_LINK -lboost_unit_test_framework -m64 -o w64 && ./w64 g++ StringEager.cc test.cc -Wall -m32 -o w32 && ./w32 g++ StringEager.cc test.cc -Wall -DBOOST_TEST_DYN_LINK -lboost_unit_test_framework -m64 -std=c++0x -o u64 && ./u64 g++ StringEager.cc test.cc -Wall -m32 -std=c++0x -o u32 && ./u32 <file_sep>/digest/DigestOOP2.cc #include "DigestOOP.h" #include <openssl/crypto.h> #include <openssl/md5.h> #include <openssl/sha.h> namespace oop { #define DEFINE(name) \ class name##Digest : public Digest \ { \ public: \ name##Digest() \ { \ name##_Init(&ctx_); \ } \ \ ~name##Digest() override \ { \ OPENSSL_cleanse(&ctx_, sizeof(ctx_)); \ } \ \ void update(const void* data, int len) override \ { \ name##_Update(&ctx_, data, len); \ } \ \ std::string digest() override \ { \ unsigned char result[name##_DIGEST_LENGTH]; \ name##_Final(result, &ctx_); \ return std::string(reinterpret_cast<char*>(result), \ name##_DIGEST_LENGTH); \ } \ \ int length() const override \ { \ return name##_DIGEST_LENGTH; \ } \ \ private: \ name##_CTX ctx_; \ }; #define SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH #define SHA1_CTX SHA_CTX DEFINE(MD5); DEFINE(SHA1); DEFINE(SHA256); // static std::unique_ptr<Digest> Digest::create(Type t) { if (t == MD5) return std::make_unique<MD5Digest>(); else if (t == SHA1) return std::make_unique<SHA1Digest>(); else if (t == SHA256) return std::make_unique<SHA256Digest>(); else return nullptr; } } <file_sep>/digest/test_evp2.cc #include "DigestEVP2.h" #include <sys/time.h> double now() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec / 1000000.0; } void print(const std::string& d) { for (int i = 0; i < d.size(); ++i) { printf("%02x", (unsigned char)d[i]); } printf("\n"); } evp::Digest getDefaultDigest() { return evp::Digest(evp::Digest::SHA1); } void testThroughput(evp::Digest::Type type, int nblocks, int block_size) { std::string x(block_size, 'x'); double start = now(); evp::Digest d(type); for (int i = 0; i < nblocks; ++i) d.update(x.data(), x.size()); d.digest(); double seconds = now() - start; int64_t bytes = int64_t(nblocks) * block_size; printf("%-6s %7.2f MiB/s\n", d.name(), bytes / seconds / 1024 / 1024); } void testLatency(evp::Digest::Type type, int nblocks, int block_size) { std::string x(block_size, 'x'); double start = now(); for (int i = 0; i < nblocks; ++i) { evp::Digest d(type); d.update(x.data(), x.size()); d.digest(); } double seconds = now() - start; int64_t bytes = int64_t(nblocks) * block_size; printf("%-6s %7.0f op/s %8.3f us/op %7.2f MiB/s\n", evp::Digest(type).name(), nblocks / seconds, seconds * 1e6 / nblocks, bytes / seconds / 1024 / 1024); } int main(int argc, char* argv[]) { // No OpenSSL_add_all_digests(); if (argc == 4) { int nblocks = atoi(argv[2]); int block_size = atoi(argv[3]); if (argv[1][0] == 't') { testThroughput(evp::Digest::MD5, nblocks, block_size); testThroughput(evp::Digest::SHA1, nblocks, block_size); testThroughput(evp::Digest::SHA256, nblocks, block_size); testThroughput(evp::Digest::SHA512, nblocks, block_size); } else { testLatency(evp::Digest::MD5, nblocks, block_size); testLatency(evp::Digest::SHA1, nblocks, block_size); testLatency(evp::Digest::SHA256, nblocks, block_size); testLatency(evp::Digest::SHA512, nblocks, block_size); } } else { evp::Digest md5(evp::Digest::MD5); print(md5.digest()); evp::Digest sha1(evp::Digest::SHA1); print(sha1.digest()); evp::Digest sha256(evp::Digest::SHA256); print(sha256.digest()); evp::Digest md = getDefaultDigest(); md.update("hello\n", 6); print(md.digest()); md = getDefaultDigest(); md = std::move(md); } } <file_sep>/reactor/mkdiff.sh #!/bin/sh diff_a_file() { diff $1 $2 -q |grep differ |grep -v Makefile|awk '{\ split($2, old, "/"); \ split($4, new, "/"); \ print "diff -U200", $2, $4, "| awk \" NR>3 {print}\" >", new[1]"-"old[1]"-"new[2]".diff"}' echo } diff_a_file s00 s01 diff_a_file s01 s02 diff_a_file s02 s03 diff_a_file s03 s04 diff_a_file s04 s05 diff_a_file s05 s06 diff_a_file s06 s07 diff_a_file s07 s08 diff_a_file s08 s09 diff_a_file s09 s10 diff_a_file s10 s11 diff_a_file s11 s12 diff_a_file s12 s13 <file_sep>/benchmark/bm_compress.cc #include <string.h> #include <memory> #include <string> #include <unordered_set> #include "benchmark/benchmark.h" #include <brotli/encode.h> #include "huf.h" #include "lz4.h" #include <snappy.h> #include "zlib.h" #include "zstd.h" enum Compress { Brotli, Huff0, // only for input size <= 128KiB LZ4, None, // memcpy Snappy, Zlib, Zstd, // Zstd is much faster on Haswell with BMI2 instructions. }; template<Compress c> static void compress(const std::string& input, benchmark::State& state) { size_t output_len = 0; int level = state.range(0); if (c == Brotli) { output_len = BrotliEncoderMaxCompressedSize(input.size()); } else if (c == Huff0) { output_len = HUF_compressBound(std::min<size_t>(input.size(), HUF_BLOCKSIZE_MAX)); } else if (c == None) { output_len = input.size(); } else if (c == Snappy) { output_len = snappy::MaxCompressedLength(input.size()); } else if (c == LZ4) { output_len = LZ4_compressBound(input.size()); } else if (c == Zlib) { output_len = compressBound(input.size()); } else if (c == Zstd) { output_len = ZSTD_compressBound(input.size()); } // printf("%zd %zd %.5f\n", input.size(), output_len, double(output_len) / input.size()); std::unique_ptr<char[]> output(new char[output_len]); size_t compressed_len = 0; for (auto _ : state) { if (c == Brotli) { compressed_len = output_len; BrotliEncoderCompress(level, BROTLI_DEFAULT_WINDOW, BROTLI_DEFAULT_MODE, input.size(), reinterpret_cast<const unsigned char*>(input.c_str()), &compressed_len, reinterpret_cast<unsigned char*>(output.get())); } else if (c == Huff0) { std::string_view in(input); compressed_len = 0; while (!in.empty()) { size_t src = std::min<size_t>(in.size(), HUF_BLOCKSIZE_MAX); output_len = HUF_compressBound(src); //printf("%zd %zd\n", src, output_len); size_t compressed = HUF_compress(output.get(), output_len, in.data(), src); if (compressed == 0) { // not compressible compressed_len += output_len; } else if (HUF_isError(compressed)) { printf("%s\n", HUF_getErrorName(compressed)); state.SetLabel(HUF_getErrorName(compressed)); return; break; } else { compressed_len += compressed; } in.remove_prefix(src); } } else if (c == LZ4) { compressed_len = LZ4_compress_default(input.c_str(), output.get(), input.size(), output_len); } else if (c == None) { memcpy(output.get(), input.c_str(), input.size()); compressed_len = output_len; } else if (c == Snappy) { snappy::RawCompress(input.c_str(), input.size(), output.get(), &compressed_len); } else if (c == Zlib) { compressed_len = output_len; compress2(reinterpret_cast<unsigned char*>(output.get()), &compressed_len, reinterpret_cast<const unsigned char*>(input.c_str()), input.size(), level); } else if (c == Zstd) { compressed_len = ZSTD_compress(output.get(), output_len, input.c_str(), input.size(), level); if (ZSTD_isError(compressed_len)) { state.SkipWithError(ZSTD_getErrorName(compressed_len)); } } } state.SetItemsProcessed(state.iterations()); state.SetBytesProcessed(input.size() * state.iterations()); char buf[256]; // printf("%zd %zd\n", input.size(), output_len); if (ZSTD_isError(compressed_len)) { snprintf(buf, sizeof buf, "%s", ZSTD_getErrorName(compressed_len)); } else { snprintf(buf, sizeof buf, "compress: %.8f", input.size() / double(compressed_len)); } state.SetLabel(buf); } template<Compress c> static void BM_highest(benchmark::State& state) { std::string input; while (input.size() < 100*1024*1024) input += "aaaaaaaaaa"; compress<c>(input, state); } BENCHMARK_TEMPLATE(BM_highest, None)->Arg(0)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_highest, Snappy)->Arg(0)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_highest, LZ4)->Arg(0)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_highest, Zlib)->Arg(1)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_highest, Brotli)->DenseRange(0, 7)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_highest, Zstd)->DenseRange(1, 9)->Unit(benchmark::kMillisecond); // zlib's max window size is 32768, and minimal match length is 3, // so we generate non-repetitive two-byte tuples with total length > 64k. // this algorithm is not efficient, we should probably use 'notseen' instead. // TODO: generate incompressible data for zstd. // zstd's minimal match length is 3, but window size can be as large as 8M, // so this doesn't work. std::string getIncompressible() { std::unordered_set<unsigned char> seen[256]; unsigned char current = 0; std::string result; while (true) { result.push_back(current); if (result.size() >= 256*255) break; if (seen[current].size() >= 256) break; unsigned char next = current + 1; while (seen[current].count(next) > 0) { next++; } seen[current].insert(next); current = next; } return result; } std::string getIncompressibleZstd() { printf("Generating incompressible data for Zstd..."); fflush(stdout); std::set<unsigned char> avails[256*256]; std::set<unsigned char> all; for (int i = 0; i < 256; ++i) all.insert(i); for (auto& x : avails) x = all; std::string data; data.reserve(256*256*256); data.push_back('\0'); data.push_back('\1'); bool popped = false; while (true) { assert(data.size() >= 2); unsigned char prev = data[data.size()-2]; unsigned char curr = data.back(); unsigned key = prev * 256 + curr; assert(key < 256*256); auto& avail = avails[key]; if (avail.empty()) { if (popped) break; popped = true; data.pop_back(); continue; } unsigned char next = data.back() + 1; auto it = avail.lower_bound(next); if (it != avail.end()) { // next avail next = *it; } else { // wrap to front next = *avail.begin(); } size_t c = avail.erase(next); assert(c == 1); data.push_back(next); } printf(" done %zd\n", data.size()); return data; } std::string incompressible; template<Compress c> static void BM_lowest(benchmark::State& state) { if (incompressible.empty()) incompressible = getIncompressibleZstd(); std::string input = incompressible; // printf("incompressible %zd\n", input.size()); while (input.size() < 100*1024*1024) input += input; compress<c>(input, state); } BENCHMARK_TEMPLATE(BM_lowest, Snappy)->Arg(0)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_lowest, LZ4)->Arg(0)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_lowest, Zlib)->Arg(1)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_lowest, Brotli)->DenseRange(0, 7)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_lowest, Zstd)->DenseRange(1, 9)->Unit(benchmark::kMillisecond); const char* g_file = "input"; template<Compress c> static void BM_file(benchmark::State& state) { std::string input; FILE* fp = fopen(g_file, "r"); if (!fp) { state.SkipWithError(strerror(errno)); return; } assert(fp); size_t nr = 0; char buf[64*1024]; while ( (nr = fread(buf, 1, sizeof buf, fp)) > 0) input.append(buf, nr); fclose(fp); compress<c>(input, state); } BENCHMARK_TEMPLATE(BM_file, Huff0)->Arg(0)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_file, Snappy)->Arg(0)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_file, LZ4)->Arg(0)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_file, Zlib)->DenseRange(1, 7)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_file, Brotli)->DenseRange(BROTLI_MIN_QUALITY, 7)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_file, Zstd)->DenseRange(1, 12)->Unit(benchmark::kMillisecond); <file_sep>/topk/gen_count.py #!/usr/bin/python import random word_len = 5 alphabet = 'ABCDEF<KEY>' output = open('word_count', 'w') words = set() N = 1000*1000 for x in xrange(N): arr = [random.choice(alphabet) for i in range(word_len)] words.add(''.join(arr)) print len(words) for word in words: output.write(word) output.write('\t') output.write(str(random.randint(1, 2*N))) output.write('\n') <file_sep>/ssl/benchmark-openssl.cc #include <openssl/aes.h> #include <openssl/conf.h> #include <openssl/err.h> #include <openssl/ssl.h> #include <stdio.h> #include "timer.h" int main(int argc, char* argv[]) { printf("Compiled with " OPENSSL_VERSION_TEXT "\n"); SSL_load_error_strings(); // ERR_load_BIO_strings(); SSL_library_init(); OPENSSL_config(NULL); SSL_CTX* ctx = SSL_CTX_new(TLSv1_2_server_method()); SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION); EC_KEY* ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE); // if (argc > 3) SSL_CTX_set_tmp_ecdh(ctx, ecdh); EC_KEY_free(ecdh); const char* CertFile = "server.pem"; // argv[1]; const char* KeyFile = "server.pem"; // argv[2]; SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM); SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM); if (!SSL_CTX_check_private_key(ctx)) abort(); SSL_CTX* ctx_client = SSL_CTX_new(TLSv1_2_client_method()); double start = now(); const int N = 1000; SSL *ssl, *ssl_client; Timer tc, ts; for (int i = 0; i < N; ++i) { BIO *client, *server; BIO_new_bio_pair(&client, 0, &server, 0); ssl = SSL_new (ctx); ssl_client = SSL_new (ctx_client); SSL_set_bio(ssl, server, server); SSL_set_bio(ssl_client, client, client); tc.start(); int ret = SSL_connect(ssl_client); tc.stop(); //printf("%d %d\n", ret, BIO_retry_type(&server)); ts.start(); int ret2 = SSL_accept(ssl); ts.stop(); //printf("%d %d\n", ret2, BIO_retry_type(&client)); while (true) { tc.start(); ret = SSL_do_handshake(ssl_client); tc.stop(); //printf("client handshake %d %d\n", ret, BIO_retry_type(&server)); ts.start(); ret2 = SSL_do_handshake(ssl); ts.stop(); //printf("server handshake %d %d\n", ret2, BIO_retry_type(&client)); //if (ret == -1 && BIO_retry_type(&server) == 0) // break; //if (ret2 == -1 && BIO_retry_type(&client) == 0) // break; if (ret == 1 && ret2 == 1) break; } if (i == 0) { printf("SSL connection using %s %s\n", SSL_get_version(ssl_client), SSL_get_cipher (ssl_client)); #ifdef OPENSSL_IS_BORINGSSL printf("Curve: %s\n", SSL_get_curve_name(SSL_get_curve_id(ssl_client))); #elif OPENSSL_VERSION_NUMBER >= 0x10002000L EVP_PKEY *key; if (SSL_get_server_tmp_key(ssl_client, &key)) { if (EVP_PKEY_id(key) == EVP_PKEY_EC) { EC_KEY *ec = EVP_PKEY_get1_EC_KEY(key); int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec)); EC_KEY_free(ec); const char *cname = EC_curve_nid2nist(nid); if (!cname) cname = OBJ_nid2sn(nid); printf("Curve: %s, %d bits\n", cname, EVP_PKEY_bits(key)); } } #endif } if (i != N-1) { SSL_free (ssl); SSL_free (ssl_client); } } double elapsed = now() - start; printf("%.2fs %.1f handshakes/s\n", elapsed, N / elapsed); printf("client %.3f %.1f\n", tc.seconds(), N / tc.seconds()); printf("server %.3f %.1f\n", ts.seconds(), N / ts.seconds()); printf("server/client %.2f\n", ts.seconds() / tc.seconds()); double start2 = now(); const int M = 1000; char buf[1024] = { 0 }; for (int i = 0; i < M*1024; ++i) { int nw = SSL_write(ssl_client, buf, sizeof buf); if (nw != sizeof buf) { printf("nw = %d\n", nw); } int nr = SSL_read(ssl, buf, sizeof buf); if (nr != sizeof buf) { printf("nr = %d\n", nr); } } elapsed = now() - start2; printf("%.2f %.1f MiB/s\n", elapsed, M / elapsed); SSL_free (ssl); SSL_free (ssl_client); SSL_CTX_free (ctx); SSL_CTX_free (ctx_client); } <file_sep>/algorithm/combination.cc #include <assert.h> #include <algorithm> #include <iostream> #include <iterator> #include <vector> int main() { int values[] = { 1, 2, 3, 4, 5, 6, 7 }; int elements[] = { 1, 1, 1, 0, 0, 0, 0 }; const size_t N = sizeof(elements)/sizeof(elements[0]); assert(N == sizeof(values)/sizeof(values[0])); std::vector<int> selectors(elements, elements + N); int count = 0; do { std::cout << ++count << ": "; for (size_t i = 0; i < selectors.size(); ++i) { if (selectors[i]) { std::cout << values[i] << ", "; } } std::cout << std::endl; } while (prev_permutation(selectors.begin(), selectors.end())); } <file_sep>/topk/sender.cc #include <muduo/base/Logging.h> #include <muduo/net/EventLoop.h> #include <muduo/net/TcpServer.h> #include <fstream> #include <vector> #include <stdio.h> #define __STDC_FORMAT_MACROS #include <inttypes.h> using namespace muduo; using namespace muduo::net; typedef std::vector<std::pair<int64_t, string> > WordCountList; WordCountList g_wordCounts; void read(const char* file) { std::ifstream in(file); std::string line; while (getline(in, line)) { size_t tab = line.find('\t'); if (tab != string::npos) { int64_t count = strtoll(line.c_str() + tab, NULL, 10); if (count > 0) { string word(line.begin(), line.begin()+tab); g_wordCounts.push_back(make_pair(count, word)); } } } std::sort(g_wordCounts.begin(), g_wordCounts.end(), std::greater<WordCountList::value_type>()); } WordCountList::iterator fillBuffer(WordCountList::iterator first, Buffer* buf) { while (first != g_wordCounts.end()) { char count[32]; snprintf(count, sizeof count, "%" PRId64 "\t", first->first); buf->append(count); buf->append(first->second); buf->append("\n", 1); ++first; if (buf->readableBytes() > 65536) { break; } } return first; } void send(const TcpConnectionPtr& conn, WordCountList::iterator first) { Buffer buf; WordCountList::iterator last = fillBuffer(first, &buf); conn->setContext(last); conn->send(&buf); } void onConnection(const TcpConnectionPtr& conn) { LOG_INFO << "Sender - " << conn->peerAddress().toIpPort() << " -> " << conn->localAddress().toIpPort() << " is " << (conn->connected() ? "UP" : "DOWN"); if (conn->connected()) { send(conn, g_wordCounts.begin()); } } void onWriteComplete(const TcpConnectionPtr& conn) { WordCountList::iterator first = boost::any_cast<WordCountList::iterator>(conn->getContext()); if (first != g_wordCounts.end()) { send(conn, first); } else { conn->shutdown(); LOG_INFO << "Sender - done"; } } void serve(uint16_t port) { LOG_INFO << "Listen on port " << port; EventLoop loop; InetAddress listenAddr(port); TcpServer server(&loop, listenAddr, "Sender"); server.setConnectionCallback(onConnection); server.setWriteCompleteCallback(onWriteComplete); server.start(); loop.loop(); } int main(int argc, char* argv[]) { if (argc > 1) { read(argv[1]); int port = argc > 2 ? atoi(argv[2]) : 2013; serve(static_cast<uint16_t>(port)); } else { fprintf(stderr, "Usage: %s shard_file [port]\n", argv[0]); } } <file_sep>/puzzle/poker/poker2.py #!/usr/bin/python import sys def get_ranks(hand): ranks = ['--23456789TJQKA'.index(r) for r, s in hand] ranks.sort(reverse = True) if ranks == [14, 5, 4, 3, 2]: ranks = [5, 4, 3, 2, 1] return ranks def expand(counts, ranks): cards = [] for i in range(len(counts)): cards.extend((ranks[i], ) * counts[i]) return cards def score2(hand): assert len(hand) == 5 cards = get_ranks(hand) assert len(cards) == len(hand) groups = [(cards.count(x), x) for x in set(cards)] groups.sort(reverse = True) counts, ranks = zip(*groups) cards = expand(counts, ranks) assert sum(counts) == len(hand) assert len(set(ranks)) == len(ranks) straight = len(ranks) == 5 and max(ranks) - min(ranks) == 4 suits = [s for r, s in hand] flush = len(set(suits)) == 1 if (5, ) == counts: score = 9 elif straight and flush: score = 8 elif (4, 1) == counts: score = 7 elif (3, 2) == counts: score = 6 elif flush: score = 5 elif straight: score = 4 elif (3, 1, 1) == counts: score = 3 elif (2, 2, 1) == counts: score = 2 elif (2, 1, 1, 1) == counts: score = 1 else: score = 0 return score, cards if __name__ == '__main__': hand = sys.argv[1:] print score2(hand) <file_sep>/digest/build.sh #!/bin/sh set -x g++ DigestOOP.cc test_oop.cc -std=c++17 -lcrypto -o oop g++ DigestOOP2.cc test_oop.cc -std=c++17 -lcrypto -o oop2 g++ DigestTMP.cc test_oop.cc -std=c++17 -lcrypto -o tmp g++ test_evp.cc -std=c++17 -lcrypto -o evp g++ test_evp2.cc -std=c++17 -lcrypto -o evp2 g++ bench.cc DigestOOP.cc -std=c++17 -lbenchmark -lpthread -lcrypto -O2 -o bench <file_sep>/esort/sort00.cc // version 00: half of speed of sort(1), only be able to sort 1GB file #include <boost/noncopyable.hpp> #include <datetime/Timestamp.h> #include <algorithm> #include <string> #include <ext/vstring.h> #include <vector> #include <assert.h> #include <stdio.h> #include <sys/resource.h> // typedef std::string string; typedef __gnu_cxx::__sso_string string; using muduo::Timestamp; class InputFile : boost::noncopyable { public: InputFile(const char* filename) : file_(fopen(filename, "rb")) { assert(file_); setbuffer(file_, buffer_, sizeof buffer_); } ~InputFile() { fclose(file_); } bool readLine(string* line) { char buf[256]; if (fgets_unlocked(buf, sizeof buf, file_)) { line->assign(buf); return true; } else { return false; } } int read(char* buf, int size) { return fread_unlocked(buf, 1, size, file_); } private: FILE* file_; char buffer_[64*1024]; }; class OutputFile : boost::noncopyable { public: OutputFile(const char* filename) : file_(fopen(filename, "wb")) { assert(file_); setbuffer(file_, buffer_, sizeof buffer_); } ~OutputFile() { fclose(file_); } void writeLine(const string& line) { if (line.empty()) { fwrite_unlocked("\n", 1, 1, file_); } else if (line[line.size() - 1] == '\n') { fwrite_unlocked(line.c_str(), 1, line.size(), file_); } else { fwrite_unlocked(line.c_str(), 1, line.size(), file_); fwrite_unlocked("\n", 1, 1, file_); } } private: FILE* file_; char buffer_[64*1024]; }; const int kRecordSize = 100; int main(int argc, char* argv[]) { bool kUseReadLine = false; bool kSortDummyData = false; { // set max virtual memory to 3GB. size_t kOneGB = 1024*1024*1024; rlimit rl = { 3.0*kOneGB, 3.0*kOneGB }; setrlimit(RLIMIT_AS, &rl); } std::vector<int> dummyData; if (kSortDummyData) { dummyData.resize(10000000); for (std::vector<int>::iterator it = dummyData.begin(); it != dummyData.end(); ++it) { *it = rand(); } } Timestamp start = Timestamp::now(); std::vector<string> data; // read { InputFile in(argv[1]); string line; int64_t totalSize = 0; data.reserve(10000000); if (kUseReadLine) { while (in.readLine(&line)) { totalSize += line.size(); data.push_back(line); } } else { char buf[kRecordSize]; while (int n = in.read(buf, sizeof buf)) { totalSize += n; line.assign(buf, n); data.push_back(line); } } } Timestamp readDone = Timestamp::now(); printf("%zd\nread %f\n", data.size(), timeDifference(readDone, start)); // sort if (kSortDummyData) { std::sort(dummyData.begin(), dummyData.end()); } else { std::sort(data.begin(), data.end()); } Timestamp sortDone = Timestamp::now(); printf("sort %f\n", timeDifference(sortDone, readDone)); // output { OutputFile out("output"); for (std::vector<string>::iterator it = data.begin(); it != data.end(); ++it) { out.writeLine(*it); } } Timestamp writeDone = Timestamp::now(); printf("write %f\n", timeDifference(writeDone, sortDone)); printf("total %f\n", timeDifference(writeDone, start)); } <file_sep>/reactor/s00/Makefile LIB_SRC = EventLoop.cc BINARIES = test1 test2 all: $(BINARIES) include ../reactor.mk test1: test1.cc test2: test2.cc <file_sep>/utility/Makefile LIBDIR=/usr/local/lib CXXFLAGS=-g -Wall -O2 -pthread #LDFLAGS=-lprotobuf -lz -lpthread -Wl,-rpath -Wl,$(LIBDIR) SRCS=x BINARIES=cwc all: $(BINARIES) cwc: cwc.cc $(BINARIES): g++ $(CXXFLAGS) $(LDFLAGS) $(filter %.cc,$^) -o $@ clean: rm -f $(BINARIES) <file_sep>/thread/test/Thread_bench.cc #include "../Thread.h" #include "../../datetime/Timestamp.h" #include <sys/wait.h> void threadFunc() { printf("pid=%d, tid=%d\n", ::getpid(), muduo::CurrentThread::tid()); sleep(10); } void threadFunc2() { } void forkBench() { sleep(10); muduo::Timestamp start(muduo::Timestamp::now()); int kProcesses = 10*1000; for (int i = 0; i < kProcesses; ++i) { pid_t child = fork(); if (child == 0) { exit(0); } else { waitpid(child, NULL, 0); } } double timeUsed = timeDifference(muduo::Timestamp::now(), start); printf("process creation time used %.3f us\n", timeUsed*1000000/kProcesses); printf("number of created processes %d\n", kProcesses); } int main() { printf("pid=%d, tid=%d\n", ::getpid(), muduo::CurrentThread::tid()); muduo::Thread t1(threadFunc, "Thread 1"); t1.start(); t1.join(); muduo::Timestamp start = muduo::Timestamp::now(); const int kThreads = 100 * 1000; for (int i = 0; i < kThreads; ++i) { muduo::Thread t1(threadFunc2); t1.start(); t1.join(); } muduo::Timestamp end = muduo::Timestamp::now(); double seconds = timeDifference(end, start); printf("created and joined %d threads in %.3f ms, %.3fus per thread.\n", kThreads, 1e3 * seconds, 1e6 * seconds / kThreads); forkBench(); } <file_sep>/sudoku/Makefile CXXFLAGS+=-O2 -ggdb -DDEBUG CXXFLAGS+=-Wall -Wextra all: sudoku sudoku: main.cc neighbor.cc sudoku_basic.cc sudoku_min_arity.cc sudoku_min_arity_cache.cc sudoku_dancing_links.cc g++ -O2 -o $@ $^ <file_sep>/esort/sort04.cc // version 04: pipeline impl to sort large files. // reduce memory usage by replacing std::string with fixed-length char array // larger IO buffer #include <boost/noncopyable.hpp> #include <boost/ptr_container/ptr_vector.hpp> #include <boost/bind.hpp> #include <boost/enable_shared_from_this.hpp> #include <datetime/Timestamp.h> #include <thread/ThreadPool.h> #include <thread/BlockingQueue.h> #include <algorithm> #include <vector> #include <assert.h> #include <stdio.h> #include <sys/resource.h> using muduo::Timestamp; class InputFile : boost::noncopyable { public: InputFile(const char* filename) : file_(fopen(filename, "rb")) { assert(file_); setbuffer(file_, buffer_, sizeof buffer_); // posix_fadvise for initial input // http://lwn.net/Articles/449420/ // http://blog.mikemccandless.com/2010/06/lucene-and-fadvisemadvise.html } ~InputFile() { fclose(file_); } int read(char* buf, int size) { return fread_unlocked(buf, 1, size, file_); } private: FILE* file_; char buffer_[4*1024*1024]; }; const int kRecordSize = 100; const int kKeySize = 10; class OutputFile : boost::noncopyable { public: OutputFile(const char* filename) : file_(fopen(filename, "wb")) { assert(file_); setbuffer(file_, buffer_, sizeof buffer_); // posix_fadvise for final output } ~OutputFile() { // how to use OS buffers sensibly ? // fdatasync(fileno_unlocked(file_)); fclose(file_); } void writeRecord(char (&record)[kRecordSize]) { fwrite_unlocked(record, 1, kRecordSize, file_); } private: FILE* file_; char buffer_[4*1024*1024]; }; const bool kUseReadLine = false; const int kBatchRecords = 10000000; struct Record { char data[kRecordSize]; }; typedef std::vector<Record> Data; void readInput(InputFile& in, Data* data) { int64_t totalSize = 0; data->clear(); data->reserve(kBatchRecords); for (int i = 0; i < kBatchRecords; ++i) { Record record; if (int n = in.read(record.data, sizeof record.data)) { assert (n == kRecordSize); totalSize += n; data->push_back(record); } else { break; } } } struct Key { char key[kKeySize]; int index; Key(const Record& record, int idx) : index(idx) { memcpy(key, record.data, sizeof key); } bool operator<(const Key& rhs) const { return memcmp(key, rhs.key, sizeof key) < 0; } }; void sortWithKeys(const Data& data, std::vector<Key>* keys) { Timestamp start = Timestamp::now(); keys->clear(); keys->reserve(data.size()); for (size_t i = 0; i < data.size(); ++i) { keys->push_back(Key(data[i], i)); } // printf("make keys %f\n", data.size(), timeDifference(Timestamp::now(), start)); std::sort(keys->begin(), keys->end()); } class Task; typedef boost::shared_ptr<Task> TaskPtr; class Task : public boost::enable_shared_from_this<Task> { public: Task(muduo::BlockingQueue<TaskPtr>* queue) : queue_(queue), id_(s_created++), sorted_(false) { assert(muduo::CurrentThread::isMainThread()); printf("Task %d\n", id_); } ~Task() { printf("~Task %d\n", id_); } bool read(InputFile& in) { assert(muduo::CurrentThread::isMainThread()); sorted_ = false; Timestamp startRead = Timestamp::now(); printf("task %d start read %s\n", id_, startRead.toString().c_str()); readInput(in, &data_); Timestamp readDone = Timestamp::now(); printf("task %d read done %s %f %zd \n", id_, readDone.toString().c_str(), timeDifference(readDone, startRead), data_.size()); return !data_.empty(); } void sort() { // assert(!muduo::CurrentThread::isMainThread()); assert(!sorted_); Timestamp startSort = Timestamp::now(); printf("task %d start sort %s\n", id_, startSort.toString().c_str()); sortWithKeys(data_, &keys_); sorted_ = true; Timestamp sortDone = Timestamp::now(); printf("task %d sort done %s %f\n", id_, sortDone.toString().c_str(), timeDifference(sortDone, startSort)); queue_->put(shared_from_this()); } void write(int batch) { assert(muduo::CurrentThread::isMainThread()); assert(sorted_); Timestamp startWrite = Timestamp::now(); printf("task %d start write %s\n", id_, startWrite.toString().c_str()); { char output[256]; snprintf(output, sizeof output, "tmp%d", batch); OutputFile out(output); for (std::vector<Key>::iterator it = keys_.begin(); it != keys_.end(); ++it) { out.writeRecord(data_[it->index].data); } } Timestamp writeDone = Timestamp::now(); printf("task %d write done %s %f\n", id_, writeDone.toString().c_str(), timeDifference(writeDone, startWrite)); } const Data& data() const { return data_; } private: Data data_; std::vector<Key> keys_; muduo::BlockingQueue<TaskPtr>* queue_; int id_; bool sorted_; static int s_created; }; int Task::s_created = 0; int sortSplit(const char* filename) { // read InputFile in(filename); muduo::BlockingQueue<TaskPtr> queue; muduo::ThreadPool threadPool; threadPool.start(2); int active = 0; // initialize { TaskPtr task(new Task(&queue)); if (task->read(in)) { threadPool.run(boost::bind(&Task::sort, task)); active++; } else { return 0; } TaskPtr task2(new Task(&queue)); if (task2->read(in)) { threadPool.run(boost::bind(&Task::sort, task2)); active++; } } int batch = 0; while (active > 0) { TaskPtr task = queue.take(); active--; task->write(batch++); if (task->read(in)) { threadPool.run(boost::bind(&Task::sort, task)); active++; } } return batch; } struct Source { char data[kRecordSize]; InputFile* input; Source(InputFile* in) : input(in) { } bool next() { return input->read(data, sizeof data) == kRecordSize; } bool operator<(const Source& rhs) const { // make_heap to build min-heap, for merging return memcmp(data, rhs.data, kKeySize) > 0; } }; void merge(const int batch) { printf("merge %d files\n", batch); boost::ptr_vector<InputFile> inputs; std::vector<Source> keys; for (int i = 0; i < batch; ++i) { char filename[128]; snprintf(filename, sizeof filename, "tmp%d", i); inputs.push_back(new InputFile(filename)); Source rec(&inputs.back()); if (rec.next()) { keys.push_back(rec); } } OutputFile out("output"); std::make_heap(keys.begin(), keys.end()); while (!keys.empty()) { std::pop_heap(keys.begin(), keys.end()); out.writeRecord(keys.back().data); if (keys.back().next()) { std::push_heap(keys.begin(), keys.end()); } else { keys.pop_back(); } } } int main(int argc, char* argv[]) { bool kKeepIntermediateFiles = false; printf("pid %d\n", getpid()); { // set max virtual memory to 3GB. size_t kOneGB = 1024*1024*1024; rlimit rl = { 3.0*kOneGB, 3.0*kOneGB }; setrlimit(RLIMIT_AS, &rl); } Timestamp start = Timestamp::now(); printf("sortSplit start %s\n", start.toString().c_str()); // sort int batch = sortSplit(argv[1]); Timestamp sortDone = Timestamp::now(); printf("sortSplit done %f\n", timeDifference(sortDone, start)); if (batch == 0) { } else if (batch == 1) { rename("tmp0", "output"); } else { // merge merge(batch); Timestamp mergeDone = Timestamp::now(); printf("mergeSplit %f\n", timeDifference(mergeDone, sortDone)); } if (!kKeepIntermediateFiles) { for (int i = 0; i < batch; ++i) { char tmp[256]; snprintf(tmp, sizeof tmp, "tmp%d", i); unlink(tmp); } } printf("total %f\n", timeDifference(Timestamp::now(), start)); } <file_sep>/digest/DigestEVP2.h #pragma once #include <assert.h> #include <memory> #include <string> #include <openssl/evp.h> namespace evp { class Digest { public: enum Type { SHA1 = 1, SHA256 = 2, SHA512 = 3, MD5 = 5, }; explicit Digest(Type t) : ctx_(EVP_MD_CTX_create()) { const EVP_MD* method = NULL; if (t == MD5) method = EVP_md5(); else if (t == SHA1) method = EVP_sha1(); else if (t == SHA256) method = EVP_sha256(); else if (t == SHA512) method = EVP_sha512(); else assert(0 && "Invalid digest type"); EVP_DigestInit_ex(ctx_, method, NULL /*engine*/); } ~Digest() { if (ctx_) EVP_MD_CTX_destroy(ctx_); } void update(const void* data, int len) { EVP_DigestUpdate(ctx_, data, len); } std::string digest() { unsigned char result[EVP_MAX_MD_SIZE]; unsigned int len = 0; EVP_DigestFinal_ex(ctx_, result, &len); assert(len == length()); return std::string(reinterpret_cast<char*>(result), len); } int length() const { return EVP_MD_CTX_size(ctx_); } const char* name() const { return EVP_MD_name(EVP_MD_CTX_md(ctx_)); } Digest(Digest&& rhs) : ctx_(rhs.ctx_) { rhs.ctx_ = nullptr; } Digest& operator=(Digest&& rhs) { Digest copy(std::move(rhs)); swap(copy); return *this; } void swap(Digest& rhs) { std::swap(ctx_, rhs.ctx_); } private: EVP_MD_CTX* ctx_; Digest(const Digest&) = delete; void operator=(const Digest&) = delete; }; } <file_sep>/python/ttcp.py #!/usr/bin/env python3 from __future__ import absolute_import from __future__ import division from __future__ import print_function import socket, struct, sys, time """ struct SessionMessage { be32 number; be32 length; } __attribute__ ((__packed__)); """ SessionMessage = struct.Struct(">ii") """ struct PayloadMessage { be32 length; char data[0]; }; """ LengthMessage = struct.Struct(">i") def transmit(sock, length, number): sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) print("Length of buffer : %5d\nNumber of buffers: %5d" % (length, number)) total_mb = length * number / 1024.0 / 1024 print("Total MiB : %7.1f " % total_mb) header = LengthMessage.pack(length) # bytearray works for both Python 2 and 3 payload = bytearray((b"0123456789ABCDEF"[i % 16] for i in range(length))) assert len(payload) == length start = time.time() sock.sendall(SessionMessage.pack(number, length)) for x in range(number): sock.sendall(header) sock.sendall(payload) ack = sock.recv(LengthMessage.size, socket.MSG_WAITALL) ack_length, = LengthMessage.unpack(ack) assert ack_length == length duration = time.time() - start print("%.3f seconds, %.3f MiB/s" % (duration, total_mb / duration)) print("%.3f microseconds per message" % (duration * 1e6 / number)) def receive(sock): number, length = SessionMessage.unpack(sock.recv(SessionMessage.size)) print("Length of buffer : %5d\nNumber of buffers: %5d" % (length, number)) total_mb = length * number / 1024.0 / 1024 print("Total MiB : %7.1f " % total_mb) ack = LengthMessage.pack(length) start = time.time() for x in range(number): header = sock.recv(LengthMessage.size, socket.MSG_WAITALL) header_length, = LengthMessage.unpack(header) assert header_length == length payload = sock.recv(length, socket.MSG_WAITALL) assert len(payload) == length sock.sendall(ack) duration = time.time() - start print("%.3f seconds, %.3f MiB/s" % (duration, total_mb / duration)) print("%.3f microseconds per message" % (duration * 1e6 / number)) def main(argv): if len(argv) < 2: print("Transmit: ttcp -t host\nReceive : ttcp -r") return port = 5001 print("SessionMessage.size = %s" % SessionMessage.size) if argv[1] == "-t": # client host = argv[2] # sock = socket.create_connection((host, port)) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) transmit(sock, length=65536, number=8192) else: # server server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(('', port)) server_socket.listen(5) (client_socket, client_address) = server_socket.accept() print("Got client from %s:%s" % client_address) server_socket.close() receive(client_socket) if __name__ == '__main__': main(sys.argv) <file_sep>/digest/bench.cc #include <benchmark/benchmark.h> #include "DigestEVP.h" #include "DigestOOP.h" template <oop::Digest::Type type> static void BM_Digest_OOP(benchmark::State& state) { std::unique_ptr<oop::Digest> digest = oop::Digest::create(type); std::string str(state.range(0), 'x'); for (auto _ : state) { digest->update(str.data(), str.size()); } digest->digest(); state.SetBytesProcessed(str.size() * state.iterations()); } template <oop::Digest::Type type> static void BM_Digest_OOP_short(benchmark::State& state) { std::string str(state.range(0), 'x'); for (auto _ : state) { std::unique_ptr<oop::Digest> digest = oop::Digest::create(type); digest->update(str.data(), str.size()); digest->digest(); } state.SetBytesProcessed(str.size() * state.iterations()); } namespace oop { const Digest::Type MD5 = Digest::MD5; BENCHMARK_TEMPLATE(BM_Digest_OOP, MD5)->Range(1, 16<<10); const Digest::Type SHA1 = Digest::SHA1; BENCHMARK_TEMPLATE(BM_Digest_OOP, SHA1)->Range(1, 16<<10); const Digest::Type SHA256 = Digest::SHA256; BENCHMARK_TEMPLATE(BM_Digest_OOP, SHA256)->Range(1, 16<<10); BENCHMARK_TEMPLATE(BM_Digest_OOP_short, MD5)->Range(1, 16<<10); BENCHMARK_TEMPLATE(BM_Digest_OOP_short, SHA1)->Range(1, 16<<10); BENCHMARK_TEMPLATE(BM_Digest_OOP_short, SHA256)->Range(1, 16<<10); } template <evp::Digest::Type type> static void BM_Digest_EVP(benchmark::State& state) { evp::Digest digest(type); std::string str(state.range(0), 'x'); for (auto _ : state) { digest.update(str.data(), str.size()); } digest.digest(); state.SetBytesProcessed(str.size() * state.iterations()); } template <evp::Digest::Type type> static void BM_Digest_EVP_short(benchmark::State& state) { std::string str(state.range(0), 'x'); for (auto _ : state) { evp::Digest digest(type); digest.update(str.data(), str.size()); digest.digest(); } state.SetBytesProcessed(str.size() * state.iterations()); } namespace evp { const Digest::Type MD5 = Digest::MD5; BENCHMARK_TEMPLATE(BM_Digest_EVP, MD5)->Range(1, 16<<10); const Digest::Type SHA1 = Digest::SHA1; BENCHMARK_TEMPLATE(BM_Digest_EVP, SHA1)->Range(1, 16<<10); const Digest::Type SHA256 = Digest::SHA256; BENCHMARK_TEMPLATE(BM_Digest_EVP, SHA256)->Range(1, 16<<10); BENCHMARK_TEMPLATE(BM_Digest_EVP_short, MD5)->Range(1, 16<<10); BENCHMARK_TEMPLATE(BM_Digest_EVP_short, SHA1)->Range(1, 16<<10); BENCHMARK_TEMPLATE(BM_Digest_EVP_short, SHA256)->Range(1, 16<<10); } BENCHMARK_MAIN(); <file_sep>/ssl/loop-polarssl.cc /* * Remember to turn off CPU frequency scaling before testing. */ #include <polarssl/ctr_drbg.h> #include <polarssl/error.h> #include <polarssl/entropy.h> #include <polarssl/ssl.h> #include <polarssl/certs.h> #include <muduo/base/Thread.h> #include <boost/bind.hpp> #include <stdio.h> #include <sys/socket.h> #include <sys/time.h> bool useRSA = false; bool useECDHE = false; const int N = 500; double now() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec / 1000000.0; } // FIXME: net_recv with buffer void clientThread(entropy_context* entropy, int* clientFd) { ctr_drbg_context ctr_drbg; ctr_drbg_init(&ctr_drbg, entropy_func, entropy, NULL, 0); ssl_context ssl; bzero(&ssl, sizeof ssl); ssl_init(&ssl); ssl_set_rng(&ssl, ctr_drbg_random, &ctr_drbg); ssl_set_bio(&ssl, &net_recv, clientFd, &net_send, clientFd); ssl_set_endpoint(&ssl, SSL_IS_CLIENT); ssl_set_authmode(&ssl, SSL_VERIFY_NONE); for (int i = 0; i < N; ++i) { ssl_session_reset( &ssl ); int ret = 0; while ( (ret = ssl_handshake(&ssl)) != 0) { if (ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE) { printf("client handshake failed %d\n", ret); break; } } if (i == 0) printf("client done %s %s\n", ssl_get_version(&ssl), ssl_get_ciphersuite(&ssl)); } ssl_free(&ssl); } void serverThread(entropy_context* entropy, int* serverFd) { const char* srv_cert = test_srv_crt_ec; const char* srv_key = test_srv_key_ec; if (useRSA) { srv_cert = test_srv_crt; srv_key = test_srv_key; } x509_crt cert; x509_crt_init(&cert); x509_crt_parse(&cert, reinterpret_cast<const unsigned char*>(srv_cert), strlen(srv_cert)); x509_crt_parse(&cert, reinterpret_cast<const unsigned char*>(test_ca_list), strlen(test_ca_list)); pk_context pkey; pk_init(&pkey); pk_parse_key(&pkey, reinterpret_cast<const unsigned char*>(srv_key), strlen(srv_key), NULL, 0); ctr_drbg_context ctr_drbg; ctr_drbg_init(&ctr_drbg, entropy_func, entropy, NULL, 0); ssl_context ssl_server; bzero(&ssl_server, sizeof ssl_server); ssl_init(&ssl_server); ssl_set_rng(&ssl_server, ctr_drbg_random, &ctr_drbg); ssl_set_bio(&ssl_server, &net_recv, serverFd, &net_send, serverFd); ssl_set_endpoint(&ssl_server, SSL_IS_SERVER); ssl_set_authmode(&ssl_server, SSL_VERIFY_NONE); ssl_set_ca_chain(&ssl_server, cert.next, NULL, NULL); ssl_set_own_cert(&ssl_server, &cert, &pkey); // ssl_set_dbg(&ssl_server, my_debug, (void*)"server"); ecp_group_id curves[] = { POLARSSL_ECP_DP_SECP256R1, POLARSSL_ECP_DP_NONE }; ssl_set_curves(&ssl_server, curves); int ciphersuites[] = { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, 0 }; if (!useECDHE) ssl_set_ciphersuites(&ssl_server, ciphersuites); for (int i = 0; i < N; ++i) { ssl_session_reset(&ssl_server); int ret = 0; while ( (ret = ssl_handshake(&ssl_server)) != 0) { if (ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE) { printf("server handshake failed %d\n", ret); break; } } if (i == 0) printf("server done %s %s\n", ssl_get_version(&ssl_server), ssl_get_ciphersuite(&ssl_server)); } ssl_free(&ssl_server); pk_free(&pkey); x509_crt_free(&cert); } int main(int argc, char* argv[]) { unsigned char buf[16384] = { 0 }; entropy_context entropy; entropy_init(&entropy); if (argc > 1) useRSA = true; useECDHE = argc > 2; int fds[2]; if (::socketpair(AF_UNIX, SOCK_STREAM, 0, fds)) abort(); double start = now(); muduo::Thread client(boost::bind(&clientThread, &entropy, &fds[0]), "ssl client"); muduo::Thread server(boost::bind(&serverThread, &entropy, &fds[1]), "ssl server"); client.start(); server.start(); client.join(); server.join(); double elapsed = now() - start; printf("%.2fs %.1f handshakes/s\n", elapsed, N / elapsed); entropy_free(&entropy); } <file_sep>/java/bankqueue/customer/Customer.java package bankqueue.customer; import bankqueue.Bank; public abstract class Customer { public final int id; public final int serviceTime; protected Customer(int id, int serviceTime) { this.id = id; this.serviceTime = serviceTime; } public String getTypeName() { return getClass().getSimpleName(); } public abstract boolean findSpareWindow(Bank bank); public abstract void gotoWindow(Bank bank); } <file_sep>/algorithm/iprange.cc #include <assert.h> #include <stdint.h> #include <algorithm> #include <vector> struct IPrange { uint32_t startIp; // inclusive uint32_t endIp; // inclusive int value; // >= 0 bool operator<(const IPrange& rhs) const { return startIp < rhs.startIp; } }; // REQUIRE: ranges is sorted. int findIpValue(const std::vector<IPrange>& ranges, uint32_t ip) { int result = -1; if (!ranges.empty()) { IPrange needle = { ip, 0, 0 }; std::vector<IPrange>::const_iterator it = std::lower_bound(ranges.begin(), ranges.end(), needle); if (it == ranges.end()) { --it; } else if (it != ranges.begin() && it->startIp > ip) { --it; } if (it->startIp <= ip && it->endIp >= ip) { result = it->value; } } return result; } bool operator==(const IPrange& lhs, const IPrange& rhs) { return lhs.startIp == rhs.startIp; } int main() { std::vector<IPrange> ranges; IPrange r1 = { 123, 234, 999 }; ranges.push_back(r1); std::sort(ranges.begin(), ranges.end()); assert(std::adjacent_find(ranges.begin(), ranges.end()) == ranges.end()); int v = findIpValue(ranges, 0); assert(v == -1); v = findIpValue(ranges, 122); assert(v == -1); v = findIpValue(ranges, 123); assert(v == 999); v = findIpValue(ranges, 234); assert(v == 999); v = findIpValue(ranges, 235); assert(v == -1); IPrange r2 = { 1000, 2000, 7777 }; ranges.push_back(r2); sort(ranges.begin(), ranges.end()); assert(adjacent_find(ranges.begin(), ranges.end()) == ranges.end()); v = findIpValue(ranges, 0); assert(v == -1); v = findIpValue(ranges, 122); assert(v == -1); v = findIpValue(ranges, 123); assert(v == 999); v = findIpValue(ranges, 234); assert(v == 999); v = findIpValue(ranges, 235); assert(v == -1); v = findIpValue(ranges, 999); assert(v == -1); v = findIpValue(ranges, 1000); assert(v == 7777); v = findIpValue(ranges, 1500); assert(v == 7777); v = findIpValue(ranges, 2000); assert(v == 7777); v = findIpValue(ranges, 2001); assert(v == -1); v = findIpValue(ranges, 1073741824); assert(v == -1); IPrange r3 = { 1073741824U*3, 1073741824U*3+1073741823U, 5555 }; ranges.push_back(r3); v = findIpValue(ranges, 1073741824U*2); assert(v == -1); v = findIpValue(ranges, 1073741824U*3); assert(v == 5555); v = findIpValue(ranges, 1073741824U*3+1073741822U); assert(v == 5555); v = findIpValue(ranges, 1073741824U*3+1073741823U); assert(v == 5555); v = findIpValue(ranges, 1073741824U*3+1073741824U); assert(v == -1); IPrange r4 = { 1073741824U*3+1073741823U, 1073741824U*3+1073741823U, 3333 }; ranges.push_back(r4); v = findIpValue(ranges, 1073741824U*3+1073741822U); assert(v == 5555); v = findIpValue(ranges, 1073741824U*3+1073741823U); assert(v == 3333); } <file_sep>/algorithm/select.cc #include <algorithm> #include <vector> #include <iostream> #include <iterator> #include <assert.h> using namespace std; vector<int> selectBySorting(const vector<int>& input, int k1, int k2) { assert(0 <= k1 && k1 < input.size()); assert(0 <= k2 && k2 < input.size()); assert(k1 <= k2); vector<int> temp(input); sort(temp.begin(), temp.end()); return vector<int>(temp.begin() + k1, temp.begin() + k2 + 1); } vector<int> selectByNthElement(const vector<int>& input, int k1, int k2) { assert(0 <= k1 && k1 < input.size()); assert(0 <= k2 && k2 < input.size()); assert(k1 <= k2); vector<int> temp(input); nth_element(temp.begin(), temp.begin() + k2 + 1, temp.end()); nth_element(temp.begin(), temp.begin() + k1, temp.begin() + k2 + 1); sort(temp.begin() + k1, temp.begin() + k2 + 1); return vector<int>(temp.begin() + k1, temp.begin() + k2 + 1); } vector<int> selectByPartialSort(const vector<int>& input, int k1, int k2) { assert(0 <= k1 && k1 < input.size()); assert(0 <= k2 && k2 < input.size()); assert(k1 <= k2); vector<int> temp(input); nth_element(temp.begin(), temp.begin() + k1, temp.end()); partial_sort(temp.begin() + k1, temp.begin() + k2 + 1, temp.end()); return vector<int>(temp.begin() + k1, temp.begin() + k2 + 1); } void print(const vector<int>& vec) { copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, ", ")); cout << endl; } int main() { vector<int> input; for (int i = 0; i < 100; ++i) { input.push_back(i); } random_shuffle(input.begin(), input.end()); print(input); print(selectBySorting(input, 10, 20)); print(selectByNthElement(input, 10, 20)); print(selectByPartialSort(input, 10, 20)); } <file_sep>/digest/test_evp.cc #include "DigestEVP.h" void print(const std::string& d) { for (int i = 0; i < d.size(); ++i) { printf("%02x", (unsigned char)d[i]); } printf("\n"); } evp::Digest getDefaultDigest() { return evp::Digest(evp::Digest::SHA1); } int main(int argc, char* argv[]) { OpenSSL_add_all_digests(); evp::Digest md5(evp::Digest::MD5); print(md5.digest()); evp::Digest sha1(evp::Digest::SHA1); print(sha1.digest()); evp::Digest sha256(evp::Digest::SHA256); print(sha256.digest()); evp::Digest md = getDefaultDigest(); md.update("hello\n", 6); print(md.digest()); md = getDefaultDigest(); md = std::move(md); EVP_cleanup(); } <file_sep>/sudoku/sudoku_dancing_links.cc #include <assert.h> #include <memory.h> #include <map> #include <vector> #include "sudoku.h" using namespace std; struct Node; typedef Node Column; struct Node { Node* left; Node* right; Node* up; Node* down; Column* col; int name; int size; }; const int kMaxNodes = 1 + 81*4 + 9*9*9*4; const int kMaxColumns = 400; const int kRow = 100, kCol = 200, kBox = 300; struct Dance { Column* root_; int* inout_; Column* columns_[400]; vector<Node*> stack_; Node nodes_[kMaxNodes]; int cur_node_; Column* new_column(int n = 0) { assert(cur_node_ < kMaxNodes); Column* c = &nodes_[cur_node_++]; memset(c, 0, sizeof(Column)); c->left = c; c->right = c; c->up = c; c->down = c; c->col = c; c->name = n; return c; } void append_column(int n) { assert(columns_[n] == NULL); Column* c = new_column(n); put_left(root_, c); columns_[n] = c; } Node* new_row(int col) { assert(columns_[col] != NULL); assert(cur_node_ < kMaxNodes); Node* r = &nodes_[cur_node_++]; //Node* r = new Node; memset(r, 0, sizeof(Node)); r->left = r; r->right = r; r->up = r; r->down = r; r->name = col; r->col = columns_[col]; put_up(r->col, r); return r; } int get_row_col(int row, int val) { return kRow+row*10+val; } int get_col_col(int col, int val) { return kCol+col*10+val; } int get_box_col(int box, int val) { return kBox+box*10+val; } Dance(int inout[81]) : inout_(inout), cur_node_(0) { stack_.reserve(100); root_ = new_column(); root_->left = root_->right = root_; memset(columns_, 0, sizeof(columns_)); bool rows[N][10] = {false}; bool cols[N][10] = {false}; bool boxes[N][10] = {false}; for (int i = 0; i < N; ++i) { int row = i / 9; int col = i % 9; int box = row/3*3 + col/3; int val = inout[i]; rows[row][val] = true; cols[col][val] = true; boxes[box][val] = true; } for (int i = 0; i < N; ++i) { if (inout[i] == 0) { append_column(i); } } for (int i = 0; i < 9; ++i) { for (int v = 1; v < 10; ++v) { if (!rows[i][v]) append_column(get_row_col(i, v)); if (!cols[i][v]) append_column(get_col_col(i, v)); if (!boxes[i][v]) append_column(get_box_col(i, v)); } } for (int i = 0; i < N; ++i) { if (inout[i] == 0) { int row = i / 9; int col = i % 9; int box = row/3*3 + col/3; //int val = inout[i]; for (int v = 1; v < 10; ++v) { if (!(rows[row][v] || cols[col][v] || boxes[box][v])) { Node* n0 = new_row(i); Node* nr = new_row(get_row_col(row, v)); Node* nc = new_row(get_col_col(col, v)); Node* nb = new_row(get_box_col(box, v)); put_left(n0, nr); put_left(n0, nc); put_left(n0, nb); } } } } } Column* get_min_column() { Column* c = root_->right; int min_size = c->size; if (min_size > 1) { for (Column* cc = c->right; cc != root_; cc = cc->right) { if (min_size > cc->size) { c = cc; min_size = cc->size; if (min_size <= 1) break; } } } return c; } void cover(Column* c) { c->right->left = c->left; c->left->right = c->right; for (Node* row = c->down; row != c; row = row->down) { for (Node* j = row->right; j != row; j = j->right) { j->down->up = j->up; j->up->down = j->down; j->col->size--; } } } void uncover(Column* c) { for (Node* row = c->up; row != c; row = row->up) { for (Node* j = row->left; j != row; j = j->left) { j->col->size++; j->down->up = j; j->up->down = j; } } c->right->left = c; c->left->right = c; } bool solve() { if (root_->left == root_) { for (size_t i = 0; i < stack_.size(); ++i) { Node* n = stack_[i]; int cell = -1; int val = -1; while (cell == -1 || val == -1) { if (n->name < 100) cell = n->name; else val = n->name % 10; n = n->right; } //assert(cell != -1 && val != -1); inout_[cell] = val; } return true; } Column* const col = get_min_column(); cover(col); for (Node* row = col->down; row != col; row = row->down) { stack_.push_back(row); for (Node* j = row->right; j != row; j = j->right) { cover(j->col); } if (solve()) { return true; } stack_.pop_back(); for (Node* j = row->left; j != row; j = j->left) { uncover(j->col); } } uncover(col); return false; } void put_left(Column* old, Column* nnew) { nnew->left = old->left; nnew->right = old; old->left->right = nnew; old->left = nnew; } void put_up(Column* old, Node* nnew) { nnew->up = old->up; nnew->down = old; old->up->down = nnew; old->up = nnew; old->size++; nnew->col = old; } }; bool solve_sudoku_dancing_links(int unused) { Dance d(board); return d.solve(); } <file_sep>/tpc/lib/InetAddress.cc #include "InetAddress.h" #include <memory> #include <assert.h> #include <arpa/inet.h> #include <netdb.h> static_assert(sizeof(InetAddress) == sizeof(struct sockaddr_in6), "InetAddress is same size as sockaddr_in6"); #ifdef __linux static_assert(offsetof(sockaddr_in, sin_family) == 0, "sin_family offset 0"); static_assert(offsetof(sockaddr_in6, sin6_family) == 0, "sin6_family offset 0"); #endif static_assert(offsetof(sockaddr_in, sin_family) == offsetof(sockaddr_in6, sin6_family), "sin_family/sin6_family offset"); static_assert(offsetof(sockaddr_in, sin_port) == 2, "sin_port offset 2"); static_assert(offsetof(sockaddr_in6, sin6_port) == 2, "sin6_port offset 2"); InetAddress::InetAddress(StringArg ip, uint16_t port) { setPort(port); int result = 0; if (strchr(ip.c_str(), ':') == NULL) { result = ::inet_pton(AF_INET, ip.c_str(), &addr_.sin_addr); addr_.sin_family = AF_INET; } else { result = ::inet_pton(AF_INET6, ip.c_str(), &addr6_.sin6_addr); addr6_.sin6_family = AF_INET6; } assert(result == 1 && "Invalid IP format"); } InetAddress::InetAddress(uint16_t port, bool ipv6) { static_assert(offsetof(InetAddress, addr6_) == 0, "addr6_ offset 0"); static_assert(offsetof(InetAddress, addr_) == 0, "addr_ offset 0"); bool loopbackOnly = false; if (ipv6) { memZero(&addr6_, sizeof addr6_); addr6_.sin6_family = AF_INET6; in6_addr ip = loopbackOnly ? in6addr_loopback : in6addr_any; addr6_.sin6_addr = ip; addr6_.sin6_port = htons(port); } else { memZero(&addr_, sizeof addr_); addr_.sin_family = AF_INET; in_addr_t ip = loopbackOnly ? INADDR_LOOPBACK : INADDR_ANY; addr_.sin_addr.s_addr = htonl(ip); addr_.sin_port = htons(port); } } InetAddress::InetAddress(const struct sockaddr& saddr) { if (saddr.sa_family == AF_INET) { memcpy(&addr_, &saddr, sizeof addr_); } else if (saddr.sa_family == AF_INET6) { memcpy(&addr6_, &saddr, sizeof addr6_); } else { assert(false); } } std::string InetAddress::toIp() const { char buf[64] = ""; static_assert(sizeof buf >= INET_ADDRSTRLEN); static_assert(sizeof buf >= INET6_ADDRSTRLEN); if (family() == AF_INET) { ::inet_ntop(AF_INET, &addr_.sin_addr, buf, static_cast<socklen_t>(sizeof buf)); } else if (family() == AF_INET6) { ::inet_ntop(AF_INET6, &addr6_.sin6_addr, buf, static_cast<socklen_t>(sizeof buf)); } return buf; } std::string InetAddress::toIpPort() const { char buf[32] = ""; snprintf(buf, sizeof buf, ":%u", port()); if (family() == AF_INET6) return "[" + toIp() + "]" + buf; return toIp() + buf; } bool InetAddress::operator==(const InetAddress& rhs) const { if (family() == rhs.family()) { if (family() == AF_INET) { return addr_.sin_port == rhs.addr_.sin_port && addr_.sin_addr.s_addr == rhs.addr_.sin_addr.s_addr; } else if (family() == AF_INET6) { return addr6_.sin6_port == rhs.addr6_.sin6_port && memcmp(&addr6_.sin6_addr, &rhs.addr6_.sin6_addr, sizeof addr6_.sin6_addr) == 0; } } return false; } // static bool InetAddress::resolve(StringArg hostname, uint16_t port, InetAddress* out) { assert(out); std::vector<InetAddress> addrs = resolveAll(hostname, port); if (addrs.empty()) return false; // Read the first result *out = addrs[0]; return true; } // static std::vector<InetAddress> InetAddress::resolveAll(StringArg hostname, uint16_t port) { std::vector<InetAddress> addrs; struct addrinfo* result = NULL; int error = getaddrinfo(hostname.c_str(), NULL, NULL, &result); if (error != 0) { if (error == EAI_SYSTEM) { perror("InetAddress::resolve"); } else { fprintf(stderr, "InetAddress::resolve: %s\n", gai_strerror(error)); } return addrs; } assert(result); std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> freeResult(result, freeaddrinfo); for (struct addrinfo* ai = result; ai != NULL; ai = ai->ai_next) { InetAddress addr(*ai->ai_addr); addr.setPort(port); addrs.push_back(addr); } return addrs; } <file_sep>/algorithm/mergeN.cc #include <algorithm> #include <iostream> #include <iterator> #include <vector> typedef int Record; typedef std::vector<Record> File; struct Input { Record value; size_t index; const File* file; explicit Input(const File* f) : value(-1), index(0), file(f) { } bool next() { if (index < file->size()) { value = (*file)[index]; ++index; return true; } else { return false; } } bool operator<(const Input& rhs) const { // make_heap to build min-heap, for merging return value > rhs.value; } }; File mergeN(const std::vector<File>& files) { File output; std::vector<Input> inputs; for (size_t i = 0; i < files.size(); ++i) { Input input(&files[i]); if (input.next()) { inputs.push_back(input); } } std::make_heap(inputs.begin(), inputs.end()); while (!inputs.empty()) { std::pop_heap(inputs.begin(), inputs.end()); output.push_back(inputs.back().value); if (inputs.back().next()) { std::push_heap(inputs.begin(), inputs.end()); } else { inputs.pop_back(); } } return output; } int main() { const int kFiles = 32; std::vector<File> files(kFiles); for (int i = 0; i < kFiles; ++i) { File file(rand() % 1000); std::generate(file.begin(), file.end(), &rand); std::sort(file.begin(), file.end()); files[i].swap(file); } File output = mergeN(files); std::copy(output.begin(), output.end(), std::ostream_iterator<Record>(std::cout, "\n")); } <file_sep>/string/StringEager.h // excerpts from http://code.google.com/p/muduo/ // // Use of this source code is governed by a BSD-style license // that can be found in the License file. // // Author: <NAME> (giantchen at gmail dot com) #ifndef MUDUO_BASE_STRINGEAGER_H #define MUDUO_BASE_STRINGEAGER_H #include <stddef.h> // size_t #include <stdint.h> // uint32_t // #include <boost/operators.hpp> namespace muduo { /** * Eager copy string. * * similiar data structure of vector<char> * sizeof() == 12 on 32-bit * sizeof() == 16 on 64-bit * max_size() == 1GB, on both 32-bit & 64-bit * */ class StringEager // : copyable // public boost::less_than_comparable<StringEager>, // public boost::less_than_comparable<StringEager, const char*>, // public boost::equality_comparable<StringEager>, // public boost::equality_comparable<StringEager, const char*>, // public boost::addable<StringEager>, // public boost::addable<StringEager, const char*> { public: typedef char value_type; typedef uint32_t size_type; typedef int32_t difference_type; typedef value_type& reference; typedef const char& const_reference; typedef value_type* pointer; typedef const char* const_pointer; typedef pointer iterator; typedef const_pointer const_iterator; static const size_type npos = static_cast<size_type>(-1); const_pointer c_str() const { return start_; } const_pointer data() const { return start_; } iterator begin() { return start_; } const_iterator begin() const { return start_; } const_iterator cbegin() const { return start_; } iterator end() { return start_ + size_; } const_iterator end() const { return start_ + size_; } const_iterator cend() const { return start_ + size_; } size_type size() const { return size_; } size_type length() const { return size_; } size_type capacity() const { return capacity_; } size_type max_size() const { return 1 << 30; } bool empty() const { return size_ == 0; } // // copy control // StringEager() : start_(kEmpty_), size_(0), capacity_(0) { } StringEager(const StringEager&); StringEager& operator=(const StringEager&); #ifdef __GXX_EXPERIMENTAL_CXX0X__ StringEager(StringEager&&); StringEager& operator=(StringEager&&); #endif ~StringEager() { if (start_ != kEmpty_) { delete[] start_; } } // // C-style string constructors & assignments // StringEager(const char* str); StringEager(const char* str, size_t); StringEager& operator=(const char*); // // operators // bool operator<(const StringEager&) const; bool operator<(const char*) const; bool operator==(const StringEager&) const; bool operator==(const char*) const; StringEager& operator+=(const StringEager&); StringEager& operator+=(const char*); // // member functions, not conform to the standard // void push_back(char c); void append(const char* str); void append(const char* str, size_t); void assign(const char* str, size_t); // FIXME: more void reserve(size_type); void clear() throw(); void swap(StringEager& rhs) throw(); private: struct NoAlloc { }; void init(const char* str); StringEager(char* str, uint32_t, uint32_t, NoAlloc); void expandAndAppend(const char* str, size_t len); uint32_t nextCapacity(uint32_t) const; bool equals(const char* str, size_t len) const; bool lessThan(const char* str, size_t len) const; char* start_; size_type size_; size_type capacity_; static char kEmpty_[1]; static const size_type kMinCapacity_ = 15; }; template<typename Stream> Stream& operator<<(Stream&, const StringEager&); } #endif // MUDUO_BASE_STRINGEAGER_H <file_sep>/thread/test/Factory_racecondition.cc // reproduce race condition of Factory.cc if compiled with -DREPRODUCE_BUG #include "../Mutex.h" #include <boost/noncopyable.hpp> #include <memory> #include <unordered_map> #include <assert.h> #include <stdio.h> #include <unistd.h> using std::string; void sleepMs(int ms) { usleep(ms * 1000); } class Stock : boost::noncopyable { public: Stock(const string& name) : name_(name) { printf("%s: Stock[%p] %s\n", muduo::CurrentThread::name(), this, name_.c_str()); } ~Stock() { printf("%s: ~Stock[%p] %s\n", muduo::CurrentThread::name(), this, name_.c_str()); } const string& key() const { return name_; } private: string name_; }; class StockFactory : boost::noncopyable { public: std::shared_ptr<Stock> get(const string& key) { std::shared_ptr<Stock> pStock; muduo::MutexLockGuard lock(mutex_); std::weak_ptr<Stock>& wkStock = stocks_[key]; pStock = wkStock.lock(); if (!pStock) { pStock.reset(new Stock(key), [this] (Stock* stock) { deleteStock(stock); }); wkStock = pStock; } return pStock; } private: void deleteStock(Stock* stock) { printf("%s: deleteStock[%p]\n", muduo::CurrentThread::name(), stock); if (stock) { sleepMs(500); muduo::MutexLockGuard lock(mutex_); #ifdef REPRODUCE_BUG printf("%s: erase %zd\n", muduo::CurrentThread::name(), stocks_.erase(stock->key())); #else auto it = stocks_.find(stock->key()); assert(it != stocks_.end()); if (it->second.expired()) { stocks_.erase(it); } else { printf("%s: %s is not expired\n", muduo::CurrentThread::name(), stock->key().c_str()); } #endif } delete stock; // sorry, I lied } mutable muduo::MutexLock mutex_; std::unordered_map<string, std::weak_ptr<Stock> > stocks_; }; void threadB(StockFactory* factory) { sleepMs(250); auto stock = factory->get("MS"); printf("%s: stock %p\n", muduo::CurrentThread::name(), stock.get()); sleepMs(500); auto stock2 = factory->get("MS"); printf("%s: stock2 %p\n", muduo::CurrentThread::name(), stock2.get()); if (stock != stock2) { printf("WARNING: stock != stock2\n"); } } int main() { StockFactory factory; muduo::Thread thr([&factory] { threadB(&factory); }, "thrB"); thr.start(); { auto stock = factory.get("MS"); printf("%s: stock %p\n", muduo::CurrentThread::name(), stock.get()); } thr.join(); } <file_sep>/string/StringEager.cc #include "StringEager.h" #include <assert.h> #include <string.h> #include <algorithm> char muduo::StringEager::kEmpty_[] = ""; const uint32_t muduo::StringEager::kMinCapacity_; using namespace muduo; StringEager::StringEager(const StringEager& rhs) : start_(kEmpty_), size_(rhs.size_), capacity_(0) { init(rhs.start_); } StringEager& StringEager::operator=(const StringEager& rhs) { // shrink is not good // StringEager tmp(rhs); // swap(tmp); // if (this != &rhs) assign(rhs.start_, rhs.size_); return *this; } #ifdef __GXX_EXPERIMENTAL_CXX0X__ StringEager::StringEager(StringEager&& rhs) : start_(rhs.start_), size_(rhs.size_), capacity_(rhs.capacity_) { rhs.start_ = NULL; } StringEager& StringEager::operator=(StringEager&& rhs) { swap(rhs); return *this; } #endif StringEager::StringEager(const char* str) : start_(kEmpty_), size_(::strlen(str)), capacity_(0) { init(str); } StringEager::StringEager(const char* str, size_t len) : start_(kEmpty_), size_(len), capacity_(0) { init(str); } StringEager& StringEager::operator=(const char* str) { assign(str, ::strlen(str)); return *this; } StringEager::StringEager(char* str, uint32_t sz, uint32_t cap, NoAlloc) : start_(str), size_(sz), capacity_(cap) { } void StringEager::init(const char* str) { if (size_ > 0) { capacity_ = std::max(size_, kMinCapacity_); start_ = new char[capacity_+1]; ::memcpy(start_, str, size_+1); } } bool StringEager::operator<(const StringEager& rhs) const { return lessThan(rhs.start_, rhs.size_); } bool StringEager::operator<(const char* str) const { return lessThan(str, ::strlen(str)); } bool StringEager::operator==(const StringEager& rhs) const { return this == &rhs || equals(rhs.start_, rhs.size_); } bool StringEager::operator==(const char* str) const { return equals(str, ::strlen(str)); } void StringEager::reserve(size_type len) { if (len > capacity_) { const uint32_t newCap = nextCapacity(len); char* newStart = new char[newCap+1]; ::memcpy(newStart, start_, size_); newStart[size_] = '\0'; StringEager tmp(newStart, size_, newCap, NoAlloc()); swap(tmp); } } void StringEager::clear() throw() { size_ = 0; start_[size_] = '\0'; } void StringEager::swap(StringEager& rhs) throw() { std::swap(start_, rhs.start_); std::swap(size_, rhs.size_); std::swap(capacity_, rhs.capacity_); } void StringEager::assign(const char* str, size_t len) { if (capacity_ >= len) { ::memmove(start_, str, len); size_ = len; start_[size_] = '\0'; } else { clear(); expandAndAppend(str, len); } } void StringEager::push_back(char c) { if (capacity_ >= size_+1) { start_[size_] = c; start_[size_+1] = '\0'; ++size_; } else { expandAndAppend(&c, 1); } } void StringEager::append(const char* str) { append(str, ::strlen(str)); } void StringEager::append(const char* str, size_t len) { if (capacity_ >= size_ + len) { ::memcpy(start_+size_, str, len); size_ += len; start_[size_] = '\0'; } else { expandAndAppend(str, len); } } void StringEager::expandAndAppend(const char* str, size_t len) { const uint32_t newSize = size_+len; const uint32_t newCap = nextCapacity(newSize); char* newStart = new char[newCap+1]; ::memcpy(newStart, start_, size_); ::memcpy(newStart+size_, str, len); newStart[newSize] = '\0'; StringEager tmp(newStart, newSize, newCap, NoAlloc()); swap(tmp); } uint32_t StringEager::nextCapacity(uint32_t newSize) const { uint32_t newCap = std::max(2*capacity_, newSize); return std::max(newCap, kMinCapacity_); } bool StringEager::equals(const char* str, size_t len) const { return size_ == len && ::memcmp(start_, str, size_) == 0; } bool StringEager::lessThan(const char* str, size_t strsize) const { // std::lexicographical_compare uint32_t size = std::min(size_, static_cast<size_type>(strsize)); int result = ::memcmp(start_, str, size); return result == 0 ? (size_ < strsize) : (result < 0); } <file_sep>/reactor/s02/Makefile LIB_SRC = Channel.cc EventLoop.cc Poller.cc Timer.cc TimerQueue.cc BINARIES = test1 test2 test3 test4 all: $(BINARIES) include ../reactor.mk test1: test1.cc test2: test2.cc test3: test3.cc test4: test4.cc <file_sep>/topk/word_freq_sort_basic.cc /* sort word by frequency, sorting version. 1. read input files, sort every 1GB to segment files word \t count -- sorted by word 2. read all segment files, do merging & counting, when count map > 10M keys, output to count files, each word goes to one count file only. count \t word -- sorted by count 3. read all count files, do merging and output */ #include "file.h" #include "input.h" #include "merge.h" #include "timer.h" #include "muduo/base/Logging.h" #include <assert.h> #include <algorithm> #include <fstream> #include <iostream> #include <map> #include <memory> #include <string> #include <unordered_map> #include <vector> #include <fcntl.h> #include <string.h> #include <sys/stat.h> #include <sys/time.h> #include <unistd.h> using std::pair; using std::string; using std::string_view; using std::vector; const size_t kMaxSize = 10 * 1000 * 1000; bool g_verbose = false, g_keep = false; const char* segment_dir = "."; const char* g_output = "output"; inline double now() { struct timeval tv = { 0, 0 }; gettimeofday(&tv, nullptr); return tv.tv_sec + tv.tv_usec / 1000000.0; } int64_t sort_segments(int* count, int fd) { Timer timer; const int64_t file_size = lseek(fd, 0, SEEK_END); lseek(fd, 0, SEEK_SET); if (g_verbose) printf(" file size %ld\n", file_size); int64_t offset = 0; while (offset < file_size) { double t = now(); const int64_t len = std::min(file_size - offset, 1024 * 1000 * 1000L); if (g_verbose) printf(" reading segment %d: offset %ld len %ld", *count, offset, len); std::unique_ptr<char[]> buf(new char[len]); const ssize_t nr = ::pread(fd, buf.get(), len, offset); double sec = now() - t; if (g_verbose) printf(" %.3f sec %.3f MB/s\n", sec, nr / sec / 1000 / 1000); // TODO: move to another thread t = now(); const char* const start = buf.get(); const char* const end = start + nr; vector<string_view> items; const char* p = start; while (p < end) { const char* nl = static_cast<const char*>(memchr(p, '\n', end - p)); if (nl) { string_view s(p, nl - p); items.push_back(s); p = nl + 1; } else { break; } } offset += p - start; if (g_verbose) printf(" parse %.3f sec %ld items %ld bytes\n", now() - t, items.size(), p - start); t = now(); std::sort(items.begin(), items.end()); if (g_verbose) printf(" sort %.3f sec\n", now() - t); t = now(); char name[256]; snprintf(name, sizeof name, "%s/segment-%05d", segment_dir, *count); ++*count; int unique = 0; { // TODO: replace with OutputFile std::ofstream out(name); string_view curr; int cnt = 0; for (auto it = items.begin(); it != items.end(); ++it) { if (*it != curr) { if (cnt) { out << curr << '\t' << cnt << '\n'; ++unique; } curr = *it; cnt = 1; } else ++cnt; } if (cnt) { out << curr << '\t' << cnt << '\n'; ++unique; } } if (g_verbose) printf(" unique %.3f sec %d\n", now() - t, unique); LOG_INFO << " wrote " << name; } LOG_INFO << " file done " << timer.report(file_size); return file_size; } int input(int argc, char* argv[], int64_t* total_in = nullptr) { int count = 0; int64_t total = 0; Timer timer; for (int i = optind; i < argc; ++i) { LOG_INFO << "Reading input file " << argv[i]; int fd = open(argv[i], O_RDONLY); if (fd >= 0) { total += sort_segments(&count, fd); ::close(fd); } else perror("open"); } LOG_INFO << "Reading done " << count << " segments " << timer.report(total); if (total_in) *total_in = total; return count; } // ======= combine ======= class Segment // copyable { public: string_view word; explicit Segment(SegmentInput* in) : in_(in) { } bool next() { if (in_->next()) { word = in_->current_word(); return true; } else return false; } bool operator<(const Segment& rhs) const { return word > rhs.word; } int64_t count() const { return in_->current_count(); } private: SegmentInput* in_; }; class CountOutput { public: CountOutput(); void add(string_view word, int64_t count) { if (block_->add(word, count)) { } else { // TODO: Move to another thread. block_->output(merge_count_); ++merge_count_; block_.reset(new Block); if (!block_->add(word, count)) { abort(); } } } int finish() { block_->output(merge_count_); ++merge_count_; return merge_count_; } private: struct Count { int64_t count = 0; int32_t offset = 0, len = 0; }; struct Block { std::unique_ptr<char[]> data { new char[kSize] }; vector<Count> counts; int start = 0; static const int kSize = 512 * 1000 * 1000; bool add(string_view word, int64_t count) { if (static_cast<size_t>(kSize - start) >= word.size()) { memcpy(data.get() + start, word.data(), word.size()); Count c; c.count = count; c.offset = start; c.len = word.size(); counts.push_back(c); start += word.size(); return true; } else return false; } void output(int n) { Timer t; char buf[256]; snprintf(buf, sizeof buf, "count-%05d", n); LOG_INFO << " writing " << buf << " of " << counts.size() << " words"; std::sort(counts.begin(), counts.end(), [](const auto& lhs, const auto& rhs) { return lhs.count > rhs.count; }); int64_t file_size = 0; { OutputFile out(buf); for (const auto& c : counts) { out.writeWord(c.count, string_view(data.get() + c.offset, c.len)); } file_size = out.tell(); } LOG_DEBUG << " done " << t.report(file_size); } }; std::unique_ptr<Block> block_; int merge_count_ = 0; }; CountOutput::CountOutput() : block_(new Block) { } int combine(int count) { Timer timer; std::vector<std::unique_ptr<SegmentInput>> inputs; std::vector<Segment> keys; int64_t total = 0; for (int i = 0; i < count; ++i) { char buf[256]; snprintf(buf, sizeof buf, "%s/segment-%05d", segment_dir, i); struct stat st; if (::stat(buf, &st) == 0) { total += st.st_size; inputs.emplace_back(new SegmentInput(buf)); Segment rec(inputs.back().get()); if (rec.next()) { keys.push_back(rec); } if (!g_keep) ::unlink(buf); } else { perror("Cannot open segment"); } } LOG_INFO << "Combining " << count << " files " << total << " bytes"; // std::cout << keys.size() << '\n'; string last = "<NAME>"; int64_t last_count = 0, total_count = 0; int64_t lines_in = 0, lines_out = 0; CountOutput out; std::make_heap(keys.begin(), keys.end()); while (!keys.empty()) { std::pop_heap(keys.begin(), keys.end()); lines_in++; total_count += keys.back().count(); if (keys.back().word != last) { if (last_count > 0) { assert(last > keys.back().word); lines_out++; out.add(last, last_count); } last = keys.back().word; last_count = keys.back().count(); } else { last_count += keys.back().count(); } if (keys.back().next()) { std::push_heap(keys.begin(), keys.end()); } else { keys.pop_back(); } } if (last_count > 0) { lines_out++; out.add(last, last_count); } int m = out.finish(); LOG_INFO << "total count " << total_count << ", lines in " << lines_in << " out " << lines_out; LOG_INFO << "Combine done " << timer.report(total); return m; } int main(int argc, char* argv[]) { setlocale(LC_NUMERIC, ""); int opt; bool sort_only = false; int count_only = 0; int merge_only = 0; while ((opt = getopt(argc, argv, "c:d:km:o:sv")) != -1) { switch (opt) { case 'c': count_only = atoi(optarg); break; case 'd': segment_dir = optarg; break; case 'k': g_keep = true; break; case 'm': merge_only = atoi(optarg); break; case 'o': g_output = optarg; break; case 's': sort_only = true; break; case 'v': g_verbose = true; break; } } if (sort_only || count_only > 0 || merge_only > 0) { g_keep = true; if (sort_only) { int count = input(argc, argv); LOG_INFO << "wrote " << count << " segments"; } if (count_only) { int m = combine(count_only); LOG_INFO << "wrote " << m << " counts"; } if (merge_only) { merge(merge_only); } } else { int64_t total = 0; Timer timer; int count = input(argc, argv, &total); int m = combine(count); merge(m); LOG_INFO << "All done " << timer.report(total); } } <file_sep>/logging/AsyncLogging_test.cc #include <stdio.h> #include "datetime/Timestamp.h" #include "AsyncLoggingQueue.h" #include "AsyncLoggingDoubleBuffering.h" #include "Logging.h" #include <sys/resource.h> int kRollSize = 500*1000*1000; void* g_asyncLog = NULL; template<typename ASYNC> void asyncOutput(const char* msg, int len) { ASYNC* log = static_cast<ASYNC*>(g_asyncLog); log->append(msg, len); } template<typename ASYNC> void bench(ASYNC* log) { g_asyncLog = log; log->start(); muduo::Logger::setOutput(asyncOutput<ASYNC>); int cnt = 0; const int kBatch = 1000; const bool kLongLog = true; muduo::string empty = " "; muduo::string longStr(3000, 'X'); longStr += " "; for (int t = 0; t < 30; ++t) { muduo::Timestamp start = muduo::Timestamp::now(); for (int i = 0; i < kBatch; ++i) { LOG_INFO << "Hello 0123456789" << " abcdefghijklmnopqrstuvwxyz " << (kLongLog ? longStr : empty) << cnt; ++cnt; } muduo::Timestamp end = muduo::Timestamp::now(); printf("%f\n", timeDifference(end, start)*1000000/kBatch); struct timespec ts = { 0, 500*1000*1000 }; nanosleep(&ts, NULL); } } int main(int argc, char* argv[]) { { // set max virtual memory to 2GB. size_t kOneGB = 1024*1024*1024; rlimit rl = { 2.0*kOneGB, 2.0*kOneGB }; setrlimit(RLIMIT_AS, &rl); } muduo::AsyncLoggingUnboundedQueue log1("log1", kRollSize); muduo::AsyncLoggingBoundedQueue log2("log2", kRollSize, 1024); muduo::AsyncLoggingUnboundedQueueL log3("log3", kRollSize); muduo::AsyncLoggingBoundedQueueL log4("log4", kRollSize, 1024); muduo::AsyncLoggingDoubleBuffering log5("log5", kRollSize); int which = argc > 1 ? atoi(argv[1]) : 1; printf("pid = %d\n", getpid()); switch (which) { case 1: bench(&log1); break; case 2: bench(&log2); break; case 3: bench(&log3); break; case 4: bench(&log4); break; case 5: bench(&log5); break; } } <file_sep>/java/bankqueue/tests/EventTest.java package bankqueue.tests; import static org.junit.Assert.assertEquals; import java.util.PriorityQueue; import org.junit.Test; import bankqueue.event.Event; import bankqueue.event.EventSimulator; public class EventTest { @Test public void testCompareTo1() { PriorityQueue<Event> queue = new PriorityQueue<Event>(); queue.add(new Event(1) { @Override public void happen(EventSimulator simulator) { } }); queue.add(new Event(2) { @Override public void happen(EventSimulator simulator) { } }); assertEquals(1, queue.poll().scheduledTime); assertEquals(2, queue.poll().scheduledTime); } @Test public void testCompareTo2() { PriorityQueue<Event> queue = new PriorityQueue<Event>(); queue.add(new Event(2) { @Override public void happen(EventSimulator simulator) { } }); queue.add(new Event(1) { @Override public void happen(EventSimulator simulator) { } }); assertEquals(1, queue.poll().scheduledTime); assertEquals(2, queue.poll().scheduledTime); } } <file_sep>/digest/DigestTMP.cc #include "DigestOOP.h" #include <openssl/crypto.h> #include <openssl/md5.h> #include <openssl/sha.h> namespace oop { template<typename CTX, int Init(CTX*), int Update(CTX *c, const void *data, size_t len), int Final(unsigned char *md, CTX *c), int DIGEST_LENGTH> class DigestT : public Digest { public: DigestT() { Init(&ctx_); } ~DigestT() override { OPENSSL_cleanse(&ctx_, sizeof(ctx_)); } void update(const void* data, int len) override { Update(&ctx_, data, len); } std::string digest() override { unsigned char result[DIGEST_LENGTH]; Final(result, &ctx_); return std::string(reinterpret_cast<char*>(result), DIGEST_LENGTH); } int length() const override { return DIGEST_LENGTH; } private: CTX ctx_; }; typedef DigestT<MD5_CTX, MD5_Init, MD5_Update, MD5_Final, MD5_DIGEST_LENGTH> MD5Digest; typedef DigestT<SHA_CTX, SHA1_Init, SHA1_Update, SHA1_Final, SHA_DIGEST_LENGTH> SHA1Digest; typedef DigestT<SHA256_CTX, SHA256_Init, SHA256_Update, SHA256_Final, SHA256_DIGEST_LENGTH> SHA256Digest; // static std::unique_ptr<Digest> Digest::create(Type t) { if (t == MD5) return std::make_unique<MD5Digest>(); else if (t == SHA1) return std::make_unique<SHA1Digest>(); else if (t == SHA256) return std::make_unique<SHA256Digest>(); else return nullptr; } } // namespace oop <file_sep>/basic/partitions.cc #include "uint.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> std::vector<int> generalized_pentagonal_numbers; int gpn(int m) { return m * (3 * m - 1) / 2; } void gen(int N) { int m = 1; do { generalized_pentagonal_numbers.push_back(gpn(m)); generalized_pentagonal_numbers.push_back(gpn(-m)); ++m; } while (generalized_pentagonal_numbers.back() < N); } int main(int argc, char* argv[]) { const int N = atoi(argv[1]); gen(N); // printf("%zd\n", generalized_pentagonal_numbers.size()); // printf("%d\n", generalized_pentagonal_numbers.back()); std::vector<UnsignedInt> partitions; partitions.resize(N+1); partitions[0].add(1); for (int k = 1; k <= N; ++k) { UnsignedInt& result = partitions[k]; assert(result.isZero()); for (size_t i = 0; i < generalized_pentagonal_numbers.size(); ++i) { int x = generalized_pentagonal_numbers[i]; if (k - x >= 0) { UnsignedInt& term = partitions[k - x]; assert(!term.isZero()); if ((i / 2) % 2 == 0) { result.add(term); } else { result.sub(term); } } else { break; } } } printf("%s\n", partitions[N].toDec().c_str()); // for (size_t i = 0; i < partitions.size(); ++i) // { // printf(" %d", partitions[i].isZero()); // } } <file_sep>/puzzle/nbody.cc /* * The Great Computer Language Shootout * http://shootout.alioth.debian.org/ * * C version contributed by <NAME> * converted to C++ and modified by <NAME> */ #include <cmath> #include <stdio.h> #include <stdlib.h> struct Vector3 { Vector3(double x, double y, double z) : x(x), y(y), z(z) { } double x; double y; double z; }; struct Planet { Planet(const Vector3& position, const Vector3& velocity, double mass) : position(position), velocity(velocity), mass(mass) { } Vector3 position; Vector3 velocity; const double mass; }; inline Vector3& operator-=(Vector3& lhs, const Vector3& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; lhs.z -= rhs.z; return lhs; } inline Vector3 operator-(Vector3 lhs, const Vector3& rhs) { return (lhs -= rhs); } inline Vector3 operator-(Vector3 lhs) { return Vector3(-lhs.x, -lhs.y, -lhs.z); } inline Vector3& operator+=(Vector3& lhs, const Vector3& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; lhs.z += rhs.z; return lhs; } inline Vector3 operator+(Vector3 lhs, const Vector3& rhs) { return (lhs += rhs); } inline Vector3& operator*=(Vector3& lhs, double rhs) { lhs.x *= rhs; lhs.y *= rhs; lhs.z *= rhs; return lhs; } inline Vector3 operator*(Vector3 lhs, double rhs) { return (lhs *= rhs); } inline Vector3 operator*(double lhs, Vector3 rhs) { return (rhs *= lhs); } inline Vector3& operator/=(Vector3& lhs, double rhs) { lhs.x /= rhs; lhs.y /= rhs; lhs.z /= rhs; return lhs; } inline Vector3 operator/(Vector3 lhs, double rhs) { return (lhs /= rhs); } inline double magnitude_squared(const Vector3& vec) { return ((vec.x * vec.x) + (vec.y * vec.y)) + (vec.z * vec.z); } inline double magnitude(const Vector3& vec) { return std::sqrt(magnitude_squared(vec)); } void advance(int nbodies, Planet* bodies, double delta_time) { for (Planet* p1 = bodies; p1 != bodies + nbodies; ++p1) { for (Planet* p2 = p1 + 1; p2 != bodies + nbodies; ++p2) { Vector3 difference = p1->position - p2->position; double distance_squared = magnitude_squared(difference); double distance = std::sqrt(distance_squared); double magnitude = delta_time / (distance * distance_squared); p1->velocity -= difference * p2->mass * magnitude; p2->velocity += difference * p1->mass * magnitude; } } for (Planet* p = bodies; p != bodies + nbodies; ++p) { p->position += delta_time * p->velocity; } } void advance2(int nbodies, Planet* bodies, double delta_time) { for (Planet* p1 = bodies; p1 != bodies + nbodies; ++p1) { for (Planet* p2 = p1 + 1; p2 != bodies + nbodies; ++p2) { Vector3 difference = p1->position - p2->position; double distance_squared = magnitude_squared(difference); double distance = std::sqrt(distance_squared); double magnitude = delta_time / (distance * distance_squared); double planet2_mass_magnitude = p2->mass * magnitude; double planet1_mass_magnitude = p1->mass * magnitude; p1->velocity -= difference * planet2_mass_magnitude; p2->velocity += difference * planet1_mass_magnitude; } } for (Planet* p = bodies; p != bodies + nbodies; ++p) { p->position += delta_time * p->velocity; } } unsigned int const number_of_bodies = 5; double const days_per_year = 365.24; double const solar_mass = 4 * M_PI * M_PI; Planet bodies[5] = { Planet(Vector3(0, 0, 0), Vector3(0, 0, 0), solar_mass), Planet(Vector3(4.84143144246472090e+00, -1.16032004402742839e+00, -1.03622044471123109e-01), Vector3(1.66007664274403694e-03 * days_per_year, 7.69901118419740425e-03 * days_per_year, -6.90460016972063023e-05 * days_per_year), 9.54791938424326609e-04 * solar_mass), Planet(Vector3(8.34336671824457987e+00, 4.12479856412430479e+00, -4.03523417114321381e-01), Vector3(-2.76742510726862411e-03 * days_per_year, 4.99852801234917238e-03 * days_per_year, 2.30417297573763929e-05 * days_per_year), 2.85885980666130812e-04 * solar_mass), Planet(Vector3(1.28943695621391310e+01, -1.51111514016986312e+01, -2.23307578892655734e-01), Vector3(2.96460137564761618e-03 * days_per_year, 2.37847173959480950e-03 * days_per_year, -2.96589568540237556e-05 * days_per_year), 4.36624404335156298e-05 * solar_mass), Planet(Vector3(1.53796971148509165e+01, -2.59193146099879641e+01, 1.79258772950371181e-01), Vector3(2.68067772490389322e-03 * days_per_year, 1.62824170038242295e-03 * days_per_year, -9.51592254519715870e-05 * days_per_year), 5.15138902046611451e-05 * solar_mass) }; double energy() { double total_energy = 0.0; for (Planet * planet1 = bodies; planet1 != bodies + number_of_bodies; ++planet1) { total_energy += 0.5 * planet1->mass * magnitude_squared(planet1->velocity); for (Planet * planet2 = planet1 + 1; planet2 != bodies + number_of_bodies; ++planet2) { Vector3 difference = planet1->position - planet2->position; double distance = magnitude(difference); total_energy -= (planet1->mass * planet2->mass) / distance; } } return total_energy; } void offset_momentum() { Vector3 momentum(bodies[1].velocity * bodies[1].mass); for (Planet * planet = bodies + 2; planet != bodies + number_of_bodies; ++planet) { momentum += planet->velocity * planet->mass; } bodies[0].velocity = -momentum / solar_mass; } int main(int argc, char * * argv) { int n = atoi(argv[1]); offset_momentum(); printf ("%.9f\n", energy()); for (int i = 1; i <= n; ++i) { advance(number_of_bodies, bodies, 0.01); } printf ("%.9f\n", energy()); } <file_sep>/logging/build.sh g++ LogStream_test.cc LogStream.cc -o test -Wall -g -O0 -DBOOST_TEST_DYN_LINK -lboost_unit_test_framework g++ LogStream_bench.cc LogStream.cc ../datetime/Timestamp.cc -o bench -Wall -g -O2 g++ LogStream_bench.cc LogStream.cc ../datetime/Timestamp.cc -o bench-dbg -Wall -g -O0 g++ Logging_test.cc Logging.cc LogStream.cc LogFile.cc ../datetime/Timestamp.cc ../thread/Thread.cc -O2 -DNDEBUG -I.. -o test_log -Wall -Wextra -Wno-type-limits -g -lpthread g++ Logging_test.cc Logging.cc LogStream.cc LogFile.cc ../datetime/Timestamp.cc ../thread/Thread.cc -O0 -I.. -o test_log-dbg -Wall -Wextra -Wno-type-limits -g -lpthread g++ LogFile_test.cc Logging.cc LogStream.cc LogFile.cc ../datetime/Timestamp.cc ../thread/Thread.cc -O2 -DNDEBUG -I.. -o file_test -g -lpthread g++ LogFile_test.cc Logging.cc LogStream.cc LogFile.cc ../datetime/Timestamp.cc ../thread/Thread.cc -O0 -I.. -o file_test-dbg -g -lpthread g++ AsyncLogging_test.cc Logging.cc LogStream.cc LogFile.cc ../datetime/Timestamp.cc ../thread/Thread.cc -O2 -DNDEBUG -I.. -o async_test -g -lpthread -lrt g++ AsyncLogging_test.cc Logging.cc LogStream.cc LogFile.cc ../datetime/Timestamp.cc ../thread/Thread.cc -O0 -I.. -o async_test-dbg -g -lpthread -lrt <file_sep>/python/echo-fork.py #!/usr/bin/python from SocketServer import BaseRequestHandler, TCPServer from SocketServer import ForkingTCPServer, ThreadingTCPServer class EchoHandler(BaseRequestHandler): def handle(self): print "got connection from", self.client_address while True: data = self.request.recv(4096) if data: sent = self.request.send(data) # sendall? else: print "disconnect", self.client_address self.request.close() break if __name__ == "__main__": listen_address = ("0.0.0.0", 2007) server = ForkingTCPServer(listen_address, EchoHandler) server.serve_forever() <file_sep>/java/bankqueue/customer/NormalCustomer.java package bankqueue.customer; import bankqueue.Bank; import bankqueue.WindowType; public class NormalCustomer extends Customer { public NormalCustomer(int id, int serviceTime) { super(id, serviceTime); } @Override public boolean findSpareWindow(Bank bank) { return bank.hasAnySpareWindow(); } @Override public void gotoWindow(Bank bank) { if (bank.hasSpareWindow(WindowType.kNormal)) { bank.serveAtWindow(this, WindowType.kNormal); } else if (bank.hasSpareWindow(WindowType.kFast)) { bank.serveAtWindow(this, WindowType.kFast); } else if (bank.hasSpareWindow(WindowType.kVip)) { bank.serveAtWindow(this, WindowType.kVip); } else { assert false; } } } <file_sep>/protobuf/Makefile LIBDIR=/usr/local/lib CXXFLAGS=-g -Wall -O0 -pthread LDFLAGS=-lprotobuf -lz -lpthread -Wl,-rpath -Wl,$(LIBDIR) BINARIES=codec_test descriptor_test dispatcher_lite dispatcher TARGETS=$(BINARIES) # comment out following line if you have boost installed TARGETS=codec_test descriptor_test all: $(TARGETS) whole: $(BINARIES) codec_test: query.pb.h query.pb.cc codec.h codec_test.cc descriptor_test: query.pb.h query.pb.cc codec.h descriptor_test.cc dispatcher_lite: query.pb.h query.pb.cc dispatcher_lite.cc dispatcher: query.pb.h query.pb.cc dispatcher.cc $(BINARIES): g++ $(CXXFLAGS) $(filter %.cc,$^) -o $@ $(LDFLAGS) query.pb.h query.pb.cc: query.proto protoc --cpp_out . $< test: codec_test ./codec_test clean: rm -f query.pb.* rm -f $(BINARIES) <file_sep>/topk/file.h #pragma once #include <stdio.h> #include <fstream> #include <memory> #include <string> #include "absl/strings/string_view.h" #include "muduo/base/Logging.h" // CHECK_NOTNULL const int kBufferSize = 1024 * 1024; // Wrappers FILE* from stdio. class File { public: int64_t tell() const { return ::ftell(file_); } void close() { if (file_) ::fclose(file_); file_ = nullptr; buffer_.reset(); } const std::string& filename() const { return filename_; } // https://github.com/coreutils/coreutils/blob/master/src/ioblksize.h /* As of May 2014, 128KiB is determined to be the minimium * blksize to best minimize system call overhead. */ protected: File(const std::string& filename, const char* mode, int bufsize=kBufferSize) : filename_(filename), file_(CHECK_NOTNULL(::fopen(filename.c_str(), mode))), buffer_(CHECK_NOTNULL(new char[bufsize])) { ::setbuffer(file_, buffer_.get(), bufsize); } virtual ~File() { close(); } protected: std::string filename_; FILE* file_ = nullptr; private: std::unique_ptr<char[]> buffer_; File(const File&) = delete; void operator=(const File&) = delete; }; class InputFile : public File { public: explicit InputFile(const char* filename, int bufsize=kBufferSize) : File(filename, "r", bufsize) { } bool getline(std::string* output) { char buf[1024]; // ="" will slow down by 50%!!! if (::fgets(buf, sizeof buf, file_)) { *output = buf; if (!output->empty() && output->back() == '\n') { output->resize(output->size()-1); } return true; } return false; } }; /* class InputFile2 { public: explicit InputFile2(const char* filename, int bufsize=kBufferSize) : filename_(filename), in_(filename) { // FIXME: bufsize } bool getline(std::string* output) { return static_cast<bool>(std::getline(in_, *output)); } const std::string& filename() const { return filename_; } private: std::string filename_; std::ifstream in_; }; */ class OutputFile : public File { public: explicit OutputFile(const std::string& filename) : File(filename, "w") { } void write(absl::string_view s) { ::fwrite(s.data(), 1, s.size(), file_); } void writeWord(int64_t count, absl::string_view word) { ::fprintf(file_, "%ld\t", count); ::fwrite(word.data(), 1, word.size(), file_); ::fwrite("\n", 1, 1, file_); } void appendRecord(absl::string_view s) { assert(s.size() < 255); uint8_t len = s.size(); ::fwrite(&len, 1, sizeof len, file_); ::fwrite(s.data(), 1, len, file_); ++items_; } size_t items() { return items_; } private: size_t items_ = 0; }; <file_sep>/python/nqueens.py #!/usr/bin/python # http://code.activestate.com/recipes/576647-eight-queens-six-lines/ from itertools import permutations N = 8 for rows in permutations(range(N)): if (N == len(set(rows[i]-i for i in range(N))) # Diagonal == len(set(rows[i]+i for i in range(N)))): # Anti-diagonal print rows <file_sep>/topk/merge.h #pragma once #include "timer.h" #include <vector> #include <fcntl.h> #include <sys/stat.h> extern bool g_keep; extern const char* g_output; class TextInput { public: explicit TextInput(const char* filename, int buffer_size = 8 * 1024 * 1024) : fd_(::open(filename, O_RDONLY)), buffer_size_(buffer_size), block_(new Block) { assert(fd_ >= 0); block_->data.reset(new char[buffer_size_]); refill(); } ~TextInput() { ::close(fd_); } absl::string_view line() const { return line_; } bool next(int64_t* count) { // EOF if (block_->records.empty()) { return false; } if (index_ < block_->records.size()) { const Record& rec = block_->records[index_]; *count = rec.count; line_ = absl::string_view(block_->data.get() + rec.offset, rec.len); ++index_; return true; } else { refill(); index_ = 0; return next(count); } } private: struct Record { int64_t count = 0; int32_t offset = 0, len = 0; }; struct Block { std::unique_ptr<char[]> data; std::vector<Record> records; }; void refill() { block_->records.clear(); char* data = block_->data.get(); ssize_t nr = ::pread(fd_, data, buffer_size_, pos_); if (nr > 0) { char* start = data; size_t len = nr; char* nl = static_cast<char*>(::memchr(start, '\n', len)); while (nl) { Record rec; rec.count = strtol(start, NULL, 10); rec.offset = start - data; rec.len = nl - start + 1; block_->records.push_back(rec); start = nl+1; len -= rec.len; nl = static_cast<char*>(::memchr(start, '\n', len)); } pos_ += start - data; } } const int fd_; const int buffer_size_; int64_t pos_ = 0; // file position size_t index_ = 0; // index into block_ std::unique_ptr<Block> block_; absl::string_view line_; TextInput(const TextInput&) = delete; void operator=(const TextInput&) = delete; }; class Source // copyable { public: explicit Source(TextInput* in) : input_(in) { } bool next() { return input_->next(&count_); } bool operator<(const Source& rhs) const { return count_ < rhs.count_; } absl::string_view line() const { return input_->line(); } private: TextInput* input_; // not owned int64_t count_ = 0; }; int64_t merge(int n) { Timer timer; std::vector<std::unique_ptr<TextInput>> inputs; std::vector<Source> keys; int64_t total = 0; for (int i = 0; i < n; ++i) { char buf[256]; snprintf(buf, sizeof buf, "count-%05d", i); struct stat st; if (::stat(buf, &st) == 0) { total += st.st_size; // TODO: select buffer size based on kShards. inputs.push_back(std::make_unique<TextInput>(buf)); Source rec(inputs.back().get()); if (rec.next()) { keys.push_back(rec); } if (!g_keep) ::unlink(buf); } else { perror("Unable to stat file:"); } } LOG_INFO << "merging " << inputs.size() << " files of " << total << " bytes in total"; int64_t lines = 0; { OutputFile out(g_output); std::make_heap(keys.begin(), keys.end()); while (!keys.empty()) { std::pop_heap(keys.begin(), keys.end()); out.write(keys.back().line()); ++lines; if (keys.back().next()) { std::push_heap(keys.begin(), keys.end()); } else { keys.pop_back(); } } } LOG_INFO << "Merging done " << timer.report(total) << " lines " << lines; return total; } <file_sep>/tpc/bin/discard.cc #include "thread/Atomic.h" #include "datetime/Timestamp.h" #include "Acceptor.h" #include "InetAddress.h" #include "TcpStream.h" #include <string.h> #include <thread> muduo::AtomicInt64 g_bytes; void measure() { muduo::Timestamp start = muduo::Timestamp::now(); while (true) { struct timespec ts = { 1, 0 }; ::nanosleep(&ts, NULL); // unfortunately, those two assignments are not atomic int64_t bytes = g_bytes.getAndSet(0); muduo::Timestamp end = muduo::Timestamp::now(); double elapsed = timeDifference(end, start); start = end; if (bytes) { printf("%.3f MiB/s\n", bytes / (1024.0 * 1024) / elapsed); } } } void discard(TcpStreamPtr stream) { char buf[65536]; while (true) { int nr = stream->receiveSome(buf, sizeof buf); if (nr <= 0) break; g_bytes.add(nr); } } // a thread-per-connection current discard server and client int main(int argc, char* argv[]) { if (argc < 3) { printf("Usage:\n %s hostname port\n %s -l port [-6]\n", argv[0], argv[0]); return 0; } std::thread(measure).detach(); int port = atoi(argv[2]); if (strcmp(argv[1], "-l") == 0) { const bool ipv6 = (argc > 3 && strcmp(argv[3], "-6") == 0); Acceptor acceptor((InetAddress(port, ipv6))); printf("Accepting... Ctrl-C to exit\n"); int count = 0; while (true) { TcpStreamPtr tcpStream = acceptor.accept(); printf("accepted no. %d client: %s <- %s\n", ++count, tcpStream->getLocalAddr().toIpPort().c_str(), tcpStream->getPeerAddr().toIpPort().c_str()); std::thread thr(discard, std::move(tcpStream)); thr.detach(); } } else { InetAddress addr; const char* hostname = argv[1]; if (InetAddress::resolve(hostname, port, &addr)) { TcpStreamPtr stream(TcpStream::connect(addr)); if (stream) { discard(std::move(stream)); } else { printf("Unable to connect %s\n", addr.toIpPort().c_str()); perror(""); } } else { printf("Unable to resolve %s\n", hostname); } } } <file_sep>/python/netcat.py #!/usr/bin/python import os import select import socket import sys def relay(sock): poll = select.poll() poll.register(sock, select.POLLIN) poll.register(sys.stdin, select.POLLIN) done = False while not done: events = poll.poll(10000) # 10 seconds for fileno, event in events: if event & select.POLLIN: if fileno == sock.fileno(): data = sock.recv(8192) if data: sys.stdout.write(data) else: done = True else: assert fileno == sys.stdin.fileno() data = os.read(fileno, 8192) if data: sock.sendall(data) else: sock.shutdown(socket.SHUT_WR) poll.unregister(sys.stdin) def main(argv): if len(argv) < 3: binary = argv[0] print "Usage:\n %s -l port\n %s host port" % (argv[0], argv[0]) return port = int(argv[2]) if argv[1] == "-l": # server server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(('', port)) server_socket.listen(5) (client_socket, client_address) = server_socket.accept() server_socket.close() relay(client_socket) else: # client sock = socket.create_connection((argv[1], port)) relay(sock) if __name__ == "__main__": main(sys.argv) <file_sep>/tpc/lib/TcpStream.cc #include "TcpStream.h" #include "InetAddress.h" #include <errno.h> #include <signal.h> #include <unistd.h> #include <sys/socket.h> namespace { class IgnoreSigPipe { public: IgnoreSigPipe() { ::signal(SIGPIPE, SIG_IGN); } } initObj; bool isSelfConnection(const Socket& sock) { return sock.getLocalAddr() == sock.getPeerAddr(); } } TcpStream::TcpStream(Socket&& sock) : sock_(std::move(sock)) { } int TcpStream::receiveAll(void* buf, int len) { #ifdef TEMP_FAILURE_RETRY return TEMP_FAILURE_RETRY(::recv(sock_.fd(), buf, len, MSG_WAITALL)); #else return ::recv(sock_.fd(), buf, len, MSG_WAITALL); #endif } int TcpStream::receiveSome(void* buf, int len) { return sock_.recv(buf, len); } int TcpStream::sendAll(const void* buf, int len) { int written = 0; while (written < len) { int nw = sock_.send(static_cast<const char*>(buf) + written, len - written); if (nw > 0) { written += nw; } else { break; } } return written; } int TcpStream::sendSome(const void* buf, int len) { return sock_.send(buf, len); } void TcpStream::setTcpNoDelay(bool on) { sock_.setTcpNoDelay(on); } void TcpStream::shutdownWrite() { sock_.shutdownWrite(); } TcpStreamPtr TcpStream::connect(const InetAddress& serverAddr) { return connectInternal(serverAddr, nullptr); } TcpStreamPtr TcpStream::connect(const InetAddress& serverAddr, const InetAddress& localAddr) { return connectInternal(serverAddr, &localAddr); } TcpStreamPtr TcpStream::connectInternal(const InetAddress& serverAddr, const InetAddress* localAddr) { TcpStreamPtr stream; Socket sock(Socket::createTCP(serverAddr.family())); if (localAddr) { sock.bindOrDie(*localAddr); } if (sock.connect(serverAddr) == 0 && !isSelfConnection(sock)) { // FIXME: do poll(POLLOUT) to check errors stream.reset(new TcpStream(std::move(sock))); } return stream; } <file_sep>/puzzle/nqueens.cc #include <algorithm> #include <numeric> #include <vector> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <sys/time.h> double now() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec / 1000000.0; } int bruteforce(const int N) { int count = 0; std::vector<int> pos(N); std::iota(pos.begin(), pos.end(), 0); do { bool diagnoal[2*N]; bzero(diagnoal, sizeof(diagnoal)); bool antidiagnoal[2*N]; bzero(antidiagnoal, sizeof(antidiagnoal)); for (int i = 0; i < N; ++i) { if (antidiagnoal[i + pos[i]]) { goto infeasible; } else { antidiagnoal[i + pos[i]] = true; } // } // for (int i = 0; i < N; ++i) { const int d = N + i - pos[i]; if (diagnoal[d]) { goto infeasible; } else { diagnoal[d] = true; } } ++count; infeasible: ; } while (next_permutation(pos.begin(), pos.end())); return count; } struct BackTracking { const static int kMaxQueens = 16; const int N; int count; bool columns[kMaxQueens]; bool diagnoal[2*kMaxQueens], antidiagnoal[2*kMaxQueens]; BackTracking(int nqueens) : N(nqueens), count(0) { assert(0 < N && N <= kMaxQueens); bzero(columns, sizeof columns); bzero(diagnoal, sizeof diagnoal); bzero(antidiagnoal, sizeof antidiagnoal); } void search(const int row) { for (int i = 0; i < N; ++i) { const int d = N + row - i; if (!(columns[i] || antidiagnoal[row + i] || diagnoal[d])) { if (row == N - 1) { ++count; } else { columns[i] = true; antidiagnoal[row + i] = true; diagnoal[d] = true; search(row+1); columns[i] = false; antidiagnoal[row + i] = false; diagnoal[d] = false; } } } } }; int backtracking(int N) { BackTracking bt(N); bt.search(0); return bt.count; } int main(int argc, char* argv[]) { int nqueens = argc > 1 ? atoi(argv[1]) : 8; double start = now(); int solutions = backtracking(nqueens); double end = now(); printf("%d solutions of %d queens puzzle.\n", solutions, nqueens); printf("%f seconds.\n", end - start); /* double start = now(); int s1 = bruteforce(nqueens); double middle = now(); int s2 = backtracking(nqueens); double end = now(); printf("brute force %d, backtracking %d\n", s1, s2); printf("brute force %f\nbacktracking %f\n", middle - start, end - middle); */ } <file_sep>/ssl/benchmark-libressl.cc #include <muduo/net/Buffer.h> #include <stdio.h> #include <tls.h> #include "timer.h" muduo::net::Buffer clientOut, serverOut; int64_t clientWrite, serverWrite; ssize_t net_read(struct tls *ctx, void *buf, size_t len, void *arg) { muduo::net::Buffer* in = ((arg == &clientOut) ? &serverOut : &clientOut); if (in->readableBytes() > 0) { size_t n = std::min(in->readableBytes(), len); memcpy(buf, in->peek(), n); in->retrieve(n); return n; } else { return TLS_WANT_POLLIN; } } ssize_t net_write(struct tls *ctx, const void *buf, size_t len, void *arg) { muduo::net::Buffer* out = static_cast<muduo::net::Buffer*>(arg); int64_t& wr = (out == &clientOut ? clientWrite : serverWrite); wr += len; out->append(buf, len); return len; } struct tls* client() { struct tls_config* cfg = tls_config_new(); assert(cfg != NULL); // symlink to libressl/tests/ca.pem tls_config_set_ca_file(cfg, "ca.pem"); // tls_config_insecure_noverifycert(cfg); // tls_config_insecure_noverifyname(cfg); struct tls* ctx = tls_client(); assert(ctx != NULL); int ret = tls_configure(ctx, cfg); assert(ret == 0); tls_connect_cbs(ctx, net_read, net_write, &clientOut, "Test Server Cert"); return ctx; } struct tls* server() { struct tls_config* cfg = tls_config_new(); assert(cfg != NULL); int ret = tls_config_set_cert_file(cfg, "server.pem"); assert(ret == 0); ret = tls_config_set_key_file(cfg, "server.pem"); assert(ret == 0); ret = tls_config_set_ecdhecurve(cfg, "prime256v1"); assert(ret == 0); // tls_config_verify_client_optional(cfg); struct tls* ctx = tls_server(); assert(ctx != NULL); ret = tls_configure(ctx, cfg); assert(ret == 0); struct tls* conn_ctx = NULL; tls_accept_cbs(ctx, &conn_ctx, net_read, net_write, &serverOut); return conn_ctx; } Timer tclient, tserver; bool handshake(struct tls* cctx, struct tls* sctx) { int client_done = false, server_done = false; while (!(client_done && server_done)) { if (!client_done) { tclient.start(); int ret = tls_handshake(cctx); tclient.stop(); // printf("c %d\n", ret); if (ret == 0) client_done = true; else if (ret == -1) { printf("client handshake failed: %s\n", tls_error(cctx)); break; } } if (!server_done) { tserver.start(); int ret = tls_handshake(sctx); tserver.stop(); // printf("s %d\n", ret); if (ret == 0) server_done = true; else if (ret == -1) { printf("server handshake failed: %s\n", tls_error(sctx)); break; } } } return client_done && server_done; } void throughput(int block_size, struct tls* cctx, struct tls* sctx) { double start = now(); int total = 0; int batch = 1024; char* message = new char[block_size]; bzero(message, block_size); clientWrite = 0; tclient.reset(); tserver.reset(); while (now() - start < 10) { for (int i = 0; i < batch; ++i) { tclient.start(); int nw = tls_write(cctx, message, block_size); tclient.stop(); assert(nw == block_size); tserver.start(); int nr = tls_read(sctx, message, block_size); tserver.stop(); assert(nr == block_size); } total += batch; batch *= 2; } double secs = now() - start; // throughput is half of real value, because client and server share one core. printf("bs %5d sec %.3f tot %d thr %.1fKB/s wr %.2fB client %.3f server %.3f\n", block_size, secs, total, block_size / secs * total / 1024, clientWrite * 1.0 / total, tclient.seconds(), tserver.seconds()); delete[] message; } int main(int argc, char* argv[]) { int ret = tls_init(); assert(ret == 0); struct tls* cctx = client(); struct tls* sctx = server(); const int N = 1000; Timer all, client, server; all.start(); for (int i = 0; i < N; ++i) { if (!handshake(cctx, sctx)) return -1; if (i == 0) printf("cipher %s\n", tls_conn_cipher(cctx)); } all.stop(); printf("%f secs, %f handshakes/sec\n", all.seconds(), N / all.seconds()); printf("client %f secs, server %f secs\n", tclient.seconds(), tserver.seconds()); for (int i = 1024 * 16; i >= 1; i /= 4) { throughput(i, cctx, sctx); } } <file_sep>/python/throughput-bidi.py #!/usr/bin/python3 # A simple program to test TCP throughput, by sending data for 10 seconds. import socket, sys, time def report(total_bytes : int, elapsed_seconds : float, syscalls : int): mbps = total_bytes / 1e6 / elapsed_seconds print('Transferred %.3fMB in %.3fs, throughput %.3fMB/s %.3fMbits/s, %d syscalls %.1f Bytes/syscall' % (total_bytes / 1e6, elapsed_seconds, mbps, mbps * 8, syscalls, total_bytes / syscalls)) def print_buf(sock): rcvbuf = sock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF) sndbuf = sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF) print('rcvbuf=%.1fK sndbuf=%.1fK' % (rcvbuf / 1024.0, sndbuf / 1024.0)) def format_address(sock): def format(addr): return '%s:%d' % addr return (format(sock.getsockname()), format(sock.getpeername())) def run_sender(sock): buf = b'X' * 65536 print('Sending... %s -> %s' % format_address(sock)) print_buf(sock) start = time.time() total = 0 count = 0 while True: total += sock.send(buf) count += 1 if time.time() - start > 10: break print_buf(sock) sent = time.time() sock.shutdown(socket.SHUT_WR) sock.recv(4096) print('waited %.1fms' % ((time.time() - sent) * 1e3)) report(total, time.time() - start, count) def run_receiver(sock): print('Receiving... %s <- %s' % format_address(sock)) print_buf(sock) start = time.time() total = 0 count = 0 while True: data = sock.recv(65536) if not data: break total += len(data) count += 1 print_buf(sock) sock.close() report(total, time.time() - start, count) if __name__ == '__main__': port = 2009 if len(sys.argv) < 2: print('Usage: {0} -s or {0} server'.format(sys.argv[0])) print('Append -b to send traffic backwards.') elif sys.argv[1] == '-s': server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(('', port)) server_socket.listen(5) while True: sock, client_addr = server_socket.accept() if len(sys.argv) > 2 and sys.argv[2] == '-b': run_sender(sock) else: run_receiver(sock) else: sock = socket.create_connection((sys.argv[1], port)) if len(sys.argv) > 2 and sys.argv[2] == '-b': run_receiver(sock) else: run_sender(sock) <file_sep>/topk/Makefile MUDUO_BUILD ?= release MUDUO_DIRECTORY ?= $(HOME)/build/$(MUDUO_BUILD)-install MUDUO_INCLUDE = $(MUDUO_DIRECTORY)/include MUDUO_LIBRARY = $(MUDUO_DIRECTORY)/lib CXXFLAGS = -g -Og -Wall -Wextra -Werror \ -Wno-unused-parameter -Wconversion\ -Wold-style-cast -Woverloaded-virtual \ -Wpointer-arith -Wshadow -Wwrite-strings \ -march=native -rdynamic \ -I$(MUDUO_INCLUDE) LDFLAGS = -L$(MUDUO_LIBRARY) -lmuduo_net -lmuduo_base -lpthread BINARIES = sender merger word_freq word_freq_shards word_freq_sort all: $(BINARIES) clean: rm -f $(BINARIES) core sender: sender.cc g++ $(CXXFLAGS) -o $@ $^ $(LDFLAGS) merger: merger.cc g++ $(CXXFLAGS) -o $@ $^ -lboost_system -lpthread word_freq: word_freq.cc g++ $(CXXFLAGS) -std=c++1y -o $@ $^ word_freq_shards: word_freq_shards.cc g++ $(CXXFLAGS) -std=c++11 -o $@ $^ word_freq_sort: word_freq_sort.cc g++ $(CXXFLAGS) -std=c++11 -o $@ $^ .PHONY: all clean <file_sep>/puzzle/fib.py from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys total_mul = 0 total_add = 0 def calc(N, c, level): global total_mul, total_add if N not in c: half = N // 2; if N % 2 == 0: print('%s"%d" -> "%d"' % (" "*level*2, half-1, N)) print('%s"%d" -> "%d"' % (" "*level*2, half, N)) print('%s"%d" -> "%d"' % (" "*level*2, half+1, N)) c.add(N) if N % 2 == 0: calc(half-1, c, level+1) calc(half, c, level+1) c.add(half+1) total_add += 2 total_mul += 1 print('%s"%d" -> "%d" [color=green,constraint=false]' % (" "*level*2, half-1, half+1)) print('%s"%d" -> "%d" [color=green,constraint=false]' % (" "*level*2, half, half+1)) else: calc(half, c, level+1) calc(half+1, c, level+1) total_add += 1 total_mul += 2 def main(argv): if len(argv) > 1: N = int(argv[1]) c = set([1, 2, 3]) print('digraph G {') print('node [shape=box]') for k in sorted(c): print('"%d" [style=filled]' % k) calc(N, c, 0) print('}\n// total_add = %d, total_mul = %d' % (total_add, total_mul)) else: print("Usage: %s N" % argv[0]) if __name__ == '__main__': main(sys.argv) <file_sep>/tpc/bin/nodelay.cc #include "InetAddress.h" #include "TcpStream.h" #include <string.h> #include <sys/time.h> #include <unistd.h> double now() { struct timeval tv = { 0, 0 }; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec / 1000000.0; } int main(int argc, char* argv[]) { if (argc < 3) { printf("Usage: %s [-b] [-D] [-n num] hostname message_length\n", argv[0]); printf(" -b Buffering request before sending.\n" " -D Set TCP_NODELAY.\n" " -n num Send num concurrent requests, default = 1.\n"); return 0; } int opt = 0; bool buffering = false; bool tcpnodelay = false; int num = 1; while ( (opt = getopt(argc, argv, "bDn:")) != -1) { switch (opt) { case 'b': buffering = true; break; case 'D': tcpnodelay = true; break; case 'n': num = atoi(optarg); break; default: printf("Unknown option '%c'\n", opt); return 0; } } if (optind > argc - 2) { printf("Please specify hostname and message_length.\n"); return 0; } const char* hostname = argv[optind]; int len = atoi(argv[optind+1]); const uint16_t port = 3210; InetAddress addr; if (!InetAddress::resolve(hostname, port, &addr)) { printf("Unable to resolve %s\n", argv[1]); return 0; } printf("connecting to %s\n", addr.toIpPort().c_str()); TcpStreamPtr stream(TcpStream::connect(addr)); if (!stream) { printf("Unable to connect %s\n", addr.toIpPort().c_str()); perror(""); return 0; } if (tcpnodelay) { stream->setTcpNoDelay(true); printf("connected, set TCP_NODELAY\n"); } else { stream->setTcpNoDelay(false); printf("connected\n"); } double start = now(); for (int n = 0; n < num; ++n) { printf("Request no. %d, sending %d bytes\n", n, len); if (buffering) { std::vector<char> message(len + sizeof len, 'S'); memcpy(message.data(), &len, sizeof len); int nw = stream->sendAll(message.data(), message.size()); printf("%.6f sent %d bytes\n", now(), nw); } else { stream->sendAll(&len, sizeof len); printf("%.6f sent header\n", now()); usleep(1000); // prevent kernel merging TCP segments std::string payload(len, 'S'); int nw = stream->sendAll(payload.data(), payload.size()); printf("%.6f sent %d bytes\n", now(), nw); } } printf("Sent all %d requests, receiving responses.\n", num); for (int n = 0; n < num; ++n) { int ack = 0; int nr = stream->receiveAll(&ack, sizeof ack); printf("%.6f received %d bytes, ack = %d\n", now(), nr, ack); } printf("total %f seconds\n", now() - start); } <file_sep>/python/chat-reactor.py #!/usr/bin/python import socket import select server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(('', 2007)) server_socket.listen(5) # serversocket.setblocking(0) poll = select.poll() # epoll() should work the same connections = {} handlers = {} def handle_input(socket, data): for (fd, other_socket) in connections.iteritems(): if other_socket != socket: other_socket.send(data) # sendall() partial? def handle_request(fileno, event): if event & select.POLLIN: client_socket = connections[fileno] data = client_socket.recv(4096) if data: handle_input(client_socket, data) else: poll.unregister(fileno) client_socket.close() del connections[fileno] del handlers[fileno] def handle_accept(fileno, event): (client_socket, client_address) = server_socket.accept() print "got connection from", client_address # client_socket.setblocking(0) poll.register(client_socket.fileno(), select.POLLIN) connections[client_socket.fileno()] = client_socket handlers[client_socket.fileno()] = handle_request poll.register(server_socket.fileno(), select.POLLIN) handlers[server_socket.fileno()] = handle_accept while True: events = poll.poll(10000) # 10 seconds for fileno, event in events: handler = handlers[fileno] handler(fileno, event) <file_sep>/basic/numheaps.cc // http://oeis.org/A056971 #include "uint.h" #include <assert.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <unordered_map> UnsignedInt combination(int N, int M) { // printf("Choose N=%d M=%d\n", N, M); assert(0 <= M && M <= N); if (M > N/2) M = N - M; UnsignedInt result(1); for (int i = 1; i <= M; ++i) { result.multiply(N - i + 1); int r = result.devide(i); assert(r == 0); if (r != 0) abort(); } return result; } std::unordered_map<int, UnsignedInt> table = { { 0, 1 }, { 1, 1 }, }; const UnsignedInt& num_heaps(int N) { UnsignedInt& result = table[N]; if (result.isZero()) { int h = log2(N); int left = std::min(pow(2, h)-1, N - pow(2,h-1)); result = combination(N-1, left); result.multiply(num_heaps(left)); int right = N - 1 - left; result.multiply(num_heaps(right)); } else { // printf("hit %d\n", N); } return result; } int main(int argc, char* argv[]) { if (argc > 1) { UnsignedInt result = num_heaps(atoi(argv[1])); printf("%s\n", result.toDec().c_str()); } else { printf("Usage: %s N\n", argv[0]); printf("Number of binary heaps on N elements.\n"); } } <file_sep>/puzzle/huarong.cc #include <boost/functional/hash/hash.hpp> #include <deque> #include <type_traits> #include <unordered_set> #include <vector> #include <assert.h> #include <stddef.h> #include <stdio.h> #include <string.h> #include <strings.h> int board[5][4] = { // 0 1 2 3 { 1, 2, 2, 3, }, // 0 { 1, 2, 2, 3, }, // 1 { 4, 5, 5, 6, }, // 2 { 4, 7, 8, 6, }, // 3 { 9, 0, 0, 10 } }; // 4 struct Mask; const int kRows = 5; const int kColumns = 4; const int kBlocks = 10; enum class Shape // : int8_t { kInvalid, kSingle, kHorizon, kVertical, kSquare, }; struct Block { Shape shape; int left, top; // int8_t Block() : shape(Shape::kInvalid), left(-1), top(-1) { } Block(Shape s, int left, int top) : shape(s), left(left), top(top) { assert(shape != Shape::kInvalid); assert(left >= 0 && left < kColumns); assert(top >= 0 && top < kRows); } int bottom() const { const static int delta[] = { 0, 0, 0, 1, 1, }; assert(shape != Shape::kInvalid); return top + delta[static_cast<int>(shape)]; } int right() const { const static int delta[] = { 0, 0, 1, 0, 1, }; assert(shape != Shape::kInvalid); return left + delta[static_cast<int>(shape)]; } void mask(int8_t value, Mask* mask) const; }; struct Mask { Mask() { bzero(board_, sizeof(board_)); } bool operator==(const Mask& rhs) const { return memcmp(board_, rhs.board_, sizeof board_) == 0; } size_t hashValue() const { const int8_t* begin = board_[0]; return boost::hash_range(begin, begin + sizeof(board_)); } void print() const { for (int i = 0; i < kRows; ++i) { for (int j = 0; j < kColumns; ++j) { printf(" %c", board_[i][j] + '0'); } printf("\n"); } } void set(int8_t value, int y, int x) { assert(value > 0); assert(x >= 0 && x < kColumns); assert(y >= 0 && y < kRows); assert(board_[y][x] == 0); board_[y][x] = value; } bool empty(int y, int x) const { assert(x >= 0 && x < kColumns); assert(y >= 0 && y < kRows); return board_[y][x] == 0; } private: int8_t board_[kRows][kColumns]; }; namespace std { template<> struct hash<Mask> { size_t operator()(const Mask& x) const { return x.hashValue(); } }; } inline void Block::mask(int8_t value, Mask* mask) const { mask->set(value, top, left); switch (shape) { case Shape::kHorizon: mask->set(value, top, left+1); break; case Shape::kVertical: mask->set(value, top+1, left); break; case Shape::kSquare: mask->set(value, top, left+1); mask->set(value, top+1, left); mask->set(value, top+1, left+1); break; default: assert(shape == Shape::kSingle); ; } } struct State { Mask toMask() const { Mask m; for (int i = 0; i < kBlocks; ++i) { Block b = blocks_[i]; b.mask(static_cast<int>(b.shape), &m); } return m; } bool isSolved() const { // FIXME: magic number Block square = blocks_[1]; assert(square.shape == Shape::kSquare); return (square.left == 1 && square.top == 3); } template<typename FUNC> void move(const FUNC& func) const { static_assert(std::is_convertible<FUNC, std::function<void(const State&)>>::value, "func must be callable with a 'const State&' parameter."); const Mask mask = toMask(); for (int i = 0; i < kBlocks; ++i) { Block b = blocks_[i]; // move up if (b.top > 0 && mask.empty(b.top-1, b.left) && mask.empty(b.top-1, b.right())) { State next = *this; next.step++; next.blocks_[i].top--; func(next); } // move down if (b.bottom() < kRows-1 && mask.empty(b.bottom()+1, b.left) && mask.empty(b.bottom()+1, b.right())) { State next = *this; next.step++; next.blocks_[i].top++; func(next); } // move left if (b.left > 0 && mask.empty(b.top, b.left-1) && mask.empty(b.bottom(), b.left-1)) { State next = *this; next.step++; next.blocks_[i].left--; func(next); } // move right if (b.right() < kColumns-1 && mask.empty(b.top, b.right()+1) && mask.empty(b.bottom(), b.right()+1)) { State next = *this; next.step++; next.blocks_[i].left++; func(next); } } } // std::vector<State> moves() const; Block blocks_[kBlocks]; int step = 0; }; int main() { printf("sizeof(Mask) = %zd, sizeof(State) = %zd\n", sizeof(Mask), sizeof(State)); std::unordered_set<Mask> seen; std::deque<State> queue; State initial; initial.blocks_[0] = Block(Shape::kVertical, 0, 0); initial.blocks_[1] = Block(Shape::kSquare, 1, 0); initial.blocks_[2] = Block(Shape::kVertical, 3, 0); initial.blocks_[3] = Block(Shape::kVertical, 0, 2); initial.blocks_[4] = Block(Shape::kHorizon, 1, 2); initial.blocks_[5] = Block(Shape::kVertical, 3, 2); initial.blocks_[6] = Block(Shape::kSingle, 1, 3); initial.blocks_[7] = Block(Shape::kSingle, 2, 3); initial.blocks_[8] = Block(Shape::kSingle, 0, 4); initial.blocks_[9] = Block(Shape::kSingle, 3, 4); queue.push_back(initial); seen.insert(initial.toMask()); while (!queue.empty()) { const State curr = queue.front(); queue.pop_front(); if (curr.isSolved()) { printf("found solution with %d steps\n", curr.step); break; } else if (curr.step > 200) { printf("too many steps.\n"); break; } curr.move([&seen, &queue](const State& next) { auto result = seen.insert(next.toMask()); if (result.second) queue.push_back(next); }); // for (const State& next : curr.moves()) // { // auto result = seen.insert(next.toMask()); // if (result.second) // queue.push_back(next); // } } } <file_sep>/algorithm/removeContinuousSpaces.cc #include <assert.h> #include <algorithm> #include <string> struct AreBothSpaces { bool operator()(char x, char y) const { return x == ' ' && y == ' '; } }; void removeContinuousSpaces(std::string& str) { std::string::iterator last = std::unique(str.begin(), str.end(), AreBothSpaces()); str.erase(last, str.end()); } int main() { std::string inout; inout = ""; removeContinuousSpaces(inout); assert(inout == ""); inout = "a"; removeContinuousSpaces(inout); assert(inout == "a"); inout = " a"; removeContinuousSpaces(inout); assert(inout == " a"); inout = " a"; removeContinuousSpaces(inout); assert(inout == " a"); inout = "a "; removeContinuousSpaces(inout); assert(inout == "a "); inout = "a "; removeContinuousSpaces(inout); assert(inout == "a "); inout = "aaa bbb"; removeContinuousSpaces(inout); assert(inout == "aaa bbb"); inout = "aaa bbb ccc"; removeContinuousSpaces(inout); assert(inout == "aaa bbb ccc"); inout = " a b c d "; removeContinuousSpaces(inout); assert(inout == " a b c d "); inout = " "; removeContinuousSpaces(inout); assert(inout == " "); } <file_sep>/pingpong/asio/build.sh #!/bin/bash g++ -O2 -finline-limit=1000 server.cpp -o server -lpthread -lboost_thread -lboost_system g++ -O2 -finline-limit=1000 client.cpp -o client -lpthread -lboost_thread -lboost_system # g++ -O2 -finline-limit=1000 -I../asio-1.4.5/include server.cpp -o server145 -lpthread # g++ -O2 -finline-limit=1000 -I../asio-1.4.5/include client.cpp -o client145 -lpthread <file_sep>/ssl/TlsConfig.h #pragma once #include "Common.h" #include "logging/Logging.h" #include <tls.h> class TlsConfig : noncopyable { public: TlsConfig() : config_(CHECK_NOTNULL(tls_config_new())) { if (initialized <= 0) { LOG_FATAL; } } ~TlsConfig() { tls_config_free(config_); } void setCaFile(StringArg caFile) { check(tls_config_set_ca_file(config_, caFile.c_str())); } void setCertFile(StringArg certFile) { check(tls_config_set_cert_file(config_, certFile.c_str())); } void setKeyFile(StringArg keyFile) { check(tls_config_set_key_file(config_, keyFile.c_str())); } struct tls_config* get() { return config_; } private: void check(int ret) { if (ret != 0) { LOG_FATAL << tls_config_error(config_); } } struct tls_config* config_; static int initialized; }; <file_sep>/java/billing/test/VipCustomerTest.java package billing.test; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.joda.time.LocalDateTime; import org.junit.Test; import billing.BillCalculator; import billing.Money; import billing.Slip; import billing.UserMonthUsage; import billing.DataFields.PackageType; import billing.DataFields.SlipType; import billing.DataFields.UserField; import billing.DataFields.UserType; public class VipCustomerTest { private static final BillCalculator calculator = new BillCalculator("./groovy/billing/"); @Test public void testVipUserNoPackageNoActivity() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 30); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(60, 0), calculator.calculate(usage)); } @Test public void testVipUserNoPackageNoActivity28days() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 28); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(56, 0), calculator.calculate(usage)); } @Test public void testVipUserNoPackageOneCall() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 30); List<Slip> slips = new ArrayList<Slip>(); slips.add(new Slip(SlipType.kPhoneCall, new LocalDateTime(), 1)); data.put(UserField.kSlips, slips); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(60, 40), calculator.calculate(usage)); } @Test public void testVipUserNoPackageOneMessage() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 30); List<Slip> slips = new ArrayList<Slip>(); slips.add(new Slip(SlipType.kShortMessage, new LocalDateTime(), 1)); data.put(UserField.kSlips, slips); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(60, 10), calculator.calculate(usage)); } @Test public void testVipUserNoPackage50kInternet() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 30); List<Slip> slips = new ArrayList<Slip>(); slips.add(new Slip(SlipType.kInternet, new LocalDateTime(), 50)); data.put(UserField.kSlips, slips); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(60, 15), calculator.calculate(usage)); } @Test public void testVipUserNoPackageAllThree() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 30); List<Slip> slips = new ArrayList<Slip>(); slips.add(new Slip(SlipType.kPhoneCall, new LocalDateTime(), 10)); slips.add(new Slip(SlipType.kShortMessage, new LocalDateTime(), 15)); slips.add(new Slip(SlipType.kInternet, new LocalDateTime(), 100)); data.put(UserField.kSlips, slips); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(65, 80), calculator.calculate(usage)); } @Test public void testVipUserNoPackageAllThree31Days() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 31); List<Slip> slips = new ArrayList<Slip>(); slips.add(new Slip(SlipType.kPhoneCall, new LocalDateTime(), 10)); slips.add(new Slip(SlipType.kShortMessage, new LocalDateTime(), 15)); slips.add(new Slip(SlipType.kInternet, new LocalDateTime(), 100)); data.put(UserField.kSlips, slips); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(67, 80), calculator.calculate(usage)); } public List<PackageType> getPackages(PackageType... packages) { return Arrays.asList(packages); } @Test public void testVipUserPackage1NoActivity() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 30); data.put(UserField.kPackages, getPackages(PackageType.kVipUserPackage1)); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(100, 0), calculator.calculate(usage)); } @Test public void testVipUserPackage1WithInLimit() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 30); data.put(UserField.kPackages, getPackages(PackageType.kVipUserPackage1)); List<Slip> slips = new ArrayList<Slip>(); slips.add(new Slip(SlipType.kPhoneCall, new LocalDateTime(), 750)); slips.add(new Slip(SlipType.kShortMessage, new LocalDateTime(), 200)); slips.add(new Slip(SlipType.kInternet, new LocalDateTime(), 100 * 1000)); data.put(UserField.kSlips, slips); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(100, 0), calculator.calculate(usage)); } @Test public void testVipUserPackage1OneMoreCall() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 30); data.put(UserField.kPackages, getPackages(PackageType.kVipUserPackage1)); List<Slip> slips = new ArrayList<Slip>(); slips.add(new Slip(SlipType.kPhoneCall, new LocalDateTime(), 751)); slips.add(new Slip(SlipType.kShortMessage, new LocalDateTime(), 200)); slips.add(new Slip(SlipType.kInternet, new LocalDateTime(), 100 * 1000)); data.put(UserField.kSlips, slips); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(100, 30), calculator.calculate(usage)); } @Test public void testVipUserPackage1OneMoreMessage() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 30); data.put(UserField.kPackages, getPackages(PackageType.kVipUserPackage1)); List<Slip> slips = new ArrayList<Slip>(); slips.add(new Slip(SlipType.kPhoneCall, new LocalDateTime(), 750)); slips.add(new Slip(SlipType.kShortMessage, new LocalDateTime(), 201)); slips.add(new Slip(SlipType.kInternet, new LocalDateTime(), 100 * 1000)); data.put(UserField.kSlips, slips); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(100, 10), calculator.calculate(usage)); } @Test public void testVipUserPackage1And50kMore() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 30); data.put(UserField.kPackages, getPackages(PackageType.kVipUserPackage1)); List<Slip> slips = new ArrayList<Slip>(); slips.add(new Slip(SlipType.kPhoneCall, new LocalDateTime(), 750)); slips.add(new Slip(SlipType.kShortMessage, new LocalDateTime(), 200)); slips.add(new Slip(SlipType.kInternet, new LocalDateTime(), 100 * 1000 + 50)); data.put(UserField.kSlips, slips); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(100, 5), calculator.calculate(usage)); } @Test public void testVipUserPackage1AllExceed() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 30); data.put(UserField.kPackages, getPackages(PackageType.kVipUserPackage1)); List<Slip> slips = new ArrayList<Slip>(); slips.add(new Slip(SlipType.kPhoneCall, new LocalDateTime(), 751)); slips.add(new Slip(SlipType.kShortMessage, new LocalDateTime(), 201)); slips.add(new Slip(SlipType.kInternet, new LocalDateTime(), 100 * 1000 + 50)); data.put(UserField.kSlips, slips); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(100, 45), calculator.calculate(usage)); } @Test public void testVipUserPackage2NoActivity() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 30); data.put(UserField.kPackages, getPackages(PackageType.kVipUserPackage2)); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(200, 0), calculator.calculate(usage)); } @Test public void testVipUserPackage2WithInLimit() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 30); data.put(UserField.kPackages, getPackages(PackageType.kVipUserPackage2)); List<Slip> slips = new ArrayList<Slip>(); slips.add(new Slip(SlipType.kPhoneCall, new LocalDateTime(), 2000)); slips.add(new Slip(SlipType.kShortMessage, new LocalDateTime(), 500)); slips.add(new Slip(SlipType.kInternet, new LocalDateTime(), 300 * 1000)); data.put(UserField.kSlips, slips); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(200, 0), calculator.calculate(usage)); } @Test public void testVipUserPackage2More() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 30); data.put(UserField.kPackages, getPackages(PackageType.kVipUserPackage2)); List<Slip> slips = new ArrayList<Slip>(); slips.add(new Slip(SlipType.kPhoneCall, new LocalDateTime(), 2001)); slips.add(new Slip(SlipType.kShortMessage, new LocalDateTime(), 501)); slips.add(new Slip(SlipType.kInternet, new LocalDateTime(), 300 * 1000 + 100)); data.put(UserField.kSlips, slips); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(200, 35), calculator.calculate(usage)); } @Test public void testVipUserNewJoinNoActivities() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 12); data.put(UserField.kIsNewUser, true); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(24, 0), calculator.calculate(usage)); } @Test public void testVipUserNewJoinWithInLimit() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 15); List<Slip> slips = new ArrayList<Slip>(); slips.add(new Slip(SlipType.kPhoneCall, new LocalDateTime(), 200)); slips.add(new Slip(SlipType.kShortMessage, new LocalDateTime(), 200)); slips.add(new Slip(SlipType.kInternet, new LocalDateTime(), 100 * 1000)); data.put(UserField.kSlips, slips); data.put(UserField.kIsNewUser, true); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(30, 0), calculator.calculate(usage)); } @Test public void testVipUserNewJoinMore() { Map<UserField, Object> data = new HashMap<UserField, Object>(); data.put(UserField.kUserType, UserType.kVip); data.put(UserField.kDaysServed, 15); List<Slip> slips = new ArrayList<Slip>(); slips.add(new Slip(SlipType.kPhoneCall, new LocalDateTime(), 201)); slips.add(new Slip(SlipType.kShortMessage, new LocalDateTime(), 201)); slips.add(new Slip(SlipType.kInternet, new LocalDateTime(), 100 * 1000 + 100)); data.put(UserField.kSlips, slips); data.put(UserField.kIsNewUser, true); UserMonthUsage usage = new UserMonthUsage(1, data); assertEquals(Money.get(30, 80), calculator.calculate(usage)); } } <file_sep>/tpc/lib/Acceptor.cc #include "Acceptor.h" #include "InetAddress.h" #include "TcpStream.h" #include <stdio.h> #include <sys/socket.h> Acceptor::Acceptor(const InetAddress& listenAddr) : listenSock_(Socket::createTCP(listenAddr.family())) { listenSock_.setReuseAddr(true); listenSock_.bindOrDie(listenAddr); listenSock_.listenOrDie(); } TcpStreamPtr Acceptor::accept() { // FIXME: use accept4 int sockfd = ::accept(listenSock_.fd(), NULL, NULL); if (sockfd >= 0) { return TcpStreamPtr(new TcpStream(Socket(sockfd))); } else { perror("Acceptor::accept"); return TcpStreamPtr(); } } Socket Acceptor::acceptSocketOrDie() { // FIXME: use accept4 int sockfd = ::accept(listenSock_.fd(), NULL, NULL); if (sockfd >= 0) { return Socket(sockfd); } else { perror("Acceptor::acceptSocketOrDie"); abort(); } } <file_sep>/tpc/bin/sendoob.cc #include "InetAddress.h" #include "Socket.h" #include <string.h> // RFC6093: On the Implementation of the TCP Urgent Mechanism, 2011/01. // Which recommends against the use of urgent mechanism. int main(int argc, char* argv[]) { if (argc < 3) { printf("Usage:\n %s hostname port\n", argv[0]); return 0; } int port = atoi(argv[2]); InetAddress addr; const char* hostname = argv[1]; if (InetAddress::resolve(hostname, port, &addr)) { Socket sock(Socket::createTCP(addr.family())); if (sock.connect(addr) == 0) { const char* buf = "hello"; ssize_t nw = ::send(sock.fd(), buf, strlen(buf), MSG_OOB); printf("sent %zd bytes\n", nw); getchar(); } else { perror("connect"); } } } <file_sep>/java/billing/Money.java package billing; public class Money { public static final long kPipsPerCent = 100; public static final long kCentsPerYuan = 100; public static final long kPipsPerYuan = kPipsPerCent * kCentsPerYuan; public final long pips; public Money(long pips) { this.pips = pips; } public static Money get(int yuan, int cents) { return new Money(yuan * kPipsPerYuan + cents * kPipsPerCent); } public long getCentsRoundDown() { return pips / kPipsPerCent; } public long getCentsRoundUp() { return (pips + kPipsPerCent - 1) / kPipsPerCent; } @Override public boolean equals(Object obj) { if (obj instanceof Money) { Money that = (Money) obj; return pips == that.pips; } else { return false; } } @Override public int hashCode() { return (int) pips; } @Override public String toString() { return Long.toString(pips) + " pips"; } }
168b2238a156a142e5e7f288326c4f08a291e857
[ "Makefile", "Java", "Python", "C", "C++", "Shell" ]
195
C++
haocoder/recipes
8caa231eba9b5006d56801a1cc29e06f2a82e9e7
51acdfffa3e3cae272f965808208fc105f9a1a88
refs/heads/master
<file_sep>import { expect } from "chai"; import { shallowMount } from "@vue/test-utils"; import Header from "@/components/Header.vue"; import Grid from "@/components/Header.vue"; describe("Header.vue", () => { it("renders Header and contains 'BLOG POST' string", () => { const msg = "BLOG POST"; const wrapper = shallowMount(Header, { props: {}, }); expect(wrapper.text()).to.include(msg); }); }); describe("Grid.vue", () => { it("renders the grid", () => { shallowMount(Grid, { props: {}, }); }); });
692869c0708161ed9892945d2c4011e085c09e32
[ "TypeScript" ]
1
TypeScript
husseinTalal2/blog-task
f16ae29cad1d6cee4105351f97028417e75a850c
bf6bdc36736a56e9803c77096226ddc576546707
refs/heads/main
<file_sep>#include "abb.h" #define EXITO 0 #define ERROR -1 #define ERROR_RECORRIDO 0 #define PRIMERO_MAYOR 1 #define PRIMERO_MENOR -1 #define AMBOS_IGUALES 0 nodo_abb_t* crear_nodo_arbol(){ nodo_abb_t* nodo = calloc(1,sizeof(nodo_abb_t)); if(!nodo) return NULL; return nodo; } int crear_raiz(abb_t* arbol,void* elemento){ arbol->nodo_raiz = crear_nodo_arbol(); if( arbol->nodo_raiz ) arbol->nodo_raiz->elemento = elemento; else return ERROR; return EXITO; } abb_t* arbol_crear(abb_comparador comparador, abb_liberar_elemento destructor){ abb_t* arbol = malloc(sizeof(abb_t)); if( !arbol ) return NULL; arbol->comparador = comparador; arbol->destructor = destructor; arbol->nodo_raiz = NULL; return arbol; } nodo_abb_t* insertar( nodo_abb_t* nodo, void* elemento,int (comparador)(void*,void*)){ if( nodo == NULL ){ nodo = crear_nodo_arbol(); nodo->elemento = elemento; if( !nodo ) return NULL; return nodo; } int comparacion = comparador(elemento,nodo->elemento); if( comparacion==PRIMERO_MENOR ) nodo->izquierda = insertar(nodo->izquierda,elemento,comparador); else if( comparacion==PRIMERO_MAYOR ) nodo->derecha = insertar(nodo->derecha,elemento,comparador); else{ nodo_abb_t* nodo_nuevo = crear_nodo_arbol(); nodo_nuevo->elemento = elemento; if( !nodo_nuevo ) return nodo; nodo_nuevo->derecha = nodo->derecha; nodo->derecha = nodo_nuevo; } return nodo; } int arbol_insertar(abb_t* arbol, void* elemento){ if(!arbol) return ERROR; if(!arbol->nodo_raiz) return crear_raiz(arbol,elemento); insertar(arbol->nodo_raiz,elemento,arbol->comparador); if(!arbol_buscar(arbol,elemento)) return ERROR; else return EXITO; } nodo_abb_t* buscar_mayor_de_menores(nodo_abb_t* nodo){ if(!nodo) return NULL; nodo_abb_t* aux = nodo->izquierda; bool encontrado = false; while(aux != NULL && !encontrado){ if( aux->derecha == NULL) encontrado = true; else aux = aux->derecha; } if(encontrado) return aux; else return NULL; } nodo_abb_t* eliminar(nodo_abb_t* nodo,void* elemento,int (comparador)(void*,void*),void (destructor)(void*)){ if(!nodo) return NULL; nodo_abb_t* reemplazo; int comparacion = comparador(elemento,nodo->elemento); if( comparacion == PRIMERO_MENOR ) nodo->izquierda = eliminar(nodo->izquierda,elemento,comparador,destructor); else if( comparacion == PRIMERO_MAYOR ) nodo->derecha = eliminar(nodo->derecha,elemento,comparador,destructor); else if( nodo->izquierda && nodo->derecha ){ void* auxiliar; reemplazo = buscar_mayor_de_menores(nodo); auxiliar = nodo->elemento; nodo->elemento = reemplazo->elemento; reemplazo->elemento = auxiliar; nodo->izquierda = eliminar(nodo->izquierda,reemplazo->elemento,comparador,destructor); }else{ reemplazo = nodo; nodo_abb_t* hijo; if( nodo->izquierda == NULL ) hijo = nodo->derecha; else if( nodo->derecha == NULL ) hijo = nodo->izquierda; else hijo = NULL; destructor(reemplazo->elemento); free( reemplazo ); return hijo; } return nodo; } int arbol_borrar(abb_t* arbol, void* elemento){ if(!arbol) return ERROR; arbol->nodo_raiz = eliminar(arbol->nodo_raiz,elemento,arbol->comparador,arbol->destructor); if(!arbol_buscar(arbol,elemento)) return EXITO; else return ERROR; } nodo_abb_t* buscar(nodo_abb_t* nodo,void* elemento,int (comparador)(void*,void*)){ if(!nodo) return NULL; int comparacion = comparador(elemento,nodo->elemento); if( comparacion == PRIMERO_MENOR) return buscar(nodo->izquierda,elemento,comparador); else if( comparacion == PRIMERO_MAYOR) return buscar(nodo->derecha,elemento,comparador); else return nodo->elemento; } void* arbol_buscar(abb_t* arbol, void* elemento){ if(!arbol) return NULL; return buscar(arbol->nodo_raiz,elemento,arbol->comparador); } void* arbol_raiz(abb_t* arbol){ if(!arbol || !arbol->nodo_raiz) return NULL; return arbol->nodo_raiz->elemento; } bool arbol_vacio(abb_t* arbol){ if(!arbol || !arbol->nodo_raiz) return true; return false; } int inorden_recursivo(nodo_abb_t* nodo, void** array, int tamanio_array,int cantidad){ if( nodo->izquierda ) cantidad = inorden_recursivo(nodo->izquierda,array,tamanio_array,cantidad); if( cantidad < tamanio_array){ array[cantidad] = nodo->elemento; cantidad++; } if(cantidad >= tamanio_array) return cantidad; if( nodo->derecha ) cantidad = inorden_recursivo(nodo->derecha,array,tamanio_array,cantidad); return cantidad; } int arbol_recorrido_inorden(abb_t* arbol, void** array, int tamanio_array){ if(!arbol || !array) return ERROR_RECORRIDO; int cantidad = 0; return inorden_recursivo(arbol->nodo_raiz, array, tamanio_array,cantidad); } int preorden_resursivo(nodo_abb_t* nodo, void** array, int tamanio_array,int cantidad){ if( cantidad < tamanio_array){ array[cantidad] = nodo->elemento; cantidad++; } if(cantidad >= tamanio_array) return cantidad; if( nodo->izquierda ) cantidad = preorden_resursivo(nodo->izquierda,array,tamanio_array,cantidad); if( nodo->derecha ) cantidad = preorden_resursivo(nodo->derecha,array,tamanio_array,cantidad); return cantidad; } int arbol_recorrido_preorden(abb_t* arbol, void** array, int tamanio_array){ if(!arbol || !array) return ERROR_RECORRIDO; int cantidad = 0; return preorden_resursivo(arbol->nodo_raiz, array, tamanio_array,cantidad); } int postorden_recursivo(nodo_abb_t* nodo, void** array, int tamanio_array,int cantidad){ if( nodo->izquierda ) cantidad = postorden_recursivo(nodo->izquierda,array,tamanio_array,cantidad); if( nodo->derecha ) cantidad = postorden_recursivo(nodo->derecha,array,tamanio_array,cantidad); if( cantidad < tamanio_array){ array[cantidad] = nodo->elemento; cantidad++; } return cantidad; } int arbol_recorrido_postorden(abb_t* arbol, void** array, int tamanio_array){ if(!arbol || !array) return ERROR_RECORRIDO; int cantidad = 0; return postorden_recursivo(arbol->nodo_raiz, array, tamanio_array,cantidad); } void destruir_nodo(nodo_abb_t* nodo,void (destructor)(void*)){ if(nodo->izquierda) destruir_nodo(nodo->izquierda,destructor); if(nodo->derecha) destruir_nodo(nodo->derecha,destructor); destructor(nodo->elemento); free(nodo); } void arbol_destruir(abb_t* arbol){ if(!arbol) return; if( arbol->nodo_raiz ) destruir_nodo(arbol->nodo_raiz,arbol->destructor); free(arbol); } bool con_cada_elemento_inorden(nodo_abb_t* nodo,bool (funcion)(void*,void*),void* extra){ if( nodo->izquierda ){ if(con_cada_elemento_inorden(nodo->izquierda,funcion,extra) == true) return true; } if(funcion(nodo->elemento,extra)==true) return true; if( nodo->derecha ){ if(con_cada_elemento_inorden(nodo->derecha,funcion,extra)==true) return true; } return false; } bool con_cada_elemento_preorden(nodo_abb_t* nodo,bool (funcion)(void*,void*),void* extra){ if(funcion(nodo->elemento,extra)==true) return true; if( nodo->izquierda ){ if(con_cada_elemento_preorden(nodo->izquierda,funcion,extra)==true) return true; } if( nodo->derecha ){ if(con_cada_elemento_preorden(nodo->derecha,funcion,extra)==true) return true; } return false; } bool con_cada_elemento_postorden(nodo_abb_t* nodo,bool (funcion)(void*,void*),void* extra){ if( nodo->izquierda ){ if(con_cada_elemento_postorden(nodo->izquierda,funcion,extra)==true) return true; } if( nodo->derecha ){ if(con_cada_elemento_postorden(nodo->derecha,funcion,extra)==true) return true; } if(funcion(nodo->elemento,extra)==true) return true; return false; } void abb_con_cada_elemento(abb_t* arbol, int recorrido, bool (*funcion)(void*, void*), void* extra){ if(!arbol || !funcion) return; if(recorrido == ABB_RECORRER_INORDEN) con_cada_elemento_inorden(arbol->nodo_raiz,funcion,extra); else if( recorrido == ABB_RECORRER_PREORDEN) con_cada_elemento_preorden(arbol->nodo_raiz,funcion,extra); else con_cada_elemento_postorden(arbol->nodo_raiz,funcion,extra); } <file_sep>#include "probador.h" #include "abb.h" #define EXITO 0 #define ERROR -1 #define MAX_DESCRIPCION 60 #define PRIMERO_MAYOR 1 #define PRIMERO_MENOR -1 #define AMBOS_IGUALES 0 bool probar_crear_arbol(abb_t* arbol){ if( arbol->nodo_raiz == NULL) return true; else return false; } bool probar_insertar_raiz(abb_t* arbol){ long elemento = 42; int retorno = arbol_insertar(arbol,(void*)elemento); if(retorno == EXITO && (long)arbol->nodo_raiz->elemento == elemento && arbol->nodo_raiz->derecha == NULL && arbol->nodo_raiz->izquierda == NULL) return true; else return false; } bool probar_insertar_mayor(abb_t* arbol){ long elemento = 62; int retorno = arbol_insertar(arbol,(void*)elemento); if(retorno == EXITO && (long)arbol->nodo_raiz->derecha->elemento == elemento) return true; else return false; } bool probar_insertar_elementos_iguales(abb_t* arbol){ long elemento = 62; int retorno = arbol_insertar(arbol,(void*)elemento); if(retorno == EXITO && (long)arbol->nodo_raiz->derecha->derecha->elemento == elemento){ arbol_borrar(arbol,(void*)elemento); return true; } else return false; } bool probar_borrar_hoja(abb_t* arbol){ arbol_insertar(arbol,(void*)28); arbol_insertar(arbol,(void*)20); arbol_insertar(arbol,(void*)37); long elemento = 20; int retorno = arbol_borrar(arbol,(void*)elemento); if( retorno==EXITO && arbol->nodo_raiz->izquierda->izquierda==NULL) return true; else return false; } bool probar_borrar_con_hijo(abb_t* arbol){ long elemento_uno = 30; long elemento_dos = 40; long elemento_borrado = 28; arbol_insertar(arbol,(void*)elemento_uno); arbol_insertar(arbol,(void*)elemento_dos); int retorno = arbol_borrar(arbol,(void*)elemento_borrado); if(retorno==EXITO && (long)arbol->nodo_raiz->izquierda->elemento==37 && (long)arbol->nodo_raiz->izquierda->derecha->elemento==elemento_dos) return true; else return false; } bool probar_borrar_con_dos_hijos_primero(abb_t* arbol){ long elemento = 41; arbol_insertar(arbol,(void*)elemento); int retorno = arbol_borrar(arbol,(void*)37); if(retorno==EXITO && (long)arbol->nodo_raiz->izquierda->elemento==30 && (long)arbol->nodo_raiz->izquierda->derecha->elemento==40) return true; else return false; } bool probar_borrar_con_dos_hijos(abb_t* arbol){ arbol_insertar(arbol,(void*)55); arbol_insertar(arbol,(void*)50); arbol_insertar(arbol,(void*)60); arbol_insertar(arbol,(void*)58); arbol_insertar(arbol,(void*)65); int retorno = arbol_borrar(arbol,(void*)62); nodo_abb_t* aux = arbol->nodo_raiz->derecha->izquierda; if(retorno == EXITO && (long)aux->elemento==55 && (long)aux->derecha->elemento==58 && (long)arbol->nodo_raiz->derecha->elemento==60) return true; else return false; } bool probar_buscar_existente(abb_t* arbol){ void* elemento = arbol->nodo_raiz->derecha->izquierda->elemento; void* retorno = arbol_buscar(arbol,elemento); if(arbol->comparador(elemento,retorno)==AMBOS_IGUALES) return true; else return false; } bool probar_buscar_inexistente(abb_t* arbol){ long elemento = (long)(arbol->nodo_raiz->derecha->izquierda->elemento)+80; void* retorno = arbol_buscar(arbol,(void*)elemento); if(retorno==NULL) return true; else return false; } bool probar_borrar_raiz(abb_t* arbol){ int retorno = arbol_borrar(arbol,(void*)42); if( retorno==EXITO && (long)arbol->nodo_raiz->elemento == (long)41) return true; else return false; } bool son_iguales(void** array,int elementos[],int cantidad){ size_t i = 0; bool iguales=true; while( i<cantidad && iguales ){ if((long)array[i] != elementos[i]) iguales=false; i++; } return iguales; } void probar_recorrido_inorden(abb_t* arbol,void**array,int tamanio_array,probador_t* probador){ char descripcion[MAX_DESCRIPCION]="Se guardan 5 elementos en un array de manera inorden"; int cantidad = arbol_recorrido_inorden(arbol,array,tamanio_array); int elementos[]={30,40,41,42,50}; if( cantidad==tamanio_array && son_iguales(array,elementos,tamanio_array)) describir_prueba(probador,descripcion,true); else describir_prueba(probador,descripcion,false); return; } void probar_recorrido_preorden(abb_t* arbol,void**array,int tamanio_array,probador_t* probador){ char descripcion[MAX_DESCRIPCION]="Se guardan 5 elementos en un array de manera preorden"; int cantidad = arbol_recorrido_preorden(arbol,array,tamanio_array); int elementos[]={42,30,40,41,60}; if( cantidad==tamanio_array && son_iguales(array,elementos,tamanio_array)) describir_prueba(probador,descripcion,true); else describir_prueba(probador,descripcion,false); return; } void probar_recorrido_postorden(abb_t* arbol,void**array,int tamanio_array,probador_t* probador){ char descripcion[MAX_DESCRIPCION]="Se guardan 5 elementos en un array de manera postorden"; int cantidad = arbol_recorrido_postorden(arbol,array,tamanio_array); int elementos[]={41,40,30,50,58}; if( cantidad==tamanio_array && son_iguales(array,elementos,tamanio_array)) describir_prueba(probador,descripcion,true); else describir_prueba(probador,descripcion,false); return; } void probar(abb_t* arbol,probador_t* probador,bool (*prueba)(abb_t*),char descripcion[MAX_DESCRIPCION]){ bool paso = prueba(arbol); describir_prueba(probador,descripcion,paso); } bool mostrar_elemento(void* elemento, void* extra){ if(elemento){ printf("%li ", (long)elemento); if((long)elemento == (long)extra) return true; } return false; } void probar_con_cada_elemento(abb_t* arbol){ printf("Se imprime todo el arbol inorden, deberia ser: 30 40 41 42 50 55 58 60 65 \n"); abb_con_cada_elemento(arbol, ABB_RECORRER_INORDEN, mostrar_elemento,NULL); printf("\n"); printf("Se imprime todo el arbol preorden, deberia ser: 42 30 40 41 60 55 50 58 65 \n"); abb_con_cada_elemento(arbol, ABB_RECORRER_PREORDEN, mostrar_elemento,NULL); printf("\n"); printf("Se imprime todo el arbol postorden, deberia ser: 41 40 30 50 58 55 65 60 42 \n"); abb_con_cada_elemento(arbol, ABB_RECORRER_POSTORDEN, mostrar_elemento,NULL); printf("\n"); printf("Se imprime el arbol hasta el 42 inorden, deberia ser: 30 40 41 42\n"); abb_con_cada_elemento(arbol, ABB_RECORRER_INORDEN, mostrar_elemento,(void*)42); printf("\n"); printf("Se imprime el arbol hasta el 42 preorden, deberia ser: 42\n"); abb_con_cada_elemento(arbol, ABB_RECORRER_PREORDEN, mostrar_elemento,(void*)42); printf("\n"); printf("Se imprime el arbol hasta el 42 postorden, deberia ser: 41 40 30 50 58 55 65 60 42 \n"); abb_con_cada_elemento(arbol, ABB_RECORRER_POSTORDEN, mostrar_elemento,(void*)42); printf("\n"); } int comparar_elementos(void* elemento_uno,void* elemento_dos){ if((long)elemento_uno>(long)elemento_dos) return PRIMERO_MAYOR; else if((long)elemento_uno<(long)elemento_dos) return PRIMERO_MENOR; else return AMBOS_IGUALES; } void destructor(void* elemento){ return; } void llamar_pruebas(abb_t* arbol,probador_t* probador){ probar(arbol,probador,(&probar_crear_arbol),"Se crea el arbol correctamente"); probar(arbol,probador,(&probar_insertar_raiz),"Se inserta la raiz correctamente"); probar(arbol,probador,(&probar_insertar_mayor),"Se inserta un elemento mayor"); probar(arbol,probador,(&probar_insertar_elementos_iguales),"Se inserta un elemento ya existente"); probar(arbol,probador,(&probar_borrar_hoja),"Se borra una hoja del arbol"); probar(arbol,probador,(&probar_borrar_con_hijo),"Se borra un elemento con un unico hijo"); probar(arbol,probador,(&probar_borrar_con_dos_hijos_primero),"Se borra un elemento con dos hijos y el primer menor no tiene hijos"); probar(arbol,probador,(&probar_borrar_con_dos_hijos),"Se borra un elemento con dos hijos, y se reemplaza por el mayor de los menores"); probar(arbol,probador,(&probar_buscar_existente),"Se busca un elemento del arbol"); probar(arbol,probador,(&probar_buscar_inexistente),"Se busca un elemento que no esta en el arbol"); int tamanio_array = 5; void** array = malloc(sizeof(void**)*(size_t)tamanio_array); if(!array) printf("No se pudieron probar los recorridos\n"); else{ probar_recorrido_inorden(arbol,array,tamanio_array,probador); probar_recorrido_preorden(arbol,array,tamanio_array,probador); probar_recorrido_postorden(arbol,array,tamanio_array,probador); } free(array); probar_con_cada_elemento(arbol); probar(arbol,probador,(&probar_borrar_raiz),"Se borra la raiz del arbol"); } int main(){ probador_t* probador = crear_probador(); if(!probador) return -1; abb_t* arbol = arbol_crear((&comparar_elementos),(&destructor)); llamar_pruebas(arbol,probador); arbol_destruir(arbol); free(probador); }<file_sep># Algo2-Abb Se pide implementar un Arbol Binario de Búsqueda. Para ello se brindan las firmas de las funciones públicas a implementar y se deja a criterio del alumno la creación de las funciones privadas del TDA para el correcto funcionamiento del Arbol cumpliendo con las buenas prácticas de programación. Adicionalmente se pide la implementación de un iterador interno para la estructura. En esta tarea me toco implementar un Arbol Binario de Búsqueda, este es un tipo de dato abstracto, es decir, un tipo de dato definido por una estructura de datos y operaciones,de manera tal que solo conservo la parte más relevante para mi problema (utilizando la abstraccion). Para compilar el programa debemos utilizar la siguiente linea en la terminal: gcc probador.c pruebas.c abb.c -o abb -g -std=c99 -Wall -Wconversion -Wtype-limits -pedantic -Werror -O0 Y para la ejecucion: valgrind --leak-check=full --track-origins=yes --show-reachable=yes ./abb Este tda pertenece a un gran grupo denominado arbol que esta formado por una coleccion de nodos en el cual se tiene a uno de estos nodos como raiz, además, el abb al ser un arbol binario podemos abstraer una idea de izquierda y derecha, pero ademas es tambien un arbol de comparacion por lo tanto los elementos a la derecha de la raiz son mayores a este y los de la izquierda menores. Como operaciones basicas tenemos: crear, destruir, vacio, insertar, eliminar, busqueda y recorrer. Convenciones: mayores a la derecha y menores a la izquierda, Si el elemento a insertar es igual va a la derecha, al eliminar y en caso de necesitarlo se reemplaza por el mayor de los menores. La estructura del arbol tiene un puntero a funcion llamado destruir la cual recibe un puntero comodin (void*) esta funcion permite que el usuario en caso de ser necesario libere el espacio de memoria reservado para el elemento a borrar, si el usuario no tiene la posibilidad de mandar una funcion destruir entonces no puede pedir memoria para su elemento ya que estaria perdiendola. Esto puede suceder cuando se quiere eliminar un elemento, tenemos que llamar al destructor antes de liberar el nodo y tambien es necesario cuando destruimos el arbol. Analisis de las operaciones implementadas en el abb: * arbol_crear: esta funcion tiene una complejidad de O(1), ya que es la complejidad mas grande que tiene la funcion. * arbol_insertar: en esta funcion la complejidad mas grande esta dada por la funcion auxiliar insertar quedando entonces una complejidad de O(log n). (se analiza mas abajo) * arbol_borrar: en esta funcion la complejidad esta dada por la funcion auxiliar eliminar y buscar: T(eliminar)+T(buscar)=Max( O(log n),O(log n) ) = O(log n).En castellano: ambas tienen complejidad O(log n) por lo que queda un O(log n). *arbol_buscar: en esta funcion sucede lo mismo que en insertar y borrar, la funcion auxiliar buscar en la mas compleja y luego del debido analisis(mas abajo) la complejidad queda O(log n). * Análisis para insertar, borrar y buscar: Por teorema maestro---> T(n)= aT(n/b) + F(n). a=1----> cantidad de llamadas recursivas. b=2----> Veces que el problema se divide, en este caso izquierda y derecha. entonces: n elevado al logaritmo en base 2 de 1 es igual a n elevado a la cero---->F(n)=1, quedando por el caso dos: T(n)= O(log n). Esta complejidad O(log n) no siempre se cumple,ya que,existe el caso que mi abb tenga la misma forma que una lista simplemente enlazada y en ese caso las complejidades O(log n) serian entonces O(n) ya que el problema no se podria dividir en 2. *arbol_raiz: O(1), simplemente es una instruccion. *arbol_vacio: O(1), instruccion. *Recorridos inorden,preoorden y postorden la complejidad es de O(n) por que recorren los n elementos. *Para el iterador interno dependera de cuando se corte la iteracion, pero evaluando el peor caso, es decir que se hagan todas las iteraciones tambien tendremos un O(n)
f028ca6974d1514ccb6e7619d9fa12f4d7f800fa
[ "Markdown", "C" ]
3
C
juanchycc/Algo2-Abb
7d48cf2a678086b4b4c6043065ca9011d534a912
5dfe1967e86d27d81f623500d2c981e7544239fb
refs/heads/master
<file_sep>package net.xdclass.xdclass_shiro; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.Factory; import org.junit.Test; /** * 单元测试用例执行顺序 * * @author : lipu * @since : 2020-08-22 15:43 */ public class QuickStartTest5_2 { @Test public void testAuthentication() { //创建Securitymanager工厂,通过配置文件ini创建 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); //将securityManager 设置到当前运行环境中 SecurityUtils.setSecurityManager(securityManager); Subject subject = SecurityUtils.getSubject(); //用户输入的账号密码 UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("xdclass", "123"); subject.login(usernamePasswordToken); System.out.println("认证结果:"+subject.isAuthenticated()); //是否有某个角色 boolean hasRole = subject.hasRole("user"); System.out.println("是否有user角色:"+hasRole); System.out.println("主体名 :"+subject.getPrincipal()); subject.checkRole("admin"); //权限 subject.checkPermission("video:delete"); System.out.println("是否有video:delete的权限:"+subject.isPermitted("video:delete")); subject.logout(); System.out.println("认证结果:"+subject.isAuthenticated()); } } <file_sep>#注意 文件格式必须为ini,编码为ANSI #声明Realm,指定realm类型 jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm #配置数据源 #dataSource=com.mchange.v2.c3p0.ComboPooledDataSource dataSource=com.alibaba.druid.pool.DruidDataSource # mysql-connector-java 5 用的驱动url是 com.mysql.jdbc.Driver, # mysql-connector-java 6 以后用的驱动url是 com.mysql.cj.jdbc.Driver dataSource.driverClassName=com.mysql.cj.jdbc.Driver #避免安全警告 dataSource.url=jdbc:mysql://127.0.0.1:3306/xdclass_shiro?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false dataSource.username=root dataSource.password=<PASSWORD> #指定数据源 jdbcRealm.dataSource=$dataSource #开启查找权限, 默认是false,不会去查找角色对应的权限,坑!!!!! jdbcRealm.permissionsLookupEnabled=true #指定SecurityManager的Realms实现,设置realms,可以有多个,用逗号隔开 securityManager.realms=$jdbcRealm
a6c3f7635b56887a2014fc00b25eeeeea9d6cb00
[ "Java", "INI" ]
2
Java
foxInfly/xdclass_shiro
5f6073c8ad709fcd04eb2015e5e0d1fd72673e4b
4c9ad33a8c3bc7ac9bc851697af5f5d09bfe0a3e
refs/heads/master
<repo_name>umeike/umk<file_sep>/modules/base/umk_allocator.h #ifndef __UMK_ALLOCATOR_H__ #define __UMK_ALLOCATOR_H__ #include "umk_type.h" struct umk_allocator_t; typedef void * (*umk_allocator_alloc_func)(struct umk_allocator_t * allocator, umk_uint64 size); typedef void * (*umk_allocator_realloc_func)(struct umk_allocator_t * allocator, void * mem_ptr, umk_uint64 size); typedef void (*umk_allocator_free_func)(struct umk_allocator_t * allocator, void * mem_ptr); typedef struct umk_allocator_t { void * ctx; umk_allocator_alloc_func alloc; umk_allocator_realloc_func realloc; umk_allocator_free_func free; } umk_allocator_t; extern void * umk_allocator_alloc_ext(umk_allocator_t * allocator, umk_uint64 size, umk_char * file, umk_uint32 line); extern void * umk_allocator_realloc_ext(umk_allocator_t * allocator, void * mem_ptr, umk_uint64 size, umk_char * file, umk_uint32 line); extern void umk_allocator_free_ext(umk_allocator_t * allocator, void * mem_ptr, umk_char * file, umk_uint32 line); #define umk_allocator_alloc(allocator, size) umk_allocator_alloc_ext(allocator, size, __FILE__, __LINE__) #define umk_allocator_realloc(allocator, mem_ptr, size) umk_allocator_realloc_ext(allocator, mem_ptr, size, __FILE__, __LINE__) #define umk_allocator_free(allocator, mem_ptr) umk_allocator_free_ext(allocator, mem_ptr, __FILE__, __LINE__) #endif /*__UMK_ALLOCATOR_H__*/ <file_sep>/modules/base/umk_process.h #ifndef __UMK_PROCESS_H__ #define __UMK_PROCESS_H__ #endif /*__UMK_PROCESS_H__*/ <file_sep>/modules/base/umk_option.h #ifndef __UMK_OPTION_H__ #define __UMK_OPTION_H__ #include "umk_node.h" #define umk_option_type "umk_option_t" typedef struct umk_option_t umk_option_t; extern umk_option_t * umk_option_alloc(umk_allocator_t * allocator); #endif /*__UMK_OPTION_H__*/ <file_sep>/tests/umk_app_test.c #include "umk_app.h" int main(int argc, char * argv[]) { if (!umk_app_init(argc, argv)) { return 1; } umk_app_t * app = umk_app_get_instance(); if (!umk_app_deinit()) { return 1; } return 0; } <file_sep>/modules/base/umk_select.c #include "umk_select.h" struct umk_select_t { umk_node_t node; umk_io_pool_i io_pool; }; static umk_int32 umk_select_open(umk_io_pool_i * io_pool) { return 0; } static umk_int32 umk_select_add(umk_io_pool_i * io_pool, umk_io_event_i * io_event) { return 0; } static umk_int32 umk_select_del(umk_io_pool_i * io_pool, umk_io_event_i * io_event) { return 0; } static umk_int32 umk_select_wait(umk_io_pool_i * io_pool, umk_int32 timeout) { return 0; } static umk_int32 umk_select_close(umk_io_pool_i * io_pool) { return 0; } static void umk_select_dealloc(void * user_data) { } umk_select_t * umk_select_alloc(umk_allocator_t * allocator) { umk_node_t * parent; umk_select_t * thiz = umk_null; parent = umk_node_alloc(allocator); if (parent) { thiz = umk_allocator_alloc(allocator, sizeof(umk_select_t)); if (thiz) { umk_node_init((umk_node_t*)thiz, umk_select_type, umk_select_dealloc); umk_node_extends((umk_node_t*)thiz, parent); thiz->io_pool.open = umk_select_open; thiz->io_pool.add = umk_select_add; thiz->io_pool.del = umk_select_del; thiz->io_pool.wait = umk_select_wait; thiz->io_pool.close = umk_select_close; thiz->io_pool.node.imp = (umk_node_t*)thiz; umk_node_implements((umk_node_t*)thiz, (umk_node_i*)&thiz->io_pool); } else { umk_node_free(parent); } } return thiz; } <file_sep>/tests/main.c #include <stdlib.h> #include <stdio.h> #define DEBUG #include "umk_type.h" #include "umk_string.h" #include "umk_log.h" #include "umk_allocator_default.h" #include "umk_application.h" #include "umk_context.h" static void echo(void) { umk_log_debug("size_t: %lu\n", sizeof(size_t)); umk_log_debug("umk_uint64: %lu\n", sizeof(umk_uint64)); umk_log_debug("umk_uint32: %lu\n", sizeof(umk_uint32)); umk_log_debug("umk_uint16: %lu\n", sizeof(umk_uint16)); umk_log_debug("umk_uint8: %lu\n", sizeof(umk_uint8)); umk_log_debug("umk_bool: %lu\n", sizeof(umk_bool)); } int main (int argc, char * argv[]) { echo(); umk_allocator_t * allocator = umk_allocator_default_get_allocator(); // umk_string_t * string = umk_string_alloc(allocator); // umk_string_with_string(string, "hello world\n", umk_string_mode_const); // printf("%s", umk_string_get_string(string)); // umk_node_free((umk_node_t*)string); umk_application_t * app = umk_application_alloc(allocator, argc, argv); umk_context_t * context = umk_context_alloc(allocator); umk_node_free((umk_node_t*)context); umk_node_free((umk_node_t*)app); return 0; } <file_sep>/modules/base/umk_tcp_connection.h #ifndef __UMK_TCP_CONNECTION_H__ #define __UMK_TCP_CONNECTION_H__ #define umk_tcp_connection_type "umk_tcp_connection_t" typedef struct umk_tcp_connection_t umk_tcp_connection_t; #endif /*__UMK_TCP_CONNECTION_H__*/ <file_sep>/modules/base/umk_map.c #include "umk_map.h" #include "umk_hash.h" #include "umk_string.h" struct umk_map_ele_t { umk_char * key; umk_uint32 code; void * value; }; struct umk_map_t { umk_node_t node; umk_uint32 max; umk_uint32 count; umk_array_t * buckets; }; static void umk_map_dealloc(void * user_data) { } umk_map_t * umk_map_alloc(umk_allocator_t * allocator, umk_uint32 max) { umk_node_t * parent = umk_node_alloc(allocator); umk_map_t * thiz = umk_null; if (parent) { thiz = umk_allocator_alloc(allocator, sizeof(umk_map_t)); if (thiz) { umk_node_init((umk_node_t*)thiz, umk_map_type, umk_map_dealloc); umk_node_extends((umk_node_t*)thiz, parent); thiz->max = max; thiz->count = 0; thiz->buckets = umk_array_alloc(allocator, max, umk_null); } else { umk_node_free(parent); } } return thiz; } umk_int32 umk_map_set(umk_map_t * thiz, umk_char * key, void * value) { umk_uint32 hash_code = umk_hash_str(key); umk_int32 index = hash_code % thiz->max; umk_array_t * bucket = umk_array_get_value(thiz->buckets, index); umk_array_push(bucket, value); return 0; } static umk_bool umk_map_ele_cmp(struct umk_map_ele_t * ele, void * user_data) { if (0 == umk_str_cmp(ele->key, user_data)) return umk_true; return umk_false; } void * umk_map_get(umk_map_t * thiz, umk_char * key) { umk_uint32 hash_code = umk_hash_str(key); umk_int32 index = hash_code % thiz->max; umk_array_t * bucket = umk_array_get_value(thiz->buckets, index); return umk_array_get(bucket, (umk_array_ele_cmp_func)umk_map_ele_cmp, key); } umk_array_t * umk_map_keys(umk_map_t * thiz) { return umk_null; } <file_sep>/Makefile req_ver = 3.81 result = $(filter $(req_ver),$(firstword $(sort $(req_ver) $(MAKE_VERSION)))) ifeq (,$(result)) $(error make version $(MAKE_VERSION) not supported, use at least $(req_ver)) endif UMK_ROOT = $(shell pwd) UMK_MAKE = make UMK_ROOT=$(UMK_ROOT) #vpath %.h $(foreach MODULE,$(UMK_MODULES),$(MODULE)) #vpath %.c $(foreach MODULE,$(UMK_MODULES),$($(MODULE)_src)) UMK_OS := $(shell uname -s | sed -e s/SunOS/solaris/ -e s/CYGWIN.*/cygwin/ \ | tr "[A-Z]" "[a-z]") #ifeq (WIN,$(UMK_HOST)) #UMK_OBJS = $(subst /,\,$(UMK_MODULES_O) #else #UMK_OBJS = $(UMK_MODULES_O) #endif .PHONY : all clean module test all: clean prepare module test @echo do finish ... echo: @echo $(UMK_OS) clean: @echo cleaning ... @if [ -d "$(UMK_ROOT)/bin" ]; then $(UMK_RM) $(UMK_ROOT)/bin; fi @if [ -d $(UMK_ROOT)/include ]; then $(UMK_RM) $(UMK_ROOT)/include; fi @if [ -d "$(UMK_ROOT)/lib" ]; then $(UMK_RM) $(UMK_ROOT)/lib; fi @cd modules && $(UMK_MAKE) clean @cd tests && $(UMK_MAKE) clean prepare: @if [ ! -d $(UMK_ROOT)/bin ]; then mkdir $(UMK_ROOT)/bin; fi @if [ ! -d $(UMK_ROOT)/include ]; then mkdir $(UMK_ROOT)/include; fi @if [ ! -d $(UMK_ROOT)/lib ]; then mkdir $(UMK_ROOT)/lib; fi module: prepare @cd modules; $(UMK_MAKE) test: prepare @cd tests; $(UMK_MAKE) <file_sep>/modules/base/umk_context.h #ifndef __UMK_CONTEXT_H__ #define __UMK_CONTEXT_H__ #include "umk_application.h" #define umk_context_type "umk_context_t" typedef struct umk_context_t umk_context_t; extern umk_context_t * umk_context_alloc(umk_allocator_t * allocator, umk_application_t * application); extern umk_application_t * umk_context_get_application(umk_context_t * thiz); #endif /*__UMK_CONTEXT_H__*/ <file_sep>/modules/base/umk_array.h #ifndef __UMK_ARRAY_H__ #define __UMK_ARRAY_H__ #include "umk_node.h" #define umk_array_type "umk_array_t" typedef struct umk_array_t umk_array_t; typedef void (*umk_array_ele_clean_func)(void * ele); typedef umk_bool (*umk_array_ele_cmp_func)(void * ele, void * user_data); extern umk_array_t * umk_array_alloc(umk_allocator_t * allocator, umk_uint32 max, umk_array_ele_clean_func clean); extern umk_int32 umk_array_count(umk_array_t * thiz); extern umk_int32 umk_array_push(umk_array_t * thiz, void * value); extern void * umk_array_pop(umk_array_t * thiz); extern umk_int32 umk_array_set_value(umk_array_t * thiz, umk_uint32 index, void * value); extern void * umk_array_get(umk_array_t * thiz, umk_array_ele_cmp_func cmp, void * user_data); extern void * umk_array_get_value(umk_array_t * thiz, umk_uint32 index); extern umk_int32 umk_array_get_index(umk_array_t * thiz, void * value); #endif /*__UMK_ARRAY_H__*/ <file_sep>/modules/base/umk_file.c #include "umk_file.h" <file_sep>/modules/base/umk_log.c #include <stdio.h> #include "umk_log.h" static void umk_log_default_print(umk_log_level_t level, umk_char * msg) { switch (level) { case umk_log_level_error: break; case umk_log_level_warn: break; case umk_log_level_debug: break; case umk_log_level_info: break; case umk_log_level_all: default: break; } printf("%s\n", msg); } static umk_logger_t umk_logger = umk_log_default_print; void umk_log_set_logger(umk_logger_t logger) { umk_logger = logger; } void umk_log(umk_log_level_t level, umk_char * fmt, ...) { umk_char buffer[umk_log_buffer_size] = {0x00}; va_list ap; va_start(ap, fmt); vsnprintf(buffer, sizeof(buffer), fmt, ap); va_end(ap); umk_logger(level, buffer); }<file_sep>/modules/base/umk_ctx.c #include "umk_ctx.h" umk_ctx_t * umk_ctx_new(const umk_mem_t * const mem, const umk_log_t * const log) { if (!mem || !log) return umk_null; umk_ctx_t * ctx = mem->alloc(sizeof(umk_ctx_t)); if (ctx) { ctx->mem = mem; ctx->log = log; } return ctx; } umk_bool umk_ctx_delete(umk_ctx_t * const ctx) { if (!ctx) return umk_false; const umk_mem_t * mem = ctx->mem; mem->free(ctx); return umk_true; } <file_sep>/modules/base/umk_string.c #include <math.h> #include "umk_string.h" #if 0 typedef struct umk_string_t { umk_node_t node; umk_string_mode_t mode; umk_uint64 length; umk_char * string; } umk_string_t; static void umk_string_dealloc(void * user_data) { umk_string_t * thiz = user_data; if (thiz->mode == umk_string_mode_default) { umk_allocator_free(umk_node_get_allocator(&thiz->node), thiz->string); } } umk_string_t * umk_string_alloc(umk_allocator_t * allocator) { umk_string_t * thiz = umk_null; umk_node_t * parent = umk_node_alloc(allocator); if (parent) { thiz = umk_allocator_alloc(allocator, sizeof(umk_string_t)); if (thiz) { umk_node_init((umk_node_t*)thiz, umk_string_type, umk_string_dealloc); umk_node_extends((umk_node_t*)thiz, parent); umk_node_retain(parent); } umk_node_free(parent); } return thiz; } umk_string_t * umk_string_init_with_string(umk_string_t * thiz, umk_char * string, umk_string_mode_t mode) { thiz->mode = mode; switch (mode) { case umk_string_mode_default: thiz->length = strlen(string); thiz->string = umk_allocator_alloc(umk_node_get_allocator(&thiz->node), thiz->length + 1); if (!thiz->string) thiz->length = 0; break; case umk_string_mode_const: thiz->length = strlen(string); thiz->string = string; break; } return thiz; } //static umk_uint64 umk_string_len(va_list list) //{ // //} umk_string_t * umk_string_init_with_format(umk_string_t * thiz, umk_char * fmt, ...) { #define ch_is_digital(ch) (((ch) >= '0') && (ch) <= '9') if (thiz && fmt) { umk_bool percent_flag = umk_false; umk_bool align_flag = umk_false; umk_bool a_flag = umk_false; umk_bool b_flag = umk_false; umk_int32 a_len = 0; umk_int32 b_len = 0; umk_uint64 len = 0; va_list ap; va_start(ap, fmt); for (umk_char * ptr = fmt; *ptr != '\0'; ptr += 1) { printf("ch = %c\n", *ptr); if (percent_flag && ch_is_digital(*ptr)) { umk_char tmp[24] = {0x00}; umk_int32 i = 0; while (ch_is_digital(*ptr)) { tmp[i++] = *ptr++; } a_flag = umk_true; a_len = atoi(tmp); if (*ptr != '.') { continue; } i = 0; memset(tmp, 0x00, sizeof(tmp)); while (ch_is_digital(*ptr)) { tmp[i++] = *ptr++; } b_flag = umk_true; b_len = atoi(tmp); } switch (*ptr) { case '%': if (percent_flag) { percent_flag = umk_false; len += 1; } else { percent_flag = umk_true; } break; case 's': len += strlen(va_arg(ap, umk_char*)); percent_flag = umk_false; align_flag = umk_false; break; case 'd': va_arg(ap, umk_int32); len += sizeof(umk_int32); percent_flag = umk_false; align_flag = umk_false; break; case 'o': percent_flag = umk_false; align_flag = umk_false; break; case 'x': percent_flag = umk_false; align_flag = umk_false; break; case 'c': va_arg(ap, umk_int32); len += 1; percent_flag = umk_false; align_flag = umk_false; break; case 'f': percent_flag = umk_false; align_flag = umk_false; break; case '-': if (percent_flag) { align_flag = umk_true; } else { align_flag = umk_false; len += 1; } break; default: len += 1; break; } //p_flag = umk_false; } va_end(ap); printf("len = %llu\n", len); percent_flag = umk_false; thiz->mode = umk_string_mode_default; thiz->string = umk_allocator_alloc(umk_node_get_allocator((umk_node_t*)thiz), len + 1); thiz->length = len; // va_list ap; va_start(ap, fmt); for (umk_char * ptr = fmt, *str = thiz->string; *ptr != '\0'; ptr += 1) { if (*ptr == '%') { percent_flag = umk_true; continue; } if (percent_flag && *ptr == '%') { percent_flag = umk_false; *str = '%'; continue; } switch (*ptr) { case 's': for (umk_char * tmp = va_arg(ap, umk_char*); *tmp != '\0'; tmp += 1, str += 1) { *str = *tmp; } break; case 'd': va_arg(ap, umk_int32); break; case 'c': *str++ = va_arg(ap, umk_int32); break; default: *str++ = *ptr; break; } percent_flag = umk_false; } va_end(ap); } return thiz; } umk_uint64 umk_string_lenght(umk_string_t * thiz) { if (thiz) { return thiz->length; } return 0; } umk_char * umk_string_origin(umk_string_t * thiz) { if (thiz) { return thiz->string; } return umk_null; } #endif void * umk_mem_copy(void * dst_mem_ptr, const void * src_mem_ptr, umk_uint32 size) { if (dst_mem_ptr && src_mem_ptr && size > 0) { return memcpy(dst_mem_ptr, src_mem_ptr, size); } else { return umk_null; } } void * umk_mem_set(void * mem_ptr, umk_int32 value, umk_uint32 size) { if (mem_ptr && size > 0) { return memset(mem_ptr, value, size); } else { return umk_null; } } umk_int32 umk_str_len(umk_char * str) { if (!str) return -1; umk_int32 len = 0; while (str && *str != '\0') { len += 1; } return len; } umk_char * umk_str_cpy(umk_char * dst, const umk_char * src) { if (!dst || !src) return umk_null; while (dst && src && *src != '\0') { *dst = *src; dst += 1; src += 1; } return dst; } umk_int32 umk_str_cmp(const umk_char * str1, const umk_char * str2) { if (!str1 || !str2) return -2; while (str1 && str2 && *str1 != '\0' && *str2 != '\0') { if (*str1 < *str2) { return -1; } else if (*str1 > *str2) { return 1; } str1 += 1; str2 += 1; } if (str1 && *str1 != '\0') return 1; if (str2 && *str2 != '\0') return -1; return 0; } <file_sep>/modules/base/umk_io_pool.h #ifndef __UMK_IO_POOL_H__ #define __UMK_IO_POOL_H__ #include "umk_io_event.h" #define umk_io_pool_interface "umk_io_pool_i" typedef struct umk_io_pool_i { umk_node_i node; umk_int32 (*open)(struct umk_io_pool_i * thiz); umk_int32 (*add)(struct umk_io_pool_i * thiz, umk_io_event_i * io_event); umk_int32 (*del)(struct umk_io_pool_i * thiz, umk_io_event_i * io_event); umk_int32 (*wait)(struct umk_io_pool_i * thiz, umk_int32 timeout); umk_int32 (*close)(struct umk_io_pool_i * thiz); } umk_io_pool_i; #define umk_io_pool_type "umk_io_pool_t" typedef struct umk_io_pool_t umk_io_pool_t; extern umk_io_pool_t * umk_io_pool_alloc(umk_allocator_t * allocator, umk_io_pool_i * imp); extern umk_int32 umk_io_pool_open(umk_io_pool_t * thiz); extern umk_int32 umk_io_pool_add(umk_io_pool_t * thiz, umk_io_event_i * io_event); extern umk_int32 umk_io_pool_del(umk_io_pool_t * thiz, umk_io_event_i * io_event); extern umk_int32 umk_io_pool_wait(umk_io_pool_t * thiz,umk_int32 timeout); extern umk_int32 umk_io_pool_close(umk_io_pool_t * thiz); #endif /*__UMK_IO_POOL_H__*/ <file_sep>/modules/base/umk_log.h #ifndef __UMK_LOG_H__ #define __UMK_LOG_H__ #include <stdarg.h> #include "umk_type.h" #define umk_log_buffer_size 1024 typedef enum umk_log_level_t { umk_log_level_error, umk_log_level_warn, umk_log_level_debug, umk_log_level_info, umk_log_level_all } umk_log_level_t; typedef void (*umk_logger_t)(umk_log_level_t level, umk_char * msg); extern void umk_log_set_logger(umk_logger_t logger); extern void umk_log(umk_log_level_t level, umk_char * fmt, ...); #ifdef DEBUG #define umk_log_error(fmt,...) umk_log(umk_log_level_error, fmt, __VA_ARGS__) #define umk_log_warn(fmt,...) umk_log(umk_log_level_warn, fmt, __VA_ARGS__) #define umk_log_debug(fmt,...) umk_log(umk_log_level_debug, fmt, __VA_ARGS__) #define umk_log_info(fmt,...) umk_log(umk_log_level_info, fmt, __VA_ARGS__) #else #define umk_log_error(fmt,...) #define umk_log_warn(fmt,...) #define umk_log_debug(fmt,...) #define umk_log_info(fmt,...) #endif typedef struct umk_log_t { } umk_log_t; #endif /*__UMK_LOG_H__*/ <file_sep>/modules/base/umk_node.c #include "umk_string.h" #include "umk_node.h" typedef struct umk_node_imp_t { umk_node_t node; umk_allocator_t * allocator; umk_uint32 ref_count; umk_node_i * interfaces; } umk_node_imp_t; umk_node_t * umk_node_alloc(umk_allocator_t * allocator) { umk_node_imp_t * imp = umk_allocator_alloc(allocator, sizeof(umk_node_imp_t)); if (imp) { umk_node_init((umk_node_t*)imp, umk_node_type, umk_null); imp->allocator = allocator; imp->ref_count = 1; } return (umk_node_t*)imp; } void umk_node_init(umk_node_t * node, umk_char * type, umk_node_dealloc_func dealloc) { node->type = type; node->dealloc = dealloc; } void umk_node_free(umk_node_t * node) { if (!node) return; umk_node_t * tmp = node; while (tmp->parent) { tmp = tmp->parent; } umk_node_imp_t * imp = (umk_node_imp_t*)tmp; imp->ref_count -= 1; if (imp->ref_count == 0) { tmp = node; while (tmp) { node = tmp->parent; if (tmp->dealloc) { tmp->dealloc(tmp); } umk_allocator_free(imp->allocator, tmp); tmp = node; } } } umk_node_t * umk_node_retain(umk_node_t * node) { if (node) { umk_node_t * tmp = node; while (tmp->parent) { tmp = tmp->parent; } umk_node_imp_t * imp = (umk_node_imp_t*)tmp; imp->ref_count += 1; } return node; } void umk_node_extends(umk_node_t * node, umk_node_t * parent) { parent->child = node; node->parent = parent; } umk_node_t * umk_node_instance_cast(umk_node_t * node, umk_char * type) { umk_return_value_if_failed(node && type, umk_null); while (node) { if (node->type == type || umk_str_cmp(type, node->type) == 0) { return node; } else { node = node->parent; } } return node; } void umk_node_implements(umk_node_t * node, umk_char * type, umk_node_i * imp) { umk_node_i * i = (umk_node_i*)imp; i->type = type; i->imp = node; umk_node_t * tmp = node; while (tmp->parent) { tmp = tmp->parent; } umk_node_imp_t * thiz = (umk_node_imp_t*)tmp; imp->next = thiz->interfaces; thiz->interfaces = imp; } umk_node_t * umk_node_interface_cast(umk_node_t * node, umk_char * type) { umk_node_t * tmp = node; while (tmp->parent) { tmp = tmp->parent; } umk_node_imp_t * thiz = (umk_node_imp_t*)tmp; umk_node_i * interfaces = thiz->interfaces; while (interfaces) { if (type == interfaces->type || strcmp(type, interfaces->type) == 0) { break; } } return interfaces ? interfaces->imp : umk_null; } umk_allocator_t * umk_node_get_allocator(umk_node_t * node) { if (node) { umk_node_t * tmp = node; while (tmp->parent) { tmp = tmp->parent; } umk_node_imp_t * imp = (umk_node_imp_t*)tmp; return imp->allocator; } else { return umk_null; } } <file_sep>/modules/base/umk_type.h #ifndef __UMK_TYPE_H__ #define __UMK_TYPE_H__ /* umk_char */ typedef char umk_char; /* umk_int8 */ typedef signed char umk_int8; /* umk_uint8 */ typedef unsigned char umk_uint8; /* umk_int16 */ typedef signed short umk_int16; /* umk_uint16 */ typedef unsigned short umk_uint16; /* umk_int32 */ typedef signed int umk_int32; /* umk_uint32 */ typedef unsigned int umk_uint32; /* umk_int64 */ typedef signed long long umk_int64; /* umk_uint64 */ typedef unsigned long long umk_uint64; /* umk_bool */ typedef unsigned char umk_bool; #define umk_true 0x01 #define umk_false 0x00 #define umk_null (void*)0 #define umk_return_if_failed(e) do { if (!(e)) return; } while(0) #define umk_return_value_if_failed(e, v) do { if (!(e)) return (v); } while(0) #endif /*__UMK_TYPE_H__*/ <file_sep>/modules/base/umk_io_pool.c #include "umk_io_pool.h" struct umk_io_pool_t { umk_node_t node; umk_io_pool_i * imp; }; static void umk_io_pool_dealloc(void * user_data) { umk_io_pool_t * io_pool = (umk_io_pool_t*)user_data; umk_node_free((umk_node_t*)io_pool); } umk_io_pool_t * umk_io_pool_alloc(umk_allocator_t * allocator, umk_io_pool_i * imp) { umk_node_t * parent; umk_io_pool_t * thiz = umk_null; parent = umk_node_alloc(allocator); if (parent) { thiz = umk_allocator_alloc(allocator, sizeof(umk_io_pool_t)); if (thiz) { umk_node_init((umk_node_t*)thiz, umk_io_pool_type, umk_io_pool_dealloc); umk_node_extends((umk_node_t*)thiz, parent); thiz->imp = imp; } else { umk_node_free(parent); } } return thiz; } umk_int32 umk_io_pool_open(umk_io_pool_t * thiz) { umk_io_pool_i * imp = thiz->imp; return imp->open(imp); } umk_int32 umk_io_pool_add(umk_io_pool_t * thiz, umk_io_event_i * io_event) { umk_io_pool_i * imp = thiz->imp; return imp->add(imp, io_event); } umk_int32 umk_io_pool_del(umk_io_pool_t * thiz, umk_io_event_i * io_event) { umk_io_pool_i * imp = thiz->imp; return imp->del(imp, io_event); } umk_int32 umk_io_pool_wait(umk_io_pool_t * thiz, umk_int32 timeout) { umk_io_pool_i * imp = thiz->imp; return imp->wait(imp, timeout); } umk_int32 umk_io_pool_close(umk_io_pool_t * thiz) { umk_io_pool_i * imp = thiz->imp; return imp->close(imp); } <file_sep>/modules/base/umk_tcp_connection.c #include "umk_tcp_connection.h" <file_sep>/modules/base/umk_thread.h #ifndef __UMK_THREAD_H__ #define __UMK_THREAD_H__ #define umk_thread_type "umk_thread_t" typedef struct umk_thread_t umk_thread_t; #endif /*__UMK_THREAD_H__*/ <file_sep>/modules/base/umk_allocator.c #include <stdlib.h> #include "umk_allocator.h" void * umk_allocator_alloc_ext(umk_allocator_t * allocator, umk_uint64 size, umk_char * file, umk_uint32 line) { if (allocator && size > 0) { return allocator->alloc(allocator, size); } return umk_null; } void * umk_allocator_realloc_ext(umk_allocator_t * allocator, void * mem_ptr, umk_uint64 size, umk_char * file, umk_uint32 line) { if (allocator && size > 0) { return allocator->realloc(allocator, mem_ptr, size); } return umk_null; } void umk_allocator_free_ext(umk_allocator_t * allocator, void * mem_ptr, umk_char * file, umk_uint32 line) { if (allocator && mem_ptr) { allocator->free(allocator, mem_ptr); } } <file_sep>/modules/base/umk_ctx.h #ifndef __umk_ctx_h__ #define __umk_ctx_h__ #include "umk_mem.h" #include "umk_log.h" typedef struct { const struct umk_mem_t * mem; const struct umk_log_t * log; const struct umk_app_t * app; } umk_ctx_t; extern umk_ctx_t * umk_ctx_new(const umk_mem_t * const mem, const umk_log_t * const log); extern umk_bool umk_ctx_delete(umk_ctx_t * const ctx); static inline const struct umk_mem_t * umk_ctx_get_mem(const umk_ctx_t * const ctx) { return ctx->mem; } static inline const struct umk_log_t * umk_ctx_get_log(const umk_ctx_t * const ctx) { return ctx->log; } #endif /*__umk_ctx_h__*/ <file_sep>/modules/base/umk_allocator_default.c #include <stdlib.h> #include <string.h> #include "umk_allocator_default.h" typedef struct umk_mem_note_t { umk_uint64 size; } umk_mem_node_t; static void * umk_allocator_default_alloc(umk_allocator_t * allocator, umk_uint64 size) { void * mem_ptr = malloc(sizeof(umk_mem_node_t) + size); if (mem_ptr) { memset(mem_ptr, 0x00, sizeof(umk_mem_node_t) + size); umk_mem_node_t * node = (umk_mem_node_t*)mem_ptr; node->size = size; return mem_ptr + sizeof(umk_mem_node_t); } return mem_ptr; } static void * umk_allocator_default_realloc(umk_allocator_t * allocator, void * mem_ptr, umk_uint64 size) { void * new_mem_ptr = malloc(size); if (new_mem_ptr) { memcpy(new_mem_ptr, mem_ptr, size); free(mem_ptr - sizeof(umk_mem_node_t)); } return new_mem_ptr; } static void umk_allocator_default_free(umk_allocator_t * allocator, void * mem_ptr) { if (mem_ptr) { free(mem_ptr - sizeof(umk_mem_node_t)); } } static const umk_allocator_t umk_allocator_default = { umk_null, umk_allocator_default_alloc, umk_allocator_default_realloc, umk_allocator_default_free }; umk_allocator_t * umk_allocator_default_get_allocator(void) { return (umk_allocator_t *)&umk_allocator_default; } <file_sep>/modules/base/umk_tcp_s.c #include "umk_tcp_s.h" //#include "winsock.h" //#pragma comment(lib, "WS2_32.lib") struct umk_tcp_s_t { umk_node_t node; umk_char * host; umk_uint16 port; umk_int32 fd; }; static void umk_tcp_s_dealloc(void * user_data) { } umk_tcp_s_t * umk_tcp_s_alloc(umk_allocator_t * allocator, umk_char * host, umk_uint16 port) { umk_node_t * parent = umk_node_alloc(allocator); umk_tcp_s_t * thiz = umk_null; if (parent) { thiz = umk_allocator_alloc(allocator, sizeof(umk_tcp_s_t)); if (thiz) { umk_node_init((umk_node_t*)thiz, umk_tcp_s_type, umk_tcp_s_dealloc); umk_node_extends((umk_node_t*)thiz, parent); thiz->host = host; thiz->port = port; } else { umk_node_free(parent); } } return thiz; } #if 0 umk_int32 umk_tcp_s_open(umk_tcp_s_t * thiz, umk_uint32 num) { umk_int32 ret; ret = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (ret < 0) { return -1; } thiz->fd = ret; struct sockaddr addr = {0x00}; int addr_len = 0; ret = bind(thiz->fd, &addr, addr_len); if (ret) { goto end; } ret = listen(thiz->fd, num); if (ret) { goto end; } return 0; end: close(thiz->fd); return -1; } umk_tcp_connection_t * umk_tcp_s_new_connection(umk_tcp_s_t * thiz) { return umk_null; } #endif umk_int32 umk_tcp_s_close(umk_tcp_s_t * thiz) { return 0; } <file_sep>/modules/base/umk_module.c #include "umk_module.h" umk_module_t * umk_module_new(umk_ctx_t * ctx) { const umk_mem_t * mem = umk_ctx_get_mem(ctx); umk_module_t * module = umk_mem_alloc(mem, sizeof(umk_module_t)); if (module) { module->ctx = ctx; } return module; } umk_bool umk_module_load(umk_module_t * module) { return umk_true; } void umk_module_delete(umk_module_t * module) { const umk_ctx_t * ctx = module->ctx; const umk_mem_t * mem = umk_ctx_get_mem(ctx); umk_mem_free(mem, module); } <file_sep>/modules/base/umk_app.c #include "umk_app.h" umk_app_t * umk_app_new(umk_ctx_t * const ctx) { const umk_mem_t * mem = umk_ctx_get_mem(ctx); umk_app_t * app = umk_mem_alloc(mem, sizeof(umk_app_t)); if (app) { app->ctx = ctx; } return app; } umk_bool umk_app_parse(umk_app_t * const app, umk_int32 argc, umk_char * argv[]) { return umk_true; } void umk_app_delete(umk_app_t * app) { const umk_ctx_t * ctx = app->ctx; const umk_mem_t * mem = umk_ctx_get_mem(ctx); umk_mem_free(mem, app); //umk_ctx_delete(ctx); } <file_sep>/modules/base/umk_buffer.c #include "umk_buffer.h" typedef struct umk_buffer_t { umk_node_t node; } umk_buffer_t; static void umk_buffer_dealloc(void * user_data) { } umk_buffer_t * umk_buffer_alloc(umk_allocator_t * allocator) { umk_buffer_t * thiz = umk_null; umk_node_t * parent = umk_node_alloc(allocator); if (parent) { thiz = umk_allocator_alloc(allocator, sizeof(umk_buffer_t)); if (thiz) { umk_node_init((umk_node_t*)thiz, umk_buffer_type, umk_buffer_dealloc); umk_node_extends((umk_node_t*)thiz, parent); } else { umk_node_free(parent); } } return thiz; }<file_sep>/modules/base/umk_mem.c #include <stdlib.h> #include <string.h> #include "umk_mem.h" static void * _umk_mem_alloc_(umk_uint32 size) { void * ptr = malloc(size); if (ptr) memset(ptr, 0x00, size); return ptr; } static void * _umk_mem_realloc_(void * ptr, umk_uint32 size) { return realloc(ptr, size); } static void _umk_mem_free_(void * ptr) { free(ptr); } static umk_mem_t umk_mem_default = { _umk_mem_alloc_, _umk_mem_realloc_, _umk_mem_free_ }; umk_mem_t * umk_mem_get_default(void) { return &umk_mem_default; } <file_sep>/modules/base/umk_option.c #include "umk_option.h" <file_sep>/modules/base/umk_mem.h #ifndef __umk_mem_h__ #define __umk_mem_h__ #include "umk_type.h" typedef struct umk_mem_t { void * (*alloc)(umk_uint32 size); void * (*realloc)(void * ptr, umk_uint32 size); void (*free)(void * ptr); } umk_mem_t; inline void * umk_mem_alloc(const umk_mem_t * const mem, umk_uint32 size) { return mem->alloc(size); } inline void * umk_mem_realloc(const umk_mem_t * const mem, void * ptr, umk_uint32 size) { return mem->realloc(ptr, size); } inline void umk_mem_free(const umk_mem_t * const mem, void * ptr) { return mem->free(ptr); } #endif /*__umk_mem_h__*/ <file_sep>/modules/base/umk_app.h #ifndef __umk_app_h__ #define __umk_app_h__ #include "umk_ctx.h" typedef struct umk_app_t { const umk_ctx_t * ctx; } umk_app_t; extern umk_app_t * umk_app_new(umk_ctx_t * ctx); extern umk_bool umk_app_parse(umk_app_t * app, umk_int32 argc, umk_char * argv[]); extern void umk_app_delete(umk_app_t * app); #endif /*__umk_app_h__*/ <file_sep>/modules/base/umk_thread.c #include "umk_thread.h" <file_sep>/modules/base/umk_map.h #ifndef __UMK_MAP_H__ #define __UMK_MAP_H__ #include "umk_node.h" #include "umk_array.h" #define umk_map_type "umk_map_t" typedef struct umk_map_t umk_map_t; extern umk_map_t * umk_map_alloc(umk_allocator_t * allocator, umk_uint32 max); extern umk_int32 umk_map_set(umk_map_t * thiz, umk_char * key,void * value); extern void * umk_map_get(umk_map_t * thiz, umk_char * key); extern umk_array_t * umk_map_keys(umk_map_t * thiz); #endif /*__UMK_MAP_H__*/ <file_sep>/tests/alloc_test.c #include <stdio.h> //#undef DEBUG #include "umk_type.h" #include "umk_allocator_default.h" #include "umk_allocator.h" #include "umk_string.h" #include "umk_log.h" int main (int argc, char * argv[]) { umk_allocator_t * allocator = umk_allocator_default_get_allocator(); void * data = umk_allocator_alloc(allocator, 20); umk_allocator_free(allocator, data); umk_string_t * hello = umk_string_alloc(allocator); // umk_string_with_format(hello, "He%s,W%s", "llo", "orld"); // printf("%s\n", umk_string_origin(hello)); umk_node_free((umk_node_t*)hello); // printf("hello world\n"); umk_log_debug("size_t: %lu\n", sizeof(size_t)); umk_log_debug("umk_uint64: %lu\n", sizeof(umk_uint64)); umk_log_debug("umk_uint32: %lu\n", sizeof(umk_uint32)); umk_log_debug("umk_uint16: %lu\n", sizeof(umk_uint16)); umk_log_debug("umk_uint8: %lu\n", sizeof(umk_uint8)); umk_log_debug("umk_bool: %lu\n", sizeof(umk_bool)); }<file_sep>/modules/base/umk_io.h #ifndef __UMK_IO_H__ #define __UMK_IO_H__ #include "umk_node.h" #define umk_io_interface "umk_io_i" typedef umk_int32 (*umk_io_open_func)(); typedef umk_int32 (*umk_io_read_func)(); typedef umk_int32 (*umk_io_write_func)(); typedef umk_int32 (*umk_io_close_func)(); typedef struct { umk_node_i node; umk_io_open_func open; umk_io_read_func read; umk_io_write_func write; umk_io_close_func close; } umk_io_i; #define umk_io_type "umk_io_t" typedef struct umk_io_t umk_io_t; extern umk_io_t * umk_io_alloc(umk_allocator_t * allocator, umk_io_i * imp); extern umk_int32 umk_io_open(umk_io_t * thiz); extern umk_int32 umk_io_read(umk_io_t * thiz); extern umk_int32 umk_io_write(umk_io_t * thiz); extern umk_int32 umk_io_close(umk_io_t * thiz); #endif /*__UMK_IO_H__*/ <file_sep>/modules/base/umk_application.h #ifndef __UMK_APPLICATION_H__ #define __UMK_APPLICATION_H__ #include "umk_node.h" #define umk_application_type "umk_application_t" typedef struct umk_application_t umk_application_t; extern umk_application_t * umk_application_alloc(umk_allocator_t * allocator, umk_int32 argc, umk_char * argv[]); #endif /*__UMK_APPLICATION_H__*/ <file_sep>/modules/base/umk_file.h #ifndef __UMK_FILE_H__ #define __UMK_FILE_H__ #include "umk_ctx.h" typedef struct umk_file_t { const umk_ctx_t * ctx; } umk_file_t; extern umk_file_t * umk_file_new(umk_ctx_t * ctx); extern void umk_file_delete(umk_file_t * file); #endif /*__UMK_FILE_H__*/ <file_sep>/modules/base/umk_buffer.h #ifndef __UMK_BUFFER_H__ #define __UMK_BUFFER_H__ #include "umk_node.h" #define umk_buffer_type "umk_buffer_t" typedef struct umk_buffer_t umk_buffer_t; extern umk_buffer_t * umk_buffer_alloc(umk_allocator_t * allocator); #endif <file_sep>/modules/base/umk_io.c #include "umk_io.h" struct umk_io_t { umk_node_t node; umk_io_i * imp; }; static void umk_io_dealloc(void * user_data) { umk_io_t * io = (umk_io_t*)user_data; umk_node_free((umk_node_t*)io); } umk_io_t * umk_io_alloc(umk_allocator_t * allocator, umk_io_i * imp) { umk_node_t * parent; umk_io_t * thiz = umk_null; parent = umk_node_alloc(allocator); if (parent) { thiz = umk_allocator_alloc(allocator, sizeof(umk_io_t)); if (thiz) { umk_node_init((umk_node_t*)thiz, umk_io_type, umk_io_dealloc); umk_node_extends((umk_node_t*)thiz, parent); thiz->imp = imp; } else { umk_node_free(parent); } } return thiz; } umk_int32 umk_io_open(umk_io_t * thiz) { umk_io_i * imp = thiz->imp; return imp->open(imp); } umk_int32 umk_io_read(umk_io_t * thiz) { umk_io_i * imp = thiz->imp; return imp->read(imp); } umk_int32 umk_io_write(umk_io_t * thiz) { umk_io_i * imp = thiz->imp; return imp->write(imp); } umk_int32 umk_io_close(umk_io_t * thiz) { umk_io_i * imp = thiz->imp; return imp->close(imp); } <file_sep>/modules/base/umk_poll.c #include "umk_poll.h" struct umk_poll_t { umk_node_t node; umk_io_pool_i io_pool; }; static umk_int32 umk_poll_open(umk_io_pool_i * io_pool) { return 0; } static umk_int32 umk_poll_add(umk_io_pool_i * io_pool, umk_io_event_i * io_event) { return 0; } static umk_int32 umk_poll_del(umk_io_pool_i * io_pool, umk_io_event_i * io_event) { return 0; } static umk_int32 umk_poll_wait(umk_io_pool_i * io_pool, umk_int32 timeout) { return 0; } static umk_int32 umk_poll_close(umk_io_pool_i * io_pool) { return 0; } static void umk_poll_dealloc(void * user_data) { } umk_poll_t * umk_poll_alloc(umk_allocator_t * allocator) { umk_node_t * parent; umk_poll_t * thiz = umk_null; parent = umk_node_alloc(allocator); if (parent) { thiz = umk_allocator_alloc(allocator, sizeof(umk_poll_t)); if (thiz) { umk_node_init((umk_node_t*)thiz, umk_poll_type, umk_poll_dealloc); umk_node_extends((umk_node_t*)thiz, parent); thiz->io_pool.open = umk_poll_open; thiz->io_pool.add = umk_poll_add; thiz->io_pool.del = umk_poll_del; thiz->io_pool.wait = umk_poll_wait; thiz->io_pool.close = umk_poll_close; thiz->io_pool.node.imp = (umk_node_t*)thiz; umk_node_implements((umk_node_t*)thiz, (umk_node_i*)&thiz->io_pool); } else { umk_node_free(parent); } } return thiz; } <file_sep>/modules/base/umk_io_event.h #ifndef __UMK_IO_EVENT_H__ #define __UMK_IO_EVENT_H__ #include "umk_node.h" typedef enum umk_io_event_e { umk_io_event_error, umk_io_event_read, umk_io_event_write, umk_io_event_close } umk_io_event_e; #define umk_io_event_interface "umk_io_event_i" typedef struct umk_io_event_i { umk_node_i node; umk_int32 (*get_fd)(struct umk_io_event_i * thiz); void (*handle)(struct umk_io_event_i * io_event, umk_io_event_e event); } umk_io_event_i; #define umk_io_event_type "umk_io_event_t" typedef struct umk_io_event_t umk_io_event_t; extern umk_io_event_t * umk_io_event_alloc(umk_allocator_t * allocator, umk_io_event_i * imp); extern umk_int32 umk_io_event_get_fd(umk_io_event_i * io_event); extern void umk_io_event_handle(umk_io_event_i * io_event, umk_io_event_e event); #endif /*__UMK_IO_EVENT_H__*/ <file_sep>/modules/base/umk_array.c #include "umk_array.h" struct umk_array_t { umk_node_t node; umk_uint32 max; umk_uint32 count; void ** data; umk_array_ele_clean_func clean; }; static void umk_array_dealloc(void * user_data) { umk_array_t * thiz = user_data; for (umk_int32 index = 0; thiz->clean && index < thiz->count; index++) { thiz->clean(thiz->data[index]); } umk_allocator_free(umk_node_get_allocator(user_data), thiz->data); } umk_array_t * umk_array_alloc(umk_allocator_t * allocator, umk_uint32 max, umk_array_ele_clean_func clean) { umk_node_t * parent = umk_node_alloc(allocator); umk_array_t * thiz = umk_null; parent = umk_node_alloc(allocator); if (parent) { thiz = umk_allocator_alloc(allocator, sizeof(umk_array_t)); if (thiz) { umk_node_init((umk_node_t*)thiz, umk_array_type, umk_array_dealloc); umk_node_extends((umk_node_t*)thiz, parent); thiz->max = max; thiz->count = 0; thiz->data = umk_allocator_alloc(allocator, sizeof(void*) * max); thiz->clean = clean; } else { umk_node_free(parent); } } return umk_null; } umk_int32 umk_array_count(umk_array_t * thiz) { if (!thiz) return -1; return thiz->count; } umk_int32 umk_array_push(umk_array_t * thiz, void * value) { if (thiz->count >= thiz->count) return -1; umk_int32 index = thiz->count; thiz->data[index] = value; thiz->count++; return index; } void * umk_array_pop(umk_array_t * thiz) { if (thiz->count == 0) return umk_null; thiz->count -= 1; return thiz->data[thiz->count]; } umk_int32 umk_array_set_value(umk_array_t * thiz, umk_uint32 index, void * value) { if (index >= thiz->count) return -1; thiz->data[index] = value; return 0; } void * umk_array_get(umk_array_t * thiz, umk_array_ele_cmp_func cmp, void * user_data) { if (!thiz || !cmp) return umk_null; for (umk_int32 index = 0; index < thiz->count; index++) { if (cmp(thiz->data[index], user_data)) { return thiz->data[index]; } } return umk_null; } void * umk_array_get_value(umk_array_t * thiz, umk_uint32 index) { if (!thiz) return umk_null; if (index >= thiz->count) return umk_null; return thiz->data[index]; } umk_int32 umk_array_get_index(umk_array_t * thiz, void * value) { if (!value) return -1; for (umk_int32 index = 0; index < thiz->count; index++) { if (thiz->data[index] == value) { return index; } } return -1; } <file_sep>/modules/base/umk_allocator_default.h #ifndef __UMK_ALLOCATOR_DEFAULT_H__ #define __UMK_ALLOCATOR_DEFAULT_H__ #include "umk_allocator.h" extern umk_allocator_t * umk_allocator_default_get_allocator(void); #endif /*__UMK_ALLOCATOR_DEFAULT_H__*/ <file_sep>/modules/base/umk_select.h #ifndef __UMK_SELECT_H__ #define __UMK_SELECT_H__ #include "umk_io_pool.h" #define umk_select_type "umk_select_t" typedef struct umk_select_t umk_select_t; extern umk_select_t * umk_select_alloc(umk_allocator_t * allocator); #endif /*__UMK_SELECT_H__*/ <file_sep>/modules/base/umk_tcp_s.h #ifndef __UMK_SOCKET_H__ #define __UMK_SOCKET_H__ #include "umk_node.h" #define umk_tcp_s_type "umk_tcp_s_t" typedef struct umk_tcp_s_t umk_tcp_s_t; #endif /*__UMK_SOCKET_H__*/ <file_sep>/modules/base/linux/umk_epoll.c #include <errno.h> #include <sys/epoll.h> #include <unistd.h> #include "umk_log.h" #include "umk_epoll.h" struct umk_epoll_t { umk_node_t node; umk_io_pool_i io_pool; umk_int32 efd; }; static umk_int32 umk_epoll_open(umk_io_pool_i * io_pool) { umk_epoll_t * thiz = (umk_epoll_t*)io_pool->node.imp; umk_int32 ret = 0; ret = epoll_create1(0); if (ret == -1) { umk_log_error("epoll_create1 failed: %s", strerror(errno)); return -1; } thiz->efd = ret; return 0; } static umk_int32 umk_epoll_add(umk_io_pool_i * io_pool, umk_io_event_i * io_event) { umk_epoll_t * thiz = (umk_epoll_t*)io_pool->node.imp; umk_int32 ret = 0; if (!thiz || -1 == thiz->efd) return -1; struct epoll_event ev; umk_int32 fd = umk_io_event_get_fd(io_event); ev.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLERR | EPOLLHUP | EPOLLET | EPOLLRDHUP | EPOLLONESHOT; //ev.data.fd = fd; ev.data.ptr = io_event; ret = epoll_ctl(thiz->efd, EPOLL_CTL_ADD, fd, &ev); if (ret == -1) { umk_log_error("epoll_ctl add failed: %s", strerror(errno)); return -1; } return 0; } static umk_int32 umk_epoll_del(umk_io_pool_i * io_pool, umk_io_event_i * io_event) { umk_epoll_t * thiz = (umk_epoll_t*)io_pool->node.imp; umk_int32 ret = 0; if (!thiz || -1 == thiz->efd) return -1; struct epoll_event ev; umk_int32 fd = umk_io_event_get_fd(io_event); ev.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLERR | EPOLLHUP | EPOLLET | EPOLLRDHUP | EPOLLONESHOT; //ev.data.fd = fd; ev.data.ptr = io_event; ret = epoll_ctl(thiz->efd, EPOLL_CTL_DEL, fd, &ev); if (ret == -1) { umk_log_error("epoll_ctl del failed: %s", strerror(errno)); return -1; } return 0; } static umk_int32 umk_epoll_wait(umk_io_pool_i * io_pool, umk_int32 timeout) { umk_epoll_t * thiz = (umk_epoll_t*)io_pool->node.imp; umk_int32 ret = 0; if (!thiz || -1 == thiz->efd) return -1; struct epoll_event evs[100] = {{0x00,},}; ret = epoll_wait(thiz->efd, evs, 100, timeout); if (ret == -1) { umk_log_error("epoll_wait failed: %s", strerror(errno)); return -1; } if (ret > 0) { for (umk_int32 i = 0; i < ret; i++) { umk_log_debug("events: %d", evs[i].events); umk_io_event_i * io_event = evs[i].data.ptr; umk_io_event_e event; if (evs[i].events & EPOLLIN) { event = umk_io_event_read; } umk_io_event_handle(io_event, event); } } return 0; } static umk_int32 umk_epoll_close(umk_io_pool_i * io_pool) { umk_epoll_t * thiz = (umk_epoll_t*)io_pool->node.imp; if (!thiz || -1 == thiz->efd) return -1; umk_int32 ret = 0; ret = close(thiz->efd); if (ret == -1) { umk_log_error("epoll close failed: %s", strerror(errno)); return -1; } return 0; } static void umk_epoll_dealloc(void * user_data) { } umk_epoll_t * umk_epoll_alloc(umk_allocator_t * allocator) { umk_node_t * parent; umk_epoll_t * thiz = umk_null; parent = umk_node_alloc(allocator); if (parent) { thiz = umk_allocator_alloc(allocator, sizeof(umk_epoll_t)); if (thiz) { umk_node_init((umk_node_t*)thiz, umk_epoll_type, umk_epoll_dealloc); umk_node_extends((umk_node_t*)thiz, parent); thiz->io_pool.open = umk_epoll_open; thiz->io_pool.add = umk_epoll_add; thiz->io_pool.del = umk_epoll_del; thiz->io_pool.wait = umk_epoll_wait; thiz->io_pool.close = umk_epoll_close; umk_node_implements((umk_node_t*)thiz, umk_io_pool_interface, (umk_node_i*)&thiz->io_pool); thiz->efd = -1; } else { umk_node_free(parent); } } return thiz; } <file_sep>/modules/base/umk_string.h #ifndef __UMK_STRING_H__ #define __UMK_STRING_H__ #include <string.h> #include <stdarg.h> #include "umk_type.h" #if 0 #define umk_string_type "umk_string_t" typedef enum umk_string_mode_t { umk_string_mode_default, umk_string_mode_const } umk_string_mode_t; typedef struct umk_string_t umk_string_t; extern umk_string_t * umk_string_alloc(umk_allocator_t * allocator); extern umk_string_t * umk_string_init_with_string(umk_string_t * thiz, umk_char * string, umk_string_mode_t mode); extern umk_string_t * umk_string_init_with_format(umk_string_t * thiz, umk_char * fmt, ...); extern umk_uint64 umk_string_lenght(umk_string_t * thiz); extern umk_char * umk_string_origin(umk_string_t * thiz); #endif /* memory */ extern void * umk_mem_copy(void * dst_mem_ptr, const void * src_mem_ptr, umk_uint32 size); extern void * umk_mem_set(void * mem_ptr, umk_int32 value, umk_uint32 size); extern umk_int32 umk_str_len(umk_char * str); extern umk_char * umk_str_cpy(umk_char * dst, const umk_char * src); extern umk_int32 umk_str_cmp(const umk_char * str1, const umk_char * str2); #endif /*__UMK_STRING_H__*/ <file_sep>/modules/base/linux/umk_epoll.h #ifndef __UMK_EPOLL_H__ #define __UMK_EPOLL_H__ #include "umk_io_pool.h" #define umk_epoll_type "umk_epoll_t" typedef struct umk_epoll_t umk_epoll_t; extern umk_epoll_t * umk_epoll_alloc(umk_allocator_t * allocator); #endif /*__UMK_EPOLL_H__*/ <file_sep>/modules/Makefile .PHONY : all clean include $(UMK_ROOT)/Makefile.conf UMK_MODULES ?= base UMK_MODULES_O := $(foreach FILE,$(foreach MODULE,$(UMK_MODULES),$(wildcard $(MODULE)/*.c)),$(FILE:.c=.o)) UMK_MODULES_H := $(foreach MODULE,$(UMK_MODULES),$(wildcard $(MODULE)/*.h)) UMK_CFLAGS += $(foreach MODULE,$(UMK_MODULES),-I$(MODULE)) #UMK_LDFLAGS = -O2 -L$(UMK_LIB_PATH) -lws2_32 -lwsock32 ifeq ($(UMK_OS),darwin) UMK_MODULES_O += $(foreach FILE,$(foreach MODULE,$(UMK_MODULES),$(wildcard $(MODULE)/darwin/*.c)),$(FILE:.c=.o)) UMK_MODULES_H += $(foreach MODULE,$(UMK_MODULES),$(wildcard $(MODULE)/darwin/*.h)) else UMK_MODULES_O += $(foreach FILE,$(foreach MODULE,$(UMK_MODULES),$(wildcard $(MODULE)/linux/*.c)),$(FILE:.c=.o)) UMK_MODULES_H += $(foreach MODULE,$(UMK_MODULES),$(wildcard $(MODULE)/linux/*.h)) endif all: $(UMK_MODULES_O) @$(UMK_AR) crs $(UMK_ROOT)/lib/libumk.a $(UMK_MODULES_O) @cp -a $(UMK_MODULES_H) $(UMK_ROOT)/include clean: @echo $(UMK_OS) @echo do cleaning ... -@$(UMK_RM) $(UMK_MODULES_O) <file_sep>/modules/base/umk_module.h #ifndef __umk_module_h__ #define __umk_module_h__ #include "umk_ctx.h" typedef struct { const umk_ctx_t * ctx; } umk_module_t; extern umk_module_t * umk_module_new(umk_ctx_t * ctx); extern umk_bool umk_module_load(umk_module_t * module); extern void umk_module_delete(umk_module_t * module); #endif /*__umk_module_h__*/ <file_sep>/tests/Makefile include $(UMK_ROOT)/Makefile.conf all: $(UMK_CC) main.c -o test -I$(UMK_ROOT)/include -L$(UMK_ROOT)/lib -lumk clean: @echo do cleaning ... <file_sep>/modules/base/umk_hash.c #include "umk_hash.h" umk_uint64 umk_hash_addr(void * addr) { return (umk_uint64)addr; } umk_uint32 umk_hash_str(umk_char * str) {/*elf_hash*/ umk_uint32 hash = 0; umk_uint32 x = 0; while (*str) { hash = (hash << 4) + (*str++); if ((x = hash & 0xF0000000L) != 0) { hash ^= (x >> 24); hash &= ~x; } } return (hash & 0x7FFFFFFF); } <file_sep>/modules/base/umk_context.c #include "umk_context.h" struct umk_context_t { umk_node_t node; umk_application_t * application; }; static void umk_context_dealloc(void * user_data) { } void umk_context_init(umk_context_t * thiz) { } umk_context_t * umk_context_alloc(umk_allocator_t * allocator, umk_application_t * application) { #if 1 umk_node_t * parent = umk_node_alloc(allocator); umk_context_t * thiz = umk_null; if (parent) { thiz = umk_allocator_alloc(allocator, sizeof(umk_context_t)); if (thiz) { umk_node_init((umk_node_t*)thiz, umk_context_type, umk_context_dealloc); umk_node_extends((umk_node_t*)thiz, parent); thiz->application = application; } else { umk_node_free(parent); } } #else umk_context_t * thiz; umk_class(umk_context_t, umk_context_init, umk_context_dealloc); #endif return thiz; } umk_application_t * umk_context_get_application(umk_context_t * thiz) { return thiz->application; } <file_sep>/modules/base/umk_node.h #ifndef __UMK_NODE_H__ #define __UMK_NODE_H__ #include "umk_allocator.h" typedef struct umk_node_i { struct umk_node_i * next; umk_char * type; struct umk_node_t * imp; } umk_node_i; typedef void (*umk_node_dealloc_func)(void * user_data); typedef struct umk_node_t { struct umk_node_t * parent; struct umk_node_t * child; umk_char * type; umk_node_dealloc_func dealloc; } umk_node_t; #define umk_node_type "umk_node_t" extern umk_node_t * umk_node_alloc(umk_allocator_t * allocator); extern void umk_node_init(umk_node_t * node, umk_char * type, umk_node_dealloc_func dealloc); extern void umk_node_free(umk_node_t * node); extern umk_node_t * umk_node_retain(umk_node_t * node); extern void umk_node_extends(umk_node_t * node, umk_node_t * parent); extern umk_node_t * umk_node_instance_cast(umk_node_t * node, umk_char * type); extern void umk_node_implements(umk_node_t * node, umk_char * type, umk_node_i * imp); extern umk_node_t * umk_node_interface_cast(umk_node_t * node, umk_char * type); extern umk_allocator_t * umk_node_get_allocator(umk_node_t * node); #endif /*__UMK_NODE_H__*/ <file_sep>/modules/base/umk_io_event.c #include "umk_io_event.h" struct umk_io_event_t { umk_node_t node; umk_int32 fd; void * user_data; }; static void umk_io_event_dealloc(void * user_data) { } umk_io_event_t * umk_io_event_alloc(umk_allocator_t * allocator, umk_io_event_i * imp) { umk_node_t * parent; umk_io_event_t * thiz = umk_null; parent = umk_node_alloc(allocator); if (parent) { thiz = umk_allocator_alloc(allocator, sizeof(umk_io_event_t)); if (thiz) { umk_node_init((umk_node_t*)thiz, umk_io_event_type, umk_io_event_dealloc); umk_node_extends((umk_node_t*)thiz, parent); } else { umk_node_free(parent); } } return thiz; } umk_int32 umk_io_event_get_fd(umk_io_event_i * io_event) { return io_event->get_fd(io_event); } void umk_io_event_handle(umk_io_event_i * io_event, umk_io_event_e event) { return io_event->handle(io_event, event); } <file_sep>/modules/base/umk_process.c #include "umk_process.h" <file_sep>/modules/base/umk_hash.h #ifndef __UMK_HASH_H__ #define __UMK_HASH_H__ #include "umk_type.h" extern umk_uint64 umk_hash_addr(void * addr); extern umk_uint32 umk_hash_str(umk_char * str); #endif /*__UMK_HASH_H__*/ <file_sep>/README.md umk === <file_sep>/modules/base/umk_application.c #include "umk_application.h" struct umk_application_t { umk_node_t node; umk_int32 argc; umk_char ** argv; umk_char * root_path; }; static void umk_application_dealloc(void * user_data) { } static void umk_application_init(umk_application_t * thiz) { // thiz->root_path = getcwd(NULL, 0); } umk_application_t * umk_application_alloc(umk_allocator_t * allocator, umk_int32 argc, umk_char * argv[]) { umk_node_t * parent = umk_node_alloc(allocator); umk_application_t * thiz = umk_null; if (parent) { thiz = umk_allocator_alloc(allocator, sizeof(umk_application_t)); if (thiz) { umk_node_init((umk_node_t*)thiz, umk_application_type, umk_application_dealloc); umk_node_extends((umk_node_t*)thiz, parent); thiz->argc = argc; thiz->argv = argv; umk_application_init(thiz); } else { umk_node_free(parent); } } return thiz; } <file_sep>/modules/base/umk_poll.h #ifndef __UMK_POLL_H__ #define __UMK_POLL_H__ #include "umk_io_pool.h" #define umk_poll_type "umk_poll_t" typedef struct umk_poll_t umk_poll_t; extern umk_poll_t * umk_poll_alloc(umk_allocator_t * allocator); #endif /*__UMK_POLL_H__*/
c5599bad063def42f03b2b1c2c7c45a722d076a4
[ "Markdown", "C", "Makefile" ]
62
C
umeike/umk
8fa00481a032590f95f21156f036285caa6899e7
83fa41b8657b29b6c63c8988f621f47766a4b70a
refs/heads/main
<repo_name>jeromedeporres/digitEngin<file_sep>/Models/equipements.php <?php class equipements { public $id_equipements = 0; public $nomequipements = ''; private $db = null; public function __construct() { $this->db = dataBase::getInstance(); } public function checkEquipementsExist(){ $checkEquipementsExist = $this->db->prepare( 'SELECT COUNT(`nomEquipements`) AS `isEquipementsExist` FROM `equipements` WHERE `nomEquipements` = :nomEquipements' ); $checkEquipementsExist->bindvalue(':nomEquipements', $this->nomEquipements, PDO::PARAM_STR); $checkEquipementsExist->execute(); return $checkEquipementsExist->fetch(PDO::FETCH_OBJ)->isEquipementsExist; } public function getEquipements(){ $getEquipements = $this->db->prepare( 'SELECT `id_equipements`, `nomEquipements` FROM `equipements`;' ); $getEquipements->execute(); return $getEquipements->fetchAll(PDO::FETCH_OBJ); } public function checkIdEquipementsExist(){ $checkIdEquipementsExist = $this->db->prepare( 'SELECT COUNT(`id_equipements`) AS `isEquipementsExist` FROM `equipements` WHERE `id_equipements` = :id_equipements' ); $checkIdEquipementsExistQuery->bindvalue(':id_equipements', $this->id_equipements, PDO::PARAM_INT); $checkIdEquipementsExistQuery->execute(); $data = $checkIdEquipementsExistQuery->fetch(PDO::FETCH_OBJ); return $data->isEquipementsExist; } public function addEquipements(){ try { $addEquipementsQuery = $this->db->prepare( 'INSERT INTO `equipements` (`nomEquipements`) VALUES (:nomEquipements);' ); $addEquipementsQuery->bindvalue(':nomEquipements', $this->nomEquipements, PDO::PARAM_STR); return $addEquipementsQuery->execute(); return true; } catch (\Throwable $th) { return false; echo $th->getMessage(); } } public function getEquipementsInfo() { $getEquipementsInfoQuery = $this->db->prepare( 'SELECT `id_equipements`, `nomEquipements` FROM `equipements` WHERE `id_equipements` = :id_equipements ' ); $getEquipementsInfoQuery->bindValue(':id_equipements', $this->id_equipements, PDO::PARAM_INT); $getEquipementsInfoQuery->execute(); return $getEquipementsInfoQuery->fetch(PDO::FETCH_OBJ); } public function modifyEquipements(){ $modifyEquipementsQuery = $this->db->prepare( 'UPDATE `equipements` SET `nomEquipements` = :nomEquipements WHERE `id_equipements` = :id_equipements' ); $modifyEquipementsQuery->bindValue(':nomEquipements', $this->nomEquipements, PDO::PARAM_STR); $modifyEquipementsQuery->bindValue(':id_equipements', $this->id_equipements, PDO::PARAM_INT); return $modifyEquipementsQuery->execute(); } public function deleteEquipements() { $deleteEquipementsQuery = $this->db->prepare( 'DELETE FROM `equipements` WHERE `id_equipements` = :id_equipements' ); $deleteEquipementsQuery->bindValue(':id_equipements', $this->id_equipements, PDO::PARAM_INT); return $deleteEquipementsQuery->execute(); } }<file_sep>/modifEquipements.php <?php include 'header.php'; include_once './Models/equipements.php'; include './Controllers/ctrlModifEquipements.php'; ?> <div class="btnModif text-center"> <a class="btn btn-outline-primary btn-sm" href="index.php"><i class="fas fa-home fa-2x"></i> Accueil</a> <!-- Btn CRUD --> <a class="btn btn-outline-primary btn-sm" href="tableauDeBord.php"><i class="fas fa-tachometer-alt fa-2x"></i> Tableau De Bord</a> <a class="btn btn-outline-primary btn-sm" href="listeEquipements.php"><i class="far fa-building fa-2x"></i> Liste des Equipements</a> </div> <!-- Titre Formulaire --> <h1 class="text-center" id="titreModif">Modifier un Equipement</h1> <div class="formModif"><?php if(isset($equipements)){ ?> <form action="modifEquipements.php?&id_equipements=<?= $equipements->id_equipements ?>" method="POST"> <div class="form-group"> <div> <!--message d'erreur/succés--> <?php if(isset($modifyMessageFail)){ ?> <div class="alert alert-danger alert-dismissible fade show" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <?= $modifyMessageFail ?> </div> <?php } if(isset($modifyMessageSuccess)){ ?> <div class="alert alert-success alert-dismissible fade show" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <?= $modifyMessageSuccess ?> </div> <?php } ?> <label for="nomEquipements">Nom de l'equipement :</label> <input oninput="this.value = this.value.toUpperCase()" id="nomEquipements" class="form-control <?= count($formErrors) > 0 ? (isset($formErrors['nomEquipements']) ? 'is-invalid' : 'is-valid') : '' ?>" value="<?= isset($_POST['nomEquipements']) ? $_POST['nomEquipements'] : $equipements->nomEquipements ?>" type="text" name="nomEquipements" /> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['nomEquipements']) ? $formErrors['nomEquipements'] : '' ?></p> </div> <input type="submit" class="btn btn-primary btn-sm" name="modify" value="Valider"></input> <button type="reset" class="btn btn-warning btn-sm">Réinitialiser</button> </form><?php } ?> </div> <?php include './footer.php';<file_sep>/Controllers/ctrlIndex.php <?php //Choix de la vue à afficher et configuration du titre if(isset($_GET['view'])){ if($_GET['view'] == 'register'){ $view = 'register'; $title = REGISTER_TITLE; }else if($_GET['view'] == 'connexion'){ $view = 'connexion'; $title = LOGIN_TITLE; } } <file_sep>/Models/clients.php <?php class clients { public $id_Clients = 0; public $nomClients = ''; private $db = null; public function __construct(){ $this->db = dataBase::getInstance(); } public function checkClientExist(){ $checkClientExist = $this->db->prepare( 'SELECT * FROM `clients` WHERE `nomClients` = :nomClients' ); $checkClientExist->bindvalue(':nomClients', $this->nomClients, PDO::PARAM_STR); $checkClientExist->execute(); return $checkClientExist->fetch(PDO::FETCH_OBJ); } public function getClients(){ $getClient = $this->db->prepare( 'SELECT `id_Clients`, `nomClients` FROM `clients`;' ); $getClient->execute(); return $getClient->fetchAll(PDO::FETCH_OBJ); } public function getClient(){ $getClient = $this->db->prepare( 'SELECT `nomClients` FROM `clients`; WHERE `id_Clients` = :id_Clients;' ); $getClient->execute(); return $getClient->fetchAll(PDO::FETCH_OBJ); } /* public function getClient(){ $getClient = $this->db->prepare( 'SELECT `nomClients` FROM `clients` WHERE `id_Clients` = :id_Clients;' ); $getClient->bindvalue(':id_Clients', $this->id_Clients, PDO::PARAM_INT); $getClient->execute(); $row = $getClient->fetch(); $this->nomClients = $row['nomClients']; */ /* return $row['nomClients']; */ /* } */ public function checkIdClientExist(){ $checkIdClientExist = $this->db->prepare( 'SELECT COUNT(`id_Clients`) AS `isIdClientExist` FROM `clients` WHERE `id_Clients` = :id_Clients' ); $checkIdClientExistQuery->bindvalue(':id_Clients', $this->id_Clients, PDO::PARAM_INT); $checkIdClientExistQuery->execute(); $data = $checkIdClientExistQuery->fetch(PDO::FETCH_OBJ); return $data->isIdClientExist; } public function addClient(){ $addClientQuery = $this->db->prepare( 'INSERT INTO `clients` (`nomClients`) VALUES (:nomClients)' ); $addClientQuery->bindvalue(':nomClients', $this->nomClients, PDO::PARAM_STR); return $addClientQuery->execute(); } public function getClientInfo() { $getClientInfoQuery = $this->db->prepare( 'SELECT `id_Clients`, `nomClients` FROM `clients` WHERE `id_Clients` = :id_Clients ' ); $getClientInfoQuery->bindValue(':id_Clients', $this->id_Clients, PDO::PARAM_INT); $getClientInfoQuery->execute(); return $getClientInfoQuery->fetch(PDO::FETCH_OBJ); } public function modifyClient(){ $modifyClientQuery = $this->db->prepare( 'UPDATE `clients` SET `nomClients` = :nomClients WHERE `id_Clients` = :id_Clients' ); $modifyClientQuery->bindValue(':nomClients', $this->nomClients, PDO::PARAM_STR); $modifyClientQuery->bindValue(':id_Clients', $this->id_Clients, PDO::PARAM_INT); return $modifyClientQuery->execute(); } public function deleteClient() { $deleteClientQuery = $this->db->prepare( 'DELETE FROM `clients` WHERE `id_Clients` = :id_Clients' ); $deleteClientQuery->bindValue(':id_Clients', $this->id_Clients, PDO::PARAM_INT); return $deleteClientQuery->execute(); } }<file_sep>/connexion.php <?php include 'header.php'; include_once 'config.php'; include_once './Models/users.php'; include_once './Controllers/ctrlConnexion.php'; ?> <h1 class="text-center mt-3" id="titreAjoutClient">Se Connecter</h1> <div class="formAjoutClient"> <form action="#" method="POST"> <div class="form-group"> <label for="mail" id="labelForm">Identifiant :</label> <input type="email" class="form-control" id="mail" aria-describedby="mailHelp" name="mail"/> <?php if(isset($formErrors['mail'])){ ?> <p class="text-danger"><?= $formErrors['mail'] ?></p> <?php }else{ ?> <small id="mailHelp" class="form-text text-muted">Merci de renseigner votre adresse mail</small> <?php } ?> </div> <div class="form-group"> <label for="pass" id="labelForm">Mot de passe :</label> <input type="password" class="form-control" id="pass" aria-describedby="passHelp" name="pass" /> <?php if(isset($formErrors['pass'])){ ?> <p class="text-danger"><?= $formErrors['pass'] ?></p> <?php }else{ ?> <small id="passHelp" class="form-text text-muted">Merci de renseigner votre mot de passe</small> <?php } ?> </div> <button type="submit" name="connexion" class="btn btn-primary">Se Connecter</button> </form> </div> <?php include 'footer.php';<file_sep>/listeTypes.php <?php include 'header.php'; include './Models/types.php'; include './Controllers/ctrlListeTypes.php'; ?> <div class="btnListeEquipements text-center"> <a class="btn btn-outline-primary btn-sm" href="index.php"><i class="fas fa-home fa-2x"></i> Accueil</a> <a class="btn btn-outline-primary btn-sm" href="tableauDeBord.php"><i class="fas fa-tachometer-alt fa-2x"></i> Tableau De Bord</a> </div> <div> <h1 class="text-center mt-3" id="titreTdb">Modifier ou Supprimer un Type</h1> </div> <!-- Avertissement avent Suppression --> <?php if(isset($_GET['idDelete'])){ ?> <div class="alert text-center alert-dismissible"> <button type="button" class="close" data-dismiss="alert">&times;</button> <h1 class="h4">Voulez-vous supprimer ce Type?</h1> <form class="text-center" method="POST" action="listeTypes.php"> <input type="hidden" name="idDelete" value="<?= $types->id_types?>" /> <button type="submit" class="btn btn-primary btn-sm" name="confirmDelete">Oui</button> <button type="button" class="btn btn-danger btn-sm" data-dismiss="alert">Non</button> </form> </div><?php } ?> <div class="pl-3 pr-3 tableTypes table-responsive"> <table class="table table-hover" id="listeTypes"> <button onclick="exportCSVTypes('xlsx')" class="btn btn-success btn-sm float-left mb-1">Exporter en format csv</button> <thead > <tr class="tdbTr"> <th scope="col">Identifiant</th> <th scope="col">Nom de Type</th> <th scope="col">Modifier ou Supprimer</th> </tr> </thead> <tbody> <?php foreach ($listeTypes as $typesListe){ ?> <tr> <td><?= $typesListe->id_types ?></td> <td><?= $typesListe->nomTypes ?></td> <td> <a href="modifType.php?&id_types=<?= $typesListe->id_types ?>"><i class="fas fa-edit fa-2x"></i></a> <a href="listeTypes.php?&idDelete=<?= $typesListe->id_types ?>"><i class="far fa-trash-alt fa-2x"></i></a></td> </tr><?php } ?> </tbody> </table> </div> <!-- Footer --> <?php include 'footer.php' ?><file_sep>/Controllers/ctrlListeEquipements.php <?php $equipements = new equipements(); if(isset($_POST['sendSearch'])){ $search = htmlspecialchars($_POST['search']); $resultsNumber = $equipements->countSearchResult($search); $link = 'listeEquipements.php?search=' . $_GET['search'] . '&sendSearch='; if($resultsNumber == 0 ){ $searchMessage = 'Aucun resultat ne correspond à votre recherche'; }else{ $searchMessage = 'Il y a ' . $resultsNumber . ' résultats'; $listeEquipements = $equipements->searchEquipementsListByName($search); } }else{ $listeEquipements = $equipements->getEquipements(); $resultsNumber = count($listeEquipements); $searchMessage = 'Il y a ' . $resultsNumber . ' equipements'; $link = 'listeEquipements.php?'; } if(!empty($_GET['idDelete'])){ $equipements->id_equipements = htmlspecialchars($_GET['idDelete']); }else if(!empty($_POST['idDelete'])){ $equipements->id_equipements = htmlspecialchars($_POST['idDelete']); }else { $deleteMessage = 'Aucun equipement n\'a été sélectionné'; } if(isset($_POST['confirmDelete'])){ if($equipements->deleteEquipements()); header('location:./listeEquipements.php'); }else { $message = 'une erreur est survenue lors de la suppression'; }<file_sep>/Controllers/ctrlAjoutType.php <?php $formErrors = array(); $types = new types(); /* if (isset($_POST['addType'])) { */ if (!empty($_POST['nomTypes'])) { $types->nomTypes = htmlspecialchars($_POST['nomTypes']); } else { $formErrors['nomTypes'] = 'L\'information n\'est pas renseigné'; } // Validation// if (empty($formErrors['nomTypes'])) { if (!$types->checkTypeExist()){ if($types->addType()){ $addTypesMessage = '<div class="alert alert-success" role="alert"><i class="far fa-check-circle"></i> Le Type d\'engin a bien été ajouté</div>'; } else { $addTypesMessage = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Une erreur est survenue.</div>'; } } else { $addTypesMessage = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Le Type d\'engin existe.</div>'; } } /* } */<file_sep>/Models/anomalies.php <?php class anomalies { public $id_anomalies = 0; public $id_Engins = 0; public $description = ''; public $numeroEngin = ''; public $imageAnom1 = ''; public $imageAnom2 = ''; public $imageAnom3 = ''; private $db = null; public function __construct(){ $this->db = dataBase::getInstance(); } public function checkAnomaliesExist(){ $checkAnomaliesExist = $this->db->prepare( 'SELECT COUNT(`id_anomalies`) AS `isAnomaliesExist` FROM `anomalies` WHERE `id_anomalies` = :id_anomalies' ); $checkAnomaliesExist->bindvalue(':id_anomalies', $this->id_anomalies, PDO::PARAM_INT); $checkAnomaliesExist->execute(); return $checkAnomaliesExist->fetch(PDO::FETCH_OBJ)->isAnomaliesExist; } public function getAnomaliesByEngin() { $getAnomaliesByEnginQuery = $this->db->prepare( 'SELECT `engins`.`id_Engins`,`anomalies`.`description`, `engins`.`numeroEngin` FROM `anomalies` INNER JOIN `engins` ON `engins`.`id_Engins`= `anomalies`.`id_Engins` WHERE `engins`.`id_Engins` = :id_Engins' ); $getAnomaliesByEnginQuery->bindValue(':id_Engins', $this->id_Engins, PDO::PARAM_INT); $getAnomaliesByEnginQuery->execute(); return $getAnomaliesByEnginQuery->fetchAll(PDO::FETCH_OBJ); } public function getAnomalies(){ $getAnomalies = $this->db->prepare( 'SELECT `anomalies`.`id_anomalies`, `anomalies`.`description`, `engins`.`numeroEngin`, `imageAnom1`,`imageAnom2`,`imageAnom3` FROM `engins` INNER JOIN `anomalies` ON `engins`.`id_Engins`= `anomalies`.`id_Engins`;' ); $getAnomalies->execute(); return $getAnomalies->fetchAll(PDO::FETCH_OBJ); } /* public function getAnomalie(){ $getAnomalie = $this->db->prepare( 'SELECT `description`, `imageAnom1`,`imageAnom2`,`imageAnom3` FROM `anomalies` INNER JOIN `engins` ON `anomalies`.`id_anomalies` = `engins`.`id_anomalies` WHERE `id_Engins` = :id_Engins;' ); $getAnomalie->bindvalue(':description', $this->description, PDO::PARAM_STR); */ /* $getAnomalie->bindvalue(':imageAnom1', $this->imageAnom1, PDO::PARAM_STR); $getAnomalie->bindvalue(':imageAnom2', $this->imageAnom2, PDO::PARAM_STR); $getAnomalie->bindvalue(':imageAnom3', $this->imageAnom3, PDO::PARAM_STR); $getAnomalie->bindvalue(':id_Engins', $this->id_Engins, PDO::PARAM_INT); */ /* $getAnomalie->execute(); return $getAnomalie->fetchAll(PDO::FETCH_OBJ); } */ /* public function getAnomalies(){ $getAnomalies = $this->db->query( 'SELECT `id_anomalies`,`description`,`numeroEngin`,`imageAnom1`,`imageAnom2`,`imageAnom3` FROM `anomalies` INNER JOIN `engins` ON `anomalies`.`id_anomalies` = `engins`.`id_Engins`' ); */ /* $getAnomalies->execute(); */ /* return $getAnomalies->fetchAll(PDO::FETCH_OBJ); } */ public function checkidAnomaliesExist(){ $checkidAnomaliesExistQuery = $this->db->prepare( 'SELECT COUNT(`id_anomalies`) AS `isIdAnomaliesExist` FROM `anomalies` WHERE `id_anomalies` = :id_anomalies' ); $checkidAnomaliesExistQuery->bindvalue(':id_anomalies', $this->id_anomalies, PDO::PARAM_INT); $checkidAnomaliesExistQuery->execute(); $data = $checkidAnomaliesExistQuery->fetch(PDO::FETCH_OBJ); return $data->isIdAnomaliesExist; } public function addAnomalies(){ $addAnomaliesQuery = $this->db->prepare( 'INSERT INTO `anomalies` (`description`, `imageAnom1`, `id_Engins`) VALUES (:description, :imageAnom1, :id_Engins)' ); $addAnomaliesQuery->bindvalue(':description', $this->description, PDO::PARAM_STR); $addAnomaliesQuery->bindvalue(':imageAnom1', $this->imageAnom1, PDO::PARAM_STR); $addAnomaliesQuery->bindvalue(':id_Engins', $this->id_Engins, PDO::PARAM_INT); return $addAnomaliesQuery->execute(); } public function modifyAnomalies(){ $modifyAnomaliesQuery = $this->db->prepare( 'UPDATE `anomalies` SET `description` = :description WHERE `id_anomalies` = :id_anomalies' ); $modifyAnomaliesQuery->bindValue(':description', $this->description, PDO::PARAM_STR); $modifyAnomaliesQuery->bindValue(':id_anomalies', $this->id_anomalies, PDO::PARAM_INT); return $modifyAnomaliesQuery->execute(); } public function deleteAnomalies() { $deleteAnomaliesQuery = $this->db->prepare( 'DELETE FROM `anomalies` WHERE `id_anomalies` = :id_anomalies' ); $deleteAnomaliesQuery->bindValue(':id_anomalies', $this->id_anomalies, PDO::PARAM_INT); return $deleteAnomaliesQuery->execute(); } }<file_sep>/Models/dataBase.php <?php class dataBase { public $db = null; private static $instance = null; public function __construct(){ try { $this->db = new PDO('mysql:host='. SQL_HOST .';dbname=' . SQL_DBNAME . ';charset=utf8', SQL_USERNAME, SQL_PASSWORD, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); } catch (Exception $error) { die($error->getMessage()); } } //Singleton //Static signifie que je ne peut pas y accèder via l'instance. // on y accède de cette façon: nomClass::methode() ou nomClass::attribut public static function getInstance(){ //On créer une instance PDO si et seulement si il en n'existe pas déjà une if(is_null(self::$instance)){ self::$instance = new dataBase(); } return self::$instance->db; } }<file_sep>/Models/types.php <?php class types { public $id_types = 0; public $nomTypes = ''; private $db = null; public function __construct() { $this->db = dataBase::getInstance(); } public function checkTypeExist(){ $checkTypeExist = $this->db->prepare( 'SELECT COUNT(`id_types`) AS `isTypeExist` FROM `types` WHERE `nomTypes` = :nomTypes' ); $checkTypeExist->bindvalue(':nomTypes', $this->nomTypes, PDO::PARAM_STR); $checkTypeExist->execute(); return $checkTypeExist->fetch(PDO::FETCH_OBJ)->isTypeExist; } public function getType(){ $getType = $this->db->prepare( 'SELECT `id_types`, `nomTypes` FROM `types`;' ); $getType->execute(); return $getType->fetchAll(PDO::FETCH_OBJ); } public function checkIdTypeExist(){ $checkIdTypeExist = $this->db->prepare( 'SELECT COUNT(`id_types`) AS `isIdTypeExist` FROM `types` WHERE `id_types` = :id_types' ); $checkIdTypeExistQuery->bindvalue(':id_types', $this->id_types, PDO::PARAM_INT); $checkIdTypeExistQuery->execute(); $data = $checkIdTypeExistQuery->fetch(PDO::FETCH_OBJ); return $data->isIdTypeExist; } public function addType(){ try { $addTypeQuery = $this->db->prepare( 'INSERT INTO `types` (`nomTypes`) VALUES (:nomTypes)' ); $addTypeQuery->bindvalue(':nomTypes', $this->nomTypes, PDO::PARAM_STR); return $addTypeQuery->execute(); return true; } catch (\Throwable $th) { return false; echo $th->getMessage(); } } public function getTypesInfo() { $getTypesInfoQuery = $this->db->prepare( 'SELECT `id_types`, `nomTypes` FROM `types` WHERE `id_types` = :id_types' ); $getTypesInfoQuery->bindValue(':id_types', $this->id_types, PDO::PARAM_INT); $getTypesInfoQuery->execute(); return $getTypesInfoQuery->fetch(PDO::FETCH_OBJ); } public function modifyType(){ $modifyTypeQuery = $this->db->prepare( 'UPDATE `types` SET `nomTypes` = :nomTypes WHERE `id_types` = :id_types' ); $modifyTypeQuery->bindValue(':nomTypes', $this->nomTypes, PDO::PARAM_STR); $modifyTypeQuery->bindValue(':id_types', $this->id_types, PDO::PARAM_INT); return $modifyTypeQuery->execute(); } public function deleteType() { $deleteTypeQuery = $this->db->prepare( 'DELETE FROM `types` WHERE `id_types` = :id_types' ); $deleteTypeQuery->bindValue(':id_types', $this->id_types, PDO::PARAM_INT); return $deleteTypeQuery->execute(); } }<file_sep>/config.php <?php define('SQL_HOST', 'localhost'); define('SQL_DBNAME', 'digit_engin'); define('SQL_USERNAME', 'root'); define('SQL_PASSWORD', '');<file_sep>/Controllers/ctrlModifEquipements.php <?php if(isset($_GET['id_equipements'])){ $equipements = new equipements(); $updatedEquipements = new equipements(); $equipements->id_equipements = $_GET['id_equipements']; if($equipements->getEquipementsInfo()){ $equipements = $equipements->getEquipementsInfo(); }else { $modifyMessageFail = '<i class="fas fa-exclamation-triangle"></i> Cette equipements n\'éxiste pas'; } } $formErrors = array(); if(isset($_POST['modify'])){ //instancier notre requete de la class equipements if(!empty($_POST['nomEquipements'])){ //J'hydrate mon instance d'objet equipements $updatedEquipements->nomEquipements = htmlspecialchars($_POST['nomEquipements']); }else{ $formErrors['nomEquipements'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Renseigner le nom de l\'equipement</div>' ; } if(empty($formErrors)){ // On verify si le nomEquipements a été modifié if ($equipements->nomEquipements != $updatedEquipements->nomEquipements){ //On vérifie si le pseudo est libre if($updatedEquipements->checkEquipementsExist()){ $formErrors['nomEquipements'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Le nom d\'equipement déja existe</div>'; }else { $updatedEquipements->id_equipements = $_GET['id_equipements']; if($updatedEquipements->modifyEquipements()){ $modifyMessageSuccess = '<i class="far fa-check-circle"></i>L\'equipement a bien été modifié'; }else { $modifyMessageFail = '<i class="fas fa-exclamation-triangle"></i> Pas de modification'; } } }else{ $modifyMessageFail ='<i class="fas fa-exclamation-triangle"></i> Pas de changements'; } } } <file_sep>/Controllers/ctrlInscription.php <?php $formErrors = []; //Vérification du formulaire d'inscription if(isset($_POST['register'])){ $user = new users(); /** * Cette variable sert à savoir si les vérifications du mot de passe et de sa confirmation se sont déroulés avec succès */ $isPasswordOk = true; if(!empty($_POST['mail'])){ if(filter_var($_POST['mail'],FILTER_VALIDATE_EMAIL)){ //J'hydrate mon instance d'objet user $user->mail = htmlspecialchars($_POST['mail']); }else{ $formErrors['mail'] ='Renseigner un adress mail valide'; } }else{ $formErrors['mail'] = 'Renseigner votre adresse mail'; } if(!empty($_POST['nomUser'])){ //J'hydrate mon instance d'objet user $user->nomUser = htmlspecialchars($_POST['nomUser']); }else{ $formErrors['nomUser'] = 'Renseigner votre nom d\'utilisateur'; } if(empty($_POST['pass'])){ $formErrors['pass'] = '<PASSWORD> de passe'; $isPasswordOk = false; } if(empty($_POST['passVerify'])){ $formErrors['passVerify'] = 'Confirmez votre mot de passe'; $isPasswordOk = false; } //Si les vérifications des mots de passe sont ok if($isPasswordOk){ if($_POST['passVerify'] == $_POST['pass']){ //On hash le mot de passe avec la méthode de PHP $user->pass = password_hash($_POST['pass'], PASSWORD_DEFAULT); }else{ $formErrors['pass'] = $formErrors['passVerify'] = 'Les mots de passe doivent être identiques'; } } if(empty($formErrors)){ $isOk = true; //On vérifie si le pseudo est libre if($user->checkUserUnavailabilityByFieldName(['nomUser'])){ $formErrors['nomUser'] = 'Votre nom d\'utilisateur déja pris'; $isOk = false; } //On vérifie si le mail est libre if($user->checkUserUnavailabilityByFieldName(['mail'])){ $formErrors['mail'] = 'Votre adress mail déja pris'; $isOk = false; } //Si c'est bon on ajoute l'utilisateur if($isOk){ if ($user->addUser()) { $inscriptionMessageSuccess = ' Vous etre bien crée votre compte'; }else { $inscriptionMessageFail = ' Une erreur est survenu'; } } } } //Traitement de la demande AJAX if(isset($_POST['fieldValue'])){ //On vérifie que l'on a bien envoyé des données en POST if(!empty($_POST['fieldValue']) && !empty($_POST['fieldName'])){ //On inclut les bons fichiers car dans ce contexte ils ne sont pas connu. include_once './config.php'; include_once '../Models/users.php'; $user = new users(); $input = htmlspecialchars($_POST['fieldName']); $user->$input = htmlspecialchars($_POST['fieldValue']); //Le echo sert à envoyer la réponse au JS echo $user->checkUserUnavailabilityByFieldName([htmlspecialchars($_POST['fieldName'])]); }else{ echo 2; } } ?><file_sep>/Models/statut.php <?php class statut { public $id_statut = 0; public $nomStatut = ''; private $db = null; public function __construct() { $this->db = dataBase::getInstance(); } public function getStatut(){ $getStatut = $this->db->prepare( 'SELECT `id_statut`, `nomStatut` FROM `statut`;' ); $getStatut->execute(); return $getStatut->fetchAll(PDO::FETCH_OBJ); } }<file_sep>/listeClients.php <?php include 'header.php'; include './Models/clients.php'; include './Controllers/ctrlListeClients.php'; ?> <div class="btnListeClients text-center"> <a class="btn btn-outline-primary btn-sm" href="index.php"><i class="fas fa-home fa-2x"></i> Accueil</a> <a class="btn btn-outline-primary btn-sm" href="tableauDeBord.php"><i class="fas fa-tachometer-alt fa-2x"></i> Tableau De Bord</a> </div> <div> <h1 class="text-center mt-3" id="titreTdb">Modifier ou Supprimer un Client</h1> </div> <!-- Avertissement avent Suppression --> <?php if(isset($_GET['idDelete'])){ ?> <div class="alert text-center alert-dismissible"> <button type="button" class="close" data-dismiss="alert">&times;</button> <h1 class="h4">Voulez-vous supprimer ce Client?</h1> <form class="text-center" method="POST" action="listeClients.php"> <input type="hidden" name="idDelete" value="<?= $clients->id_Clients?>" /> <button type="submit" class="btn btn-primary btn-sm" name="confirmDelete">Oui</button> <button type="button" class="btn btn-danger btn-sm" data-dismiss="alert">Non</button> </form> </div><?php } ?> <div class="pl-3 pr-3 tableClients table-responsive"> <table class="table table-hover" id="listeClients"> <button onclick="exportCSVClients('xlsx')" type="button" class="btn btn-success btn-sm float-left mb-1">Exporter en format csv</button> <thead > <tr class="tdbTr"> <th scope="col">Identifiant</th> <th scope="col">Nom de Client</th> <th scope="col">Modifier ou Supprimer</th> </tr> </thead> <tbody> <?php foreach ($listeClients as $clientsListe){ ?> <tr> <td><?= $clientsListe->id_Clients ?></td> <td><?= $clientsListe->nomClients ?></td> <td> <a href="modifClient.php?&id_Clients=<?= $clientsListe->id_Clients ?>"><i class="fas fa-edit fa-2x"></i></a> <a href="listeClients.php?&idDelete=<?= $clientsListe->id_Clients ?>"><i class="far fa-trash-alt fa-2x"></i></a></td> </tr><?php } ?> </tbody> </table> </div> <!-- Footer --> <?php include 'footer.php' ?><file_sep>/Models/users.php <?php class users{ public $id_users = 0; public $nomUser = ''; public $pass = ''; public $mail = ''; public $id_roles = 1; private $db = null; private $table = 'users'; public function __construct() { $this->db = dataBase::getInstance(); } /** * Méthode permettant d'enregistrer un utilisateur * @return boolean */ public function addUser(){ $addUser = $this->db->prepare(' INSERT INTO ' . $this->table . ' (`nomUser`, `mail`, `pass`, `id_roles`) VALUES (:nomUser, :mail, :pass, :id_roles) '); $addUser->bindValue(':nomUser',$this->nomUser,PDO::PARAM_STR); $addUser->bindValue(':mail',$this->mail,PDO::PARAM_STR); $addUser->bindValue(':pass',$this->pass,PDO::PARAM_STR); $addUser->bindValue(':id_roles',$this->id_roles,PDO::PARAM_INT); return $addUser->execute(); } /** * Méthode permettant de savoir une valeur d'un champ est déjà prise * Valeur de retour : * - True : la valeur est déjà prise * - False : la valeur est disponible * @param array $field * @return boolean */ public function checkUserUnavailabilityByFieldName($field){ $whereArray = []; foreach($field as $fieldName ){ $whereArray[] = '`' . $fieldName . '` = :' . $fieldName; } $where = ' WHERE ' . implode(' AND ', $whereArray); $checkUserUnavailabilityByFieldName = $this->db->prepare(' SELECT COUNT(`id_users`) as `isUnavailable` FROM ' . $this->table . $where ); foreach($field as $fieldName ){ $checkUserUnavailabilityByFieldName->bindValue(':'.$fieldName,$this->$fieldName,PDO::PARAM_STR); } $checkUserUnavailabilityByFieldName->execute(); return $checkUserUnavailabilityByFieldName->fetch(PDO::FETCH_OBJ)->isUnavailable; } /** * Méthode permettant de récupérer le hash du mot de passe de l'utilisateur * * @return void */ public function getUserPasswordHash(){ $getUserPasswordHash = $this->db->prepare( 'SELECT `pass` FROM ' . $this->table . ' WHERE `mail` = :mail' ); $getUserPasswordHash->bindValue(':mail', $this->mail, PDO::PARAM_STR); $getUserPasswordHash->execute(); $response = $getUserPasswordHash->fetch(PDO::FETCH_OBJ); if(is_object($response)){ return $response->pass; }else{ return ''; } } /** * Méthode permettant de récupérer les différentes infos d'un utilisateur * * @return object */ public function getUserAccount(){ $getUserAccount = $this->db->prepare( 'SELECT `id_users`, `nomUser`, id_roles FROM ' . $this->table . ' WHERE `mail` = :mail' ); $getUserAccount->bindValue(':mail', $this->mail, PDO::PARAM_STR); $getUserAccount->execute(); return $getUserAccount->fetch(PDO::FETCH_OBJ); } public function getUsersList() { $getUsersListQuery = $this->db->query( 'SELECT `id_users`, `id_roles`, `nomUser`, `mail` FROM `users`' ); return $getUsersListQuery->fetchAll(PDO::FETCH_OBJ); } public function getProfilUser() { $getProfilUserQuery = $this->db->prepare( 'SELECT `id_users`, `nomUser`, `mail` FROM `users` WHERE `id_users` = :id_users ' ); $getProfilUserQuery->bindValue(':id_users', $this->id_users, PDO::PARAM_INT); $getProfilUserQuery->execute(); return $getProfilUserQuery->fetch(PDO::FETCH_OBJ); } public function checkIdUsersExist() { $checkIdUsersExistQuery = $this->db->prepare( 'SELECT COUNT(`id_users`) AS `isIdUserExist` FROM `users` WHERE `id_users` = :id_users ' ); $checkIdUsersExistQuery->bindvalue(':id_users', $this->id_users, PDO::PARAM_INT); $checkIdUsersExistQuery->execute(); $data = $checkIdUsersExistQuery->fetch(PDO::FETCH_OBJ); return $data->isIdUserExist; } public function modifyUserProfil(){ $modifyUserProfilQuery = $this->db->prepare( 'UPDATE `users` SET `nomUser` = :nomUser, `mail` = :mail WHERE `id_users` = :id_users ' ); $modifyUserProfilQuery->bindValue(':id_users', $this->id_users, PDO::PARAM_INT); $modifyUserProfilQuery->bindValue(':nomUser', $this->nomUser, PDO::PARAM_STR); $modifyUserProfilQuery->bindValue(':mail', $this->mail, PDO::PARAM_STR); return $modifyUserProfilQuery->execute(); } public function deleteUsers() { $deleteUsersQuery = $this->db->prepare( 'DELETE FROM `users` WHERE `id_users` = :id_users' ); $deleteUsersQuery->bindValue(':id_users', $this->id_users, PDO::PARAM_INT); return $deleteUsersQuery->execute(); } }<file_sep>/ajoutAnomalies.php <?php include 'header.php'; include './Models/engins.php'; include './Models/anomalies.php'; include './Controllers/ctrlAnomalies.php'; ?> <div class="btnAjoutEngin text-center"> <a class="btn btn-outline-primary btn-sm" href="index.php"><i class="fas fa-home fa-2x"></i> Accueil</a> <!-- Btn CRUD --> <a class="btn btn-outline-primary btn-sm" href="tableauDeBord.php"><i class="fas fa-tachometer-alt fa-2x"></i> Tableau De Bord</a> </div> <!-- Début Formulaire --> <!-- Titre Formulaire --> <h1 class="text-center mt-3" id="titreAjoutEngin">Declarer une Anomalie</h1> <div class="formAjoutAnomalies"> <form action="ajoutAnomalies.php" method="POST" enctype="multipart/form-data"> <!-- TYPE D'ENGINE --> <div class="form-group"> <label for="numeroEngin" id="labelForm">Numero d'Engin</label> <select id="numeroEngin" class="form-control" name="numeroEngin"> <option selected disabled>Choisissez l'Engin :</option><?php foreach($numeroEnginListe as $numeroEngin){ ?> <option value="<?= $numeroEngin->id_engins ?>"><?= $numeroEngin->id_engins . ' - ' . $numeroEngin->numeroEngin ?></option><?php } ?> </select> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['id_Engins']) ? $formErrors['id_Engins'] : '' ?></p> </div> <div class="form-group"> <label for="description" id="labelForm">Observation</label> <textarea onkeyup="textCounter(this,'counter',300);" class="form-control <?= count($formErrors) > 0 ? (isset($formErrors['description']) ? 'is-invalid' : 'is-valid') : '' ?>" value="<?= isset($_POST['description']) ? $_POST['description'] : ' ' ?>" type="text" maxlength=300 name="description" ></textarea> <input disabled maxlength="300" size="22" value="Maximum 300 Caractères." id="counter"> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['description']) ? $formErrors['description'] : '' ?></p> </div> <!-- IMAGE --> <div class="form-group"> <label for="image" id="labelForm">Image</label> <input id="image" class="form-control <?= count($formErrors) > 0 ? (isset($formErrors['imageAnom1']) ? 'is-invalid' : 'is-valid') : '' ?>" value="<?= isset($_POST['imageAnom1']) ? $_POST['imageAnom1'] : '' ?>" type="file" name="imageAnom1" /> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['imageAnom1']) ? $formErrors['imageAnom1'] : '' ?></p> </div> <!--message de succés ou d'erreur--> <p class="formMessage"><?= isset($addAnomaliesMessage) ? $addAnomaliesMessage : '' ?></p> <!-- Btn validation --> <div> <button type="submit" name="addAnomalies" class="btn btn-primary btn-sm">Valider</button> <button type="reset" class="btn btn-warning btn-sm">Réinitialiser</button> </div> </form> </div> <!-- Affichage de Footer --> <?php include 'footer.php' ?><file_sep>/index.php <?php include 'header.php'; include './Controllers/ctrlIndex.php'; include './Controllers/ctrlConnexion.php'; ?> <div class="jumbotron jumbotron-fluid infoIndex"> <!-- Les Buttons de la page d'Accueil --> <div class="container"> <?php if (isset($_SESSION['account']) && $_SESSION['account']['id_roles'] == 2) { ?> <a class="btn btn-outline-primary btn-sm" href="debutPoste.php"><i class="fas fa-play fa-2x"></i> Prise Poste</a> <a class="btn btn-outline-primary btn-sm" href="finPoste.php"><i class="fas fa-stop fa-2x"></i> Fin Poste</a> <a class="btn btn-outline-primary btn-sm" href="tableauDeBord.php"><i class="fas fa-tachometer-alt fa-2x"></i>Tableau De Bord</a> <?php } else if (isset($_SESSION['account']) && $_SESSION['account']['id_roles'] == 1) {?> <a class="btn btn-outline-primary btn-sm" href="debutPoste.php"><i class="fas fa-play fa-2x"></i> Prise Poste</a> <a class="btn btn-outline-primary btn-sm" href="finPoste.php"><i class="fas fa-stop fa-2x"></i> Fin Poste</a> </div> <?php }?> <div class="container"> <h1 class="display-4">Digit Engin</h1> <p class="lead">La productivité, la fiabilité, la disponibilité et les performances.</p> <img src="./Assets/Img/imgIntro.jpg" alt="imgIntro" class="img-fluid imgHeader"> </div> </div> <!-- Affichage de Footer --> <?php include 'footer.php'; ?><file_sep>/header.php <?php session_start(); include 'config.php'; include_once './Models/dataBase.php'; include_once './Controllers/ctrlHeader.php'; ?> <!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="icon" href="Assets/Img/imgHead.png"> <title>Digit Engin</title> <link rel="stylesheet" href="Assets/Styles/style.css"> <link href="https://fonts.googleapis.com/css2?family=Raleway&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css"> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/css/mdb.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/bbbootstrap/libraries@main/choices.min.css"> </head> <body> <!-- Header Image --> <header class="blog-header"> <a href="./index.php"><img src="./Assets/Img/logo.jpg" class="img-fluid imgLogo" alt="logo"></a> <!-- Header BTN --> <div class="container-fluid"> <?php if(!isset($_SESSION['account'])){ //Si l'utilisateur n'est pas connecté ?> <a href="connexion.php?view=connexion" role="button" class="btn btn-primary btn-sm"> <span title="S'identifier"><i class="fas fa-sign-in-alt"> S'identifier</i></span></a> <a href="inscription.php?view=inscription" role="button" class="btn btn-primary btn-sm"><span title="s'inscrire"><i class="fas fa-user-plus"> S'inscrire</i></span></a> <?php }else{ //Si la personne est connectée?> <a href="userProfile.php/" class="titreUtilisateur"><?= isset($_SESSION['account']['nomUser']) ? ' Bonjour ' . $_SESSION['account']['nomUser']: ''?></a> <a href="?action=disconnect" role="button" class="btn btn-outline-danger btn-sm"><span title="Se deconnecter"><i class="fas fa-sign-out-alt"> Se deconnecter</i></span></a> <?php } ?> </div> </header><file_sep>/inscription.php <?php include 'header.php'; include_once './Models/users.php'; include_once './Controllers/ctrlInscription.php'; if(isset($inscriptionMessageFail)){ ?> <div class="alert alert-danger alert-dismissible fade show" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <?= $inscriptionMessageFail ?> </div> <?php } if(isset($inscriptionMessageSuccess)){ ?> <div class="alert alert-success alert-dismissible fade show" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <?= $inscriptionMessageSuccess ?> </div> <?php } ?> <h1 class="text-center mt-3" id="titreAjoutClient">Créer Mon Compte</h1> <div class="formAjoutClient"> <form action="#" method="POST"> <div class="form-group"> <label for="nomUser" id="labelForm">Nom d'utilisateur :</label> <input type="text" class="form-control" id="nomUser" aria-describedby="nomUserHelp" name="nomUser" onblur="checkUnavailability(this)" /> <?php if(isset($formErrors['nomUser'])){ ?> <p class="text-danger"><?= $formErrors['nomUser'] ?></p> <?php }else{ ?> <small id="nomUserHelp" class="form-text text-muted">Merci de renseigner votre nom d'utilisateur</small> <?php } ?> </div> <div class="form-group"> <label for="mail" id="labelForm">Adresse mail :</label> <input type="email" class="form-control" id="mail" aria-describedby="mailHelp" name="mail" onblur="checkUnavailability(this)" /> <?php if(isset($formErrors['mail'])){ ?> <p class="text-danger"><?= $formErrors['mail'] ?></p> <?php }else{ ?> <small id="mailHelp" class="form-text text-muted">Merci de renseigner votre adresse mail</small> <?php } ?> </div> <div class="form-group"> <label for="pass" id="labelForm">Mot de passe :</label> <input type="<PASSWORD>" class="form-control" aria-describedby="passHelp" name="pass" > <?php if(isset($formErrors['pass'])){ ?> <p class="text-danger"><?= $formErrors['pass'] ?></p> <?php }else{ ?> <small id="passHelp" class="form-text text-muted">Merci de renseigner votre mot de passe</small> <?php } ?> </div> <div class="form-group"> <label for="passVerify" id="labelForm">Mot de passe (confirmation) :</label> <input type="password" class="form-control" id="passVerify" aria-describedby="passVerifyHelp" name="passVerify" /> <?php if(isset($formErrors['passVerify'])){ ?> <p class="text-danger"><?= $formErrors['passVerify'] ?></p> <?php }else{ ?> <small id="passVerifyHelp" class="form-text text-muted">Merci de confirmer votre mot de passe</small> <?php } ?> </div> <!-- Btn validation --> <button type="submit" name="register" class="btn btn-primary btn-sm">Je m'inscris</button> <button type="reset" class="btn btn-warning btn-sm">Réinitialiser</button> </form> </div> <?php include 'footer.php';<file_sep>/ajoutEquipement.php <?php include 'header.php'; include './Models/equipements.php'; include './Controllers/ctrlAjoutEquipement.php'; ?> <div class="btnAjoutClient text-center"> <a class="btn btn-outline-primary btn-sm" href="index.php"><i class="fas fa-home fa-2x"></i> Accueil</a> <!-- Btn CRUD --> <a class="btn btn-outline-primary btn-sm" href="tableauDeBord.php"><i class="fas fa-tachometer-alt fa-2x"></i> Tableau De Bord</a> </div> <!-- Début Formulaire --> <!-- Titre Formulaire --> <h1 class="text-center mt-3" id="titreAjoutEquipement">Ajouter un Equipement</h1> <div class="formAjoutEquipement"> <form action="ajoutEquipement.php" method="POST"> <div class="form-group"> <label for="nomEquipements" id="labelForm">Nom d'équipement</label> <input oninput="this.value = this.value.toUpperCase()" class="form-control" id="nomEquipements" <?= count($formErrors) > 0 ? (isset($formErrors['nomEquipements']) ? 'is-invalid' : 'is-valid') : '' ?>value="<?= isset($_POST['nomEquipements']) ? $_POST['nomEquipements'] : '' ?>" type="text" name="nomEquipements" /> <small id="help" class="form-text text-muted">Entrez un nouveau équipement</small> </div> <!--message de succés ou d'erreur--> <p class="formMessage"><?= isset($addEquipementMessage) ? $addEquipementMessage : '' ?></p> <!-- Btn validation --> <button type="submit" name="addEquipements" class="btn btn-primary btn-sm">Valider</button> <button type="reset" class="btn btn-warning btn-sm">Réinitialiser</button> </form> </div> <!-- Affichage de Footer --> <?php include 'footer.php' ?><file_sep>/ajoutClient.php <?php include 'header.php'; include './Models/clients.php'; include './Controllers/ctrlAjoutClient.php'; ?> <div class="btnAjoutClient text-center"> <a class="btn btn-outline-primary btn-sm" href="index.php"><i class="fas fa-home fa-2x"></i> Accueil</a> <!-- Btn CRUD --> <a class="btn btn-outline-primary btn-sm" href="tableauDeBord.php"><i class="fas fa-tachometer-alt fa-2x"></i> Tableau De Bord</a> </div> <!-- Début Formulaire --> <!-- Titre Formulaire --> <h1 class="text-center mt-3" id="titreAjoutClient">Ajouter un Client</h1> <div class="formAjoutClient"> <form action="ajoutClient.php" method="POST"> <div class="form-group"> <label for="nomClient" id="labelForm">Nom de Client</label> <input oninput="this.value = this.value.toUpperCase()" class="form-control" id="nomClients" <?= count($formErrors) > 0 ? (isset($formErrors['nomClients']) ? 'is-invalid' : 'is-valid') : '' ?> label="Nom de Client" value="<?= isset($_POST['nomClients']) ? $_POST['nomClients'] : '' ?>" type="text" name="nomClients" /> <small id="help" class="form-text text-muted">Entrez un nouveau client</small> </div> <!--message de succés ou d'erreur--> <p class="formMessage"><?= isset($addClientMessage) ? $addClientMessage : '' ?></p> <!-- Btn validation --> <button type="submit" name="addClient" class="btn btn-primary btn-sm">Valider</button> <button type="reset" class="btn btn-warning btn-sm">Réinitialiser</button> </form> </div> <!-- Affichage de Footer --> <?php include 'footer.php' ?><file_sep>/debutPoste.php <?php include 'header.php'; include './Models/engins.php'; include './Models/statut.php'; include './Models/debPoste.php'; include './Controllers/ctrlDebutPoste.php'; ?> <div class="btnDebutPoste text-center"> <a class="btn btn-outline-primary btn-sm" href="index.php"><i class="fas fa-home fa-2x"></i> Accueil</a> <!-- Btn CRUD --> <a class="btn btn-outline-primary btn-sm" href="tableauDeBord.php"><i class="fas fa-tachometer-alt fa-2x"></i> Tableau De Bord</a> </div> <!-- Début Formulaire --> <!-- Titre Formulaire --> <h1 class="text-center mt-3" id="titreDebutPoste">Début Du Poste</h1> <div class="formDebutPoste"> <form action="debutPoste.php" method="POST" enctype="multipart/form-data"> <!--message de succés ou d'erreur--> <p class="formMessage"><?= isset($addDebutPoste) ? $addDebutPoste : '' ?></p> <!-- DATE L'HEURE --> <div class="form-group"> <label for="dateHeure" id="labelForm">Selectionnez La date et L'heure</label> <input class="form-control" id="dateHeure" value="<?php echo date("Y-m-d\TH:i"); ?>" type="datetime-local" name="debutPoste" /> </div> <!-- ENGINE --> <div class="form-group"> <label for="numeroEngin" id="labelForm">Choisissez votre Engin</label> <select id="numeroEngin" class="form-control" name="id_Engins" onchange="selectEngin(this.value)"> <option selected disabled>Choisissez votre Engin</option> <?php foreach($enginsListe as $engins){ ?> <option value="<?= $engins->id_Engins ?>"><?= $engins->id_Engins . ' . ' . $engins->numeroEngin ?></option><?php } ?> </select> </div> <!-- Prise du poste Info--> <div id="prisePosteInfo"></div> <!-- Btn validation --> <div> <button type="submit" name="addDebutPoste" class="btn btn-primary btn-sm">Valider</button> <button type="reset" class="btn btn-warning btn-sm">Réinitialiser</button> </div> </form> </div> <!-- Affichage de Footer --> <?php include 'footer.php'; ?><file_sep>/ajoutEngin.php <?php include 'header.php'; include './Models/engins.php'; include './Models/types.php'; include './Models/equipements.php'; include './Models/clients.php'; include './Models/statut.php'; include './Controllers/ctrlAjoutEngin.php'; ?> <div class="btnAjoutEngin text-center"> <a class="btn btn-outline-primary btn-sm" href="index.php"><i class="fas fa-home fa-2x"></i> Accueil</a> <!-- Btn CRUD --> <a class="btn btn-outline-primary btn-sm" href="tableauDeBord.php"><i class="fas fa-tachometer-alt fa-2x"></i> Tableau De Bord</a> </div> <!-- Début Formulaire --> <!-- Titre Formulaire --> <h1 class="text-center mt-3" id="titreAjoutEngin">Ajouter un Engin</h1> <div class="formAjoutEngin"> <form action="ajoutEngin.php" method="POST" enctype="multipart/form-data"> <!--message de succés ou d'erreur--> <p class="formMessage"><?= isset($addEnginMessage) ? $addEnginMessage : '' ?></p> <!-- TYPE D'ENGINE --> <div class="form-group"> <label for="typeEngin" id="labelForm">Type d'engin</label> <select id="typeEngin" class="form-control" name="id_types"> <option selected disabled>Choisissez le Type :</option><?php foreach($typesListe as $types){ ?> <option value="<?= $types->id_types ?>"><?= $types->id_types . ' . ' . $types->nomTypes ?></option><?php } ?> </select> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['id_types']) ? $formErrors['id_types'] : '' ?></p> </div> <!-- NUMERO D'ENGIN --> <div class="form-group"> <label for="numeroEngin" id="labelForm">Numéro d'engin</label> <input oninput="this.value = this.value.toUpperCase()" class="form-control" id="numeroEngin" <?= count($formErrors) > 0 ? (isset($formErrors['numeroEngin']) ? 'is-invalid' : 'is-valid') : '' ?>value="<?= isset($_POST['numeroEngin']) ? $_POST['numeroEngin'] : '' ?>" type="text" name="numeroEngin" /> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['numeroEngin']) ? $formErrors['numeroEngin'] : '' ?></p> </div> <!-- EQUIPEMENTS --> <div class="form-group"> <label for="equipements" id="labelForm">Le(s) Equipement(s)</label> <input oninput="this.value = this.value.toUpperCase()" class="form-control" id="nomEquipements" <?= count($formErrors) > 0 ? (isset($formErrors['nomEquipements']) ? 'is-invalid' : 'is-valid') : '' ?>value="<?= isset($_POST['nomEquipements']) ? $_POST['nomEquipements'] : '' ?>" type="text" name="nomEquipements" /> <small>Veuillez séparer par une virgule / Ex : TE,IMP,DOU</small> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['nomEquipements']) ? $formErrors['nomEquipements'] : '' ?></p> </div> <!-- STATUT --> <div class="form-group"> <label for="statut" id="labelForm">Disponibilité</label> <select class="form-control" id="statut" name="id_statut"> <option selected disabled>Choisissez le statut :</option><?php foreach($statutListe as $statut){ ?> <option value="<?= $statut->id_statut ?>"><?= $statut->id_statut . ' . ' . $statut->nomStatut ?></option><?php } ?> </select> <p class="errorForm"><?= isset($formErrors['statut']) ? $formErrors['statut'] : '' ?></p> </div> <!-- DERNIER REVISION --> <div class="form-group"> <label for="dernierRevision" id="labelForm">Dernier Revision</label> <input oninput="this.value = this.value.toUpperCase()" class="form-control" id="dernierRevision" <?= count($formErrors) > 0 ? (isset($formErrors['dernierRevision']) ? 'is-invalid' : 'is-valid') : '' ?>value="<?= isset($_POST['dernierRevision']) ? $_POST['dernierRevision'] : '' ?>" type="date" name="dernierRevision" /> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['dernierRevision']) ? $formErrors['dernierRevision'] : '' ?></p> </div> <!-- PROCHAIN REVISION --> <div class="form-group"> <label for="prochainRevision" id="labelForm">Prochain Revision</label> <input oninput="this.value = this.value.toUpperCase()" class="form-control" id="prochainRevision" <?= count($formErrors) > 0 ? (isset($formErrors['prochainRevision']) ? 'is-invalid' : 'is-valid') : '' ?>value="<?= isset($_POST['prochainRevision']) ? $_POST['prochainRevision'] : '' ?>" type="date" name="prochainRevision" /> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['prochainRevision']) ? $formErrors['prochainRevision'] : '' ?></p> </div> <!-- KM REEL --> <div class="form-group"> <label for="km_reel" id="labelForm">Kilométrage</label> <input oninput="this.value = this.value.toUpperCase()" class="form-control" id="km_reel" <?= count($formErrors) > 0 ? (isset($formErrors['km_reel']) ? 'is-invalid' : 'is-valid') : '' ?>value="<?= isset($_POST['km_reel']) ? $_POST['km_reel'] : '' ?>" type="number" name="km_reel" /> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['km_reel']) ? $formErrors['km_reel'] : '' ?></p> </div> <!-- HORAMETRE --> <div class="form-group"> <label for="horametre" id="labelForm">Horamétre</label> <input oninput="this.value = this.value.toUpperCase()" class="form-control" id="horametre" <?= count($formErrors) > 0 ? (isset($formErrors['horametre']) ? 'is-invalid' : 'is-valid') : ''?>value="<?= isset($_POST['horametre']) ? $_POST['horametre'] : '' ?>" type="number" name="horametre" /> <small>Ex : 234 H 56 M</small> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['horametre']) ? $formErrors['horametre'] : '' ?></p> </div> <!-- CLIENT --> <div class="form-group"> <label for="client" id="labelForm">Client</label> <select id="client" class="form-control" name="id_Clients"> <option selected disabled>Choisissez le Client :</option><?php foreach($clientsListe as $clients){ ?> <option value="<?= $clients->id_Clients ?>"><?= $clients->id_Clients . ' . ' . $clients->nomClients ?></option><?php } ?> </select> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['id_Clients']) ? $formErrors['id_Clients'] : '' ?></p> </div> <!-- IMAGE --> <div class="form-group"> <label for="image" id="labelForm">Image</label> <input id="image" class="form-control <?= count($formErrors) > 0 ? (isset($formErrors['image']) ? 'is-invalid' : 'is-valid') : '' ?>" value="<?= isset($_POST['image']) ? $_POST['image'] : '' ?>" type="file" name="image" /> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['image']) ? $formErrors['image'] : '' ?></p> </div> <!-- Btn validation --> <div> <button type="submit" name="addEngin" class="btn btn-primary btn-sm">Valider</button> <button type="reset" class="btn btn-warning btn-sm">Réinitialiser</button> </div> </form> </div> <!-- Affichage de Footer --> <?php include 'footer.php' ?><file_sep>/Controllers/ctrlConnexion.php <?php $formErrors = []; //Vérification du formulaire de connexion if(isset($_POST['connexion'])){ $user = new users(); if(!empty($_POST['mail'])){ if(filter_var($_POST['mail'],FILTER_VALIDATE_EMAIL)){ //J'hydrate mon instance d'objet user $user->mail = htmlspecialchars($_POST['mail']); }else{ $formErrors['mail'] = 'Renseigner un adress mail valide'; } }else{ $formErrors['mail'] = 'Renseigner votre adress mail'; } if(empty($_POST['pass'])){ $formErrors['pass'] = 'Renseigner un mot de passe'; } if(empty($formErrors)){ //On récupère le hash de l'utilisateur $hash = $user->getUserPasswordHash(); //Si le hash correspond au mot de passe saisi if(password_verify($_POST['pass'], $hash)){ //On récupère son profil $userAccount = $user->getUserAccount(); //On met en session ses informations $_SESSION['account']['id_users'] = $userAccount->id_users; $_SESSION['account']['nomUser'] = $userAccount->nomUser; $_SESSION['account']['id_roles'] = $userAccount->id_roles; if($_SESSION['account']['id_roles'] == 1) { $userAccount->id_roles; header('location:./index.php'); }else { header('location:./tableauDeBord.php'); //On redirige vers une autre page. }exit(); }else{ $formErrors['pass'] = $formErrors['mail'] = 'Veuillez renseigner vos identifiants valide'; } } }<file_sep>/Controllers/ctrlListeClients.php <?php $clients = new clients(); if(isset($_POST['sendSearch'])){ $search = htmlspecialchars($_POST['search']); $resultsNumber = $clients->countSearchResult($search); $link = 'listeClients.php?search=' . $_GET['search'] . '&sendSearch='; if($resultsNumber == 0 ){ $searchMessage = 'Aucun resultat ne correspond à votre recherche'; }else{ $searchMessage = 'Il y a ' . $resultsNumber . ' résultats'; $listeClients = $clients->searchCatListByName($search); } }else{ $listeClients = $clients->getClients(); $resultsNumber = count($listeClients); $searchMessage = 'Il y a ' . $resultsNumber . ' clients'; $link = 'listeClients.php?'; } if(!empty($_GET['idDelete'])){ $clients->id_Clients = htmlspecialchars($_GET['idDelete']); }else if(!empty($_POST['idDelete'])){ $clients->id_Clients = htmlspecialchars($_POST['idDelete']); }else { $deleteMessage = 'Aucun utilisateur n\'a été sélectionné'; } if(isset($_POST['confirmDelete'])){ if($clients->deleteClient()); header('location:./listeClients.php'); }else { $message = 'une erreur est survenue lors de la suppression'; }<file_sep>/Models/finPoste.php <?php $engineKm = !empty($_GET['enginKm']) ? htmlspecialchars($_GET['enginKm']) : ""; $connexion = mysqli_connect('localhost','root','','digit_engin'); if (!$connexion) { die('Pas de connexion: ' . mysqli_error($connexion)); } mysqli_select_db($connexion,"debutPoste"); $sql=" SELECT `km_reel`,`nomEquipements`, `nomStatut`, `observation`,`imageObservation` FROM `engins` /* JOIN equipements */ JOIN statut /* WHERE `equipements`.`id_equipements` = `engins`.`id_equipements` */ WHERE `statut`.`id_statut` = `engins`.`id_statut` AND `id_Engins`= '".$engineKm."'"; $resultat = mysqli_query($connexion,$sql); while($row = mysqli_fetch_array($resultat)) { echo "<div class='form-group'>"; echo "<label for='km_reel' id='labelForm'>Relevé de compteur</label>"; if ($row['nomStatut'] == 'Disponible') { echo "<input class='form-control text-center' type='number' name='km_reel' value='$row[km_reel]' />"; } else{ echo "<input disabled class='form-control text-center' type='number' name='km_reel' value='$row[km_reel]' />"; } echo "<div class='form-group'>"; echo "<label for='nomEquipements' id='labelForm'>Equipements</label>"; if ($row['nomStatut'] == 'Disponible') { echo "<input oninput='this.value = this.value.toUpperCase()' class='form-control text-center' type='text' name='nomEquipements' value='$row[nomEquipements]' />"; } else{ echo "<input disabled class='form-control text-center' type='text' name='nomEquipements' value='$row[nomEquipements]' />"; } echo "<div class='form-group'>"; echo "<label for='nomStatut' id='labelForm'>Disponible ?</label>"; if ($row['nomStatut'] == 'Disponible') { echo "<input disabled class='form-control text-center' style= 'background: #58C454; color:white' type='text' name='nomStatut' value='$row[nomStatut]'/>"; } else{ echo "<input disabled class='form-control text-center' style= 'background:#E91616; color:white ' type='text' name='nomStatut' value='$row[nomStatut]' />"; } echo "<div class='form-group'>"; echo "<label for='observation' id='labelForm'>Observation</label>"; if ($row['nomStatut'] == 'Disponible') { echo "<input onkeyup='textCounter(this,'counter',300);' class='form-control text-center' type='text' name='observation' value='$row[observation]'/>"; echo "<input disabled maxlength='300' size='22' value= 'Maximum 300 Caractères.' id='counter'/>"; } else{ echo "<textarea disabled class='form-control text-center' type='text' name='observation' value='$row[observation]'></textarea>"; } echo "<div class='form-group'>"; echo "<p id='labelForm'>Image d'anomalie existant</p>"; echo "<img src='$row[imageObservation]' alt='' id='imgObs' width='100' height='100'> "; echo "<div class='form-group'>"; echo "<label for='imageObservation' id='labelForm'>Image d'une Anomalie</label>"; echo "<input id='imageObservation' class='form-control value='$row[imageObservation]' type='file' name='imageObservation' multiple='multiple' />"; } mysqli_close($connexion); ?> <file_sep>/Controllers/ctrlHeader.php <?php //Gestion des actions if(isset($_GET['action'])){ if($_GET['action'] == 'disconnect'){ //Pour deconnecter l'utilisateur on détruit sa session session_destroy(); //Et on le redirige vers l'accueil header('location:./index.php'); exit(); } }<file_sep>/Controllers/ctrlModifTypes.php <?php if(isset($_GET['id_types'])){ $types = new types(); $updatedTypes = new types(); $types->id_types = $_GET['id_types']; if($types->getTypesInfo()){ $types = $types->getTypesInfo(); }else { $modifyMessageFail = '<i class="fas fa-exclamation-triangle"></i> Ce Type n\'éxiste pas'; } } $formErrors = array(); if(isset($_POST['modify'])){ //instancier notre requete de la class types if(!empty($_POST['nomTypes'])){ //J'hydrate mon instance d'objet types $updatedTypes->nomTypes = htmlspecialchars($_POST['nomTypes']); }else{ $formErrors['nomTypes'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Renseigner le nom de type</div>' ; } if(empty($formErrors)){ // On verify si le nomEquipements a été modifié if ($types->nomTypes != $updatedTypes->nomTypes){ //On vérifie si le pseudo est libre if($updatedTypes->checkTypeExist()){ $formErrors['nomTypes'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Le nom type déja existe</div>'; }else { $updatedTypes->id_types = $_GET['id_types']; if($updatedTypes->modifyType()){ $modifyMessageSuccess = '<i class="far fa-check-circle"></i> Le Type a bien été modifié'; }else { $modifyMessageFail = '<i class="fas fa-exclamation-triangle"></i> Pas de modification'; } } }else{ $modifyMessageFail ='<i class="fas fa-exclamation-triangle"></i> Pas de changements'; } } } <file_sep>/ajoutType.php <?php include 'header.php'; include './Models/types.php'; include './Controllers/ctrlAjoutType.php'; ?> <div class="btnAjoutType text-center"> <a class="btn btn-outline-primary btn-sm" href="index.php"><i class="fas fa-home fa-2x"></i> Accueil</a> <!-- Btn CRUD --> <a class="btn btn-outline-primary btn-sm" href="tableauDeBord.php"><i class="fas fa-tachometer-alt fa-2x"></i> Tableau De Bord</a> </div> <!-- Début Formulaire --> <!-- Titre Formulaire --> <h1 class="text-center mt-3" id="titreAjoutEquipement">Ajouter un Type d'engin</h1> <div class="formAjoutType"> <form action="ajoutType.php" method="POST"> <div class="form-group"> <label for="nomTypes" id="labelForm">Nom de Type d'engin</label> <input oninput="this.value = this.value.toUpperCase()" class="form-control" id="nomTypes" <?= count($formErrors) > 0 ? (isset($formErrors['nomTypes']) ? 'is-invalid' : 'is-valid') : '' ?>value="<?= isset($_POST['nomTypes']) ? $_POST['nomTypes'] : '' ?>" type="text" name="nomTypes" /> <small id="help" class="form-text text-muted">Entrez un nouveau type</small> </div> <!--message de succés ou d'erreur--> <p class="formMessage"><?= isset($addTypesMessage) ? $addTypesMessage : '' ?></p> <!-- Btn validation --> <button type="submit" name="addTypes" class="btn btn-primary btn-sm">Valider</button> <button type="reset" class="btn btn-warning btn-sm">Réinitialiser</button> </form> </div> <!-- Affichage de Footer --> <?php include 'footer.php' ?><file_sep>/tableauDeBord.php <?php include 'header.php'; include './Models/engins.php'; include './Models/anomalies.php'; include './Models/clients.php'; include './Models/equipements.php'; include './Controllers/ctrlTableauDeBord.php'; include './Controllers/ctrlListeAnomalies.php'; $session['orderBy'] = isset($_POST['orderBy'])? htmlspecialchars($_POST['orderBy']) : 1; ?> <div class="btnTdbMain text-center"> <a class="btn btn-outline-primary btn-sm" href="index.php"><i class="fas fa-home fa-2x"></i> Accueil</a> <!-- Btn CRUD --> <div class="btn-group" role="group" aria-label="Button group with nested dropdown"> <div class="btn-group" role="group"> <button id="btnGroupeAjout" type="button" class="btn btn-outline-primary dropdown-toggle btn-sm" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="fas fa-plus fa-2x"></i> Ajouter un Entitie</button> <div class="dropdown-menu p-1" aria-labelledby="btnGroupeAjout"> <a class="btn btn-outline-success btn-sm btn-block" href="ajoutEngin.php"><i class="fas fa-dolly"></i> Un Engin</a> <a class="btn btn-outline-success btn-sm btn-block" href="ajoutClient.php"><i class="far fa-building"></i> Un Client</a> <a class="btn btn-outline-success btn-sm btn-block" href="ajoutType.php"><i class="fab fa-typo3"></i> Un Type</a> <a class="btn btn-outline-success btn-sm btn-block" href="ajoutEquipement.php"><i class="fas fa-wrench"></i> Un Equipement</a> <a class="btn btn-outline-danger btn-sm btn-block" href="AjoutAnomalies.php"><i class="fas fa-exclamation"></i> Une Anomalie</a> </div> </div> </div> <div class="btn-group" role="group" aria-label="Button group with nested dropdown"> <div class="btn-group" role="group"> <button id="btnGroupeModif" type="button" class="btn btn-outline-warning dropdown-toggle btn-sm" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="fas fa-pencil-alt fa-2x"></i> Modifier/Supprimer un Entitie</button> <div class="dropdown-menu p-1" aria-labelledby="btnGroupeModif"> <a class="btn btn-outline-warning btn-sm btn-block" href="listeClients.php"><i class="fas fa-edit"></i> Un Client</a> <a class="btn btn-outline-warning btn-sm btn-block" href="listeTypes.php"><i class="fas fa-edit"></i> Un Type</a> <a class="btn btn-outline-warning btn-sm btn-block" href="listeEquipements.php"><i class="fas fa-edit"></i> Un Equipement</a> <a class="btn btn-outline-warning btn-sm btn-block" href="listeAnomalies.php"><i class="fas fa-edit"></i> Une Anomalie</a> </div> </div> </div> </div> <div> <h1 class="text-center" id="titreTdb">Tableau de Bord - Principale</h1> </div> <!-- Avertissement avent Suppression --> <div class="container text-center"> <?php if(isset($_GET['idDelete'])){ ?> <div class="alert text-center alert-dismissible"> <button type="button" class="close" data-dismiss="alert">&times;</button> <h1 class="h4">Voulez-vous supprimer ce Engin?</h1> <form class="text-center" method="POST" action="tableauDeBord.php"> <input type="hidden" name="idDelete" value="<?= $engins->id_Engins?>" /> <button type="submit" class="btn btn-primary btn-sm" name="confirmDelete">Oui</button> <button type="button" class="btn btn-danger btn-sm" data-dismiss="alert">Non</button> </form> </div><?php } ?> </div> <!-- TRI --> <div class="triFiltre"> <form class="form-inline" action="" method="POST"> <div class="form-group"> <label for="tri" id="labelTri"> Trier Par</label> <select name="orderBy" id="tri" value="trier par" class="browser-default custom-select "> <option value="id_Engins" <?php echo ($session['orderBy']=='id_Engins'?'selected':'')?>> Identifiant </option> <option value="nomTypes" <?php echo ($session['orderBy']=='nomTypes'?'selected':'')?>> Type d'Engin </option> <option value="numeroEngin" <?php echo ($session['orderBy']=='numeroEngin'?'selected':'')?>> Numéro </option> <option value="dernierRevision" <?php echo ($session['orderBy']=='dernierRevision'?'selected':'')?>> Dernier Révision</option> <option value="prochainRevision" <?php echo ($session['orderBy']=='prochainRevision'?'selected':'')?>> Prochain Révision</option> <option value="nomStatut" <?php echo ($session['orderBy']=='nomStatut'?'selected':'')?>> Disponiblité </option> <option value="nomEquipements" <?php echo ($session['orderBy']=='nomEquipements'?'selected':'')?>> Equipements</option> <option value="horametre" <?php echo ($session['orderBy']=='horametre'?'selected':'')?>> Horamétre </option> <option value="km_reel" <?php echo ($session['orderBy']=='km_reel'?'selected':'')?>> Kilométrage </option> <option value="nomClients" <?php echo ($session['orderBy']=='nomClients'?'selected':'')?>> Client </option> </select> <div class="form-group mx-sm-3 mb-2"> <button type="submit" class="btn btn-primary btn-sm">Trier</button> </div> <!-- FILTRE --> <input class="form-control" id="filter" type="text" placeholder="Filtre.."> <!-- BUTTON DE EXPORT EN CSV --> <div> <button onclick="exportCSV('xlsx')" type="button" class="btn btn-success btn-sm">Exporter en format csv</button></br> </div> </form> </div> </div> <div class="pl-3 pr-3 tdbPrincipale table-responsive"> <!-- TABLEAU DE BORD --> <table id="tototo" class="table table-hover"> <div> <thead> <tr class="tdbTr"> <th scope="col">Identifiant</th> <th scope="col">Type</th> <th scope="col">Numéro</th> <th scope="col">Dernier Révision</th> <th scope="col">Prochain Révision</th> <th scope="col">Equipements</th> <!-- <th scope="col">Heure/J</th> --> <th scope="col">Horamétre</th> <th scope="col">Kilométrage</th> <th scope="col">Client</th> <!-- <th scope="col">Anomalies</th> --> <th scope="col">Image</th> <th scope="col">Action</th> </tr> </thead> <tbody id="FiltreTable"> <?php foreach ($listeEngins as $EnginsListe){ ?> <tr <?php if($EnginsListe->nomStatut == "Disponible") : ?> style="background-color:#90EE90;" <?php else : ?> style="background-color:#FF7F7F;" <?php endif ?>> <td><?= $EnginsListe->id_Engins ?></td> <td><?= $EnginsListe->nomTypes ?></td> <td><a data-toggle="modal" data-target="#exampleModal"><?= $EnginsListe->numeroEngin ?> </a></td> <td><?= $EnginsListe->dernierRevision ?></td> <td><?= $EnginsListe->prochainRevision ?></td> <td><?= $EnginsListe->nomEquipements?></td> <!-- <td><?= $EnginsListe->heure_jour ?></td> --> <td><?= $EnginsListe->horametre?></td> <td><?= $EnginsListe->km_reel ?></td> <td><?= $EnginsListe->nomClients ?></td> <td><img id="imageEngin" src="<?= $EnginsListe->image?>" alt="imageEngin" /></td> <td> <a href="modifEngin.php?&id_Engins=<?= $EnginsListe->id_Engins ?>"><i class="fas fa-edit"></i></a> <a href="tableauDeBord.php?&idDelete=<?= $EnginsListe->id_Engins ?>"><i class="far fa-trash-alt"></i></a> </td> </tr><?php } ?> </tbody> </table> </div> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="#exampleModal" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModal">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <?php foreach ($listeEngins as $EnginsListe){ ?> <p><?php $EnginsListe->nomEquipements?></p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <?php } ?> <!-- Footer --> <?php include 'footer.php' ?><file_sep>/listeEquipements.php <?php include 'header.php'; include './Models/equipements.php'; include './Controllers/ctrlListeEquipements.php'; ?> <div class="btnListeEquipements text-center"> <a class="btn btn-outline-primary btn-sm" href="index.php"><i class="fas fa-home fa-2x"></i> Accueil</a> <a class="btn btn-outline-primary btn-sm" href="tableauDeBord.php"><i class="fas fa-tachometer-alt fa-2x"></i> Tableau De Bord</a> </div> <div> <h1 class="text-center mt-3" id="titreTdb">Modifier ou Supprimer un Equipement</h1> </div> <!-- Avertissement avent Suppression --> <?php if(isset($_GET['idDelete'])){ ?> <div class="alert text-center alert-dismissible"> <button type="button" class="close" data-dismiss="alert">&times;</button> <h1 class="h4">Voulez-vous supprimer ce Equipement?</h1> <form class="text-center" method="POST" action="listeEquipements.php"> <input type="hidden" name="idDelete" value="<?= $equipements->id_equipements?>" /> <button type="submit" class="btn btn-primary btn-sm" name="confirmDelete">Oui</button> <button type="button" class="btn btn-danger btn-sm" data-dismiss="alert">Non</button> </form> </div><?php } ?> <div class="pl-3 pr-3 tableEquipements table-responsive"> <table class="table table-hover" id="listeEquipements"> <button onclick="exportCSVEquipements('xlsx')" type="button" class="btn btn-success btn-sm float-left mb-1">Exporter en format csv</button> <thead > <tr class="tdbTr"> <th scope="col">Identifiant</th> <th scope="col">Nom de Equipement</th> <th scope="col">Modifier ou Supprimer</th> </tr> </thead> <tbody> <?php foreach ($listeEquipements as $equipementsListe){ ?> <tr> <td><?= $equipementsListe->id_equipements ?></td> <td><?= $equipementsListe->nomEquipements ?></td> <td> <a href="modifEquipements.php?&id_equipements=<?= $equipementsListe->id_equipements ?>"><i class="fas fa-edit fa-2x"></i></a> <a href="listeEquipements.php?&idDelete=<?= $equipementsListe->id_equipements ?>"><i class="far fa-trash-alt fa-2x"></i></a></td> </tr><?php } ?> </tbody> </table> </div> <!-- Footer --> <?php include 'footer.php' ?><file_sep>/Models/engins.php <?php class engins { public $id_Engins = 0; public $nomTypes = ''; public $numeroEngin = ''; public $id_equipements = 0; public $dernierRevision = ''; public $km_reel = ''; public $horametre = ''; public $prochainRevision = ''; public $id_Clients = ''; public $id_types = ''; public $nomClients = ''; public $description = ''; public $id_statut = 0; public $nomEquipements = ''; public $nomStatut = ''; public $imageObservation = ''; public $debutPoste = ''; public $finPoste = ''; public $image = ''; private $db = null; public function __construct(){ $this->db = dataBase::getInstance(); } public function getEngin(){ $getEngin = $this->db->prepare( 'SELECT `id_Engins`, `numeroEngin` FROM `engins`;' ); $getEngin->execute(); return $getEngin->fetchAll(PDO::FETCH_OBJ); } public function getEnginsByNumber(){ $getEngNumber = $this->db->prepare( 'SELECT `id_engins`, `numeroEngin`, `id_types` FROM `engins`;' ); $getEngNumber->execute(); return $getEngNumber->fetchAll(PDO::FETCH_OBJ); } public function getEnginsByClients() { $getEnginsByClientsQuery = $this->db->prepare( 'SELECT `id_Engins`, `id_Types`, `numeroEngin`,/* `id_equipements`, */ `id_statut`,`dernierRevision`, `km_reel` , /* `heure_jour`, */ `horametre`, `prochainRevision`,`id_Clients`,`image` FROM `engins` WHERE `id_Engins` = :id_Engins' ); $getEnginsByClientsQuery->bindValue(':id_Engins', $this->id_Engins, PDO::PARAM_INT); $getEnginsByClientsQuery->execute(); return $getEnginsByClientsQuery->fetchAll(PDO::FETCH_OBJ); } /* public function getAnomaliesByEngin() { $getAnomaliesByEnginQuery = $this->db->prepare( 'SELECT `anomalies`.`description`, `ImageAnom1` ,`ImageAnom2`, `ImageAnom3` FROM `anomalies` WHERE `id_Engins` = :id_Engins' ); $getAnomaliesByEnginQuery->bindValue(':id_Engins', $this->id_Engins, PDO::PARAM_INT); $getAnomaliesByEnginQuery->execute(); return $getAnomaliesByEnginQuery->fetchAll(PDO::FETCH_OBJ); } */ public function checkEnginsExist(){ $checkEnginsExistQuery = $this->db->prepare( 'SELECT COUNT(`id_Engins`) AS `isEnginsExist` FROM `engins` WHERE `typeEngin` = :typeEngin AND `numeroEngin` = :numeroEngin' ); $checkEnginsExistQuery->bindvalue(':typeEngin', $this->typeEngin, PDO::PARAM_STR); $checkEnginsExistQuery->bindvalue(':numeroEngin', $this->numeroEngin, PDO::PARAM_STR); $checkEnginsExistQuery->execute(); $data = $checkEnginsExistQuery->fetch(PDO::FETCH_OBJ); return $data->isEnginsExist; } public function checkIdEnginsExist(){ $checkIdEnginsExistQuery = $this->db->prepare( 'SELECT COUNT(`id_Engins`) AS `isIdEnginsExist` FROM `engins` WHERE `id_Engins` = :id_Engins' ); $checkIdEnginsExistQuery->bindvalue(':id_Engins', $this->id_Engins, PDO::PARAM_INT); $checkIdEnginsExistQuery->execute(); $data = $checkIdEnginsExistQuery->fetch(PDO::FETCH_OBJ); return $data->isIdEnginsExist; } public function addEngins(){ //$db devient une instance de l'objet PDO // on fait une requête préparée $addEnginsQuery = $this->db->prepare( // Marqueur nominatif //bindValue: vérifie le type et que ça ne génère pas de faille de sécurité. //$this-> : permet d'acceder aux attributs de l'instance qui est en cours 'INSERT INTO `engins` ( `numeroEngin`,`nomEquipements`, `id_statut`,`dernierRevision`, `km_reel` , /* `heure_jour`, */ `horametre`, `prochainRevision`,`id_Clients`,`image`,`id_types`) VALUES( :numeroEngin, :nomEquipements, :id_statut,:dernierRevision, :km_reel, /* :heure_jour, */ :horametre, :prochainRevision, :id_Clients, :image,:id_types)' ); $addEnginsQuery->bindvalue(':numeroEngin', $this->numeroEngin, PDO::PARAM_STR); $addEnginsQuery->bindvalue(':nomEquipements', $this->nomEquipements, PDO::PARAM_STR); $addEnginsQuery->bindvalue(':id_statut', $this->id_statut, PDO::PARAM_INT); $addEnginsQuery->bindvalue(':dernierRevision', $this->dernierRevision, PDO::PARAM_STR); $addEnginsQuery->bindvalue(':km_reel', $this->km_reel, PDO::PARAM_INT); /* $addEnginsQuery->bindvalue(':heure_jour', $this->heure_jour, PDO::PARAM_STR); */ $addEnginsQuery->bindvalue(':horametre', $this->horametre, PDO::PARAM_INT); $addEnginsQuery->bindvalue(':prochainRevision', $this->prochainRevision, PDO::PARAM_STR); $addEnginsQuery->bindvalue(':id_Clients', $this->id_Clients, PDO::PARAM_INT); $addEnginsQuery->bindvalue(':image', $this->image, PDO::PARAM_STR); $addEnginsQuery->bindvalue(':id_types', $this->id_types, PDO::PARAM_INT); /* $addEnginsQuery->execute(); $addEnginsQuery = $this->db->prepare( 'SELECT `id_Engins` FROM `engins` ORDER BY `id_Engins` desc limit 1;'); $addEnginsQuery->execute(); $row=$addEnginsQuery->fetch(PDO::FETCH_OBJ); $addEnginsQuery = $this->db->prepare( 'INSERT INTO `anomalies` (`id_Engins`) VALUES (:id_Engins);'); $addEnginsQuery->bindvalue(':id_Engins', $row->id_Engins, PDO::PARAM_STR); */ return $addEnginsQuery->execute(); } public function getEnginsList($orderBy) { $getEnginsListQuery = $this->db->query( /* 'SELECT * FROM `engins` CROSS JOIN types ON engins.id_Engins = types.id_types INNER JOIN equipements ON engins.id_Engins = equipements.id_equipements INNER JOIN anomalies ON engins.id_Engins = anomalies.id_anomalies INNER JOIN clients ON engins.id_Engins = clients.id_clients ORDER BY '.$orderBy.' ;' */ /* 'SELECT `engins`.`id_Engins`, `nomTypes`, `nomClients` , `numeroEngin`,`nomEquipements`, `description`, `ImageAnom1` ,`ImageAnom2`, `ImageAnom3`, `statut`,`dernierRevision`, `km_reel` , `heure_jour`, `horametre`, `prochainRevision`,`image` FROM `clients` INNER JOIN `engins` ON `clients`.`id_clients` = `engins`.`id_clients` INNER JOIN `types` ON `types`.`id_types` = `engins`.`id_types` INNER JOIN `equipements` ON `equipements`.`id_equipements` = `engins`.`id_equipements` INNER JOIN `anomalies` ON `engins`.`id_Engins`= `anomalies`.`id_Engins` ORDER BY '.$orderBy.' ;' */ 'SELECT TIME_FORMAT(horametre,"%H:%i") AS horametre, `engins`.`id_Engins`, `nomTypes`, `nomClients` , `numeroEngin`,`nomEquipements`, /* `anomalies`.`description`, `ImageAnom1` ,`ImageAnom2`, `ImageAnom3`, */`nomStatut`,`dernierRevision`, `km_reel` , /* `heure_jour`, */ `prochainRevision`,`image`, `engins`.`id_types` FROM `engins` JOIN `clients` JOIN `types` /* JOIN `equipements` */ JOIN `statut` /* JOIN `anomalies` */ WHERE `clients`.`id_clients` = `engins`.`id_clients` AND `types`.`id_types` = `engins`.`id_types` /* AND `equipements`.`id_equipements` = `engins`.`id_equipements` */ /* AND `anomalies`.`id_Engins` = `engins`.`id_Engins` */ AND `engins`.`id_Engins` = `engins`.`id_Engins` AND `statut`.`id_statut` = `engins`.`id_statut` GROUP BY `engins`.`id_engins` ORDER BY '.$orderBy.';' ); return $getEnginsListQuery->fetchAll(PDO::FETCH_OBJ); } /* DEBUT POSTE */ public function getInfoByEngin() { $getInfoByEnginQuery = $this->db->prepare( 'SELECT `km_reel` FROM `engins` WHERE `id_Engins` = :id_Engins' ); $getInfoByEnginQuery->bindValue(':id_Engins', $this->id_Engins, PDO::PARAM_INT); $getInfoByEnginQuery->execute(); return $getInfoByEnginQuery->fetch(PDO::FETCH_OBJ); } public function getEnginsInfo() { $getEnginsInfoQuery = $this->db->prepare( 'SELECT `id_types`, `numeroEngin`, `nomEquipements`,`imageObservation`, `debutPoste`, `finPoste`, `id_statut`,`dernierRevision`, `km_reel` , /* `heure_jour`, */ `horametre`, `prochainRevision`,`id_Clients`, `engins`.`image` FROM `engins` WHERE `id_Engins` = :id_Engins' ); $getEnginsInfoQuery->bindValue(':id_Engins', $this->id_Engins, PDO::PARAM_INT); $getEnginsInfoQuery->execute(); return $getEnginsInfoQuery->fetch(PDO::FETCH_OBJ); } public function modifyEnginsInfo(){ $modifyEnginsInfoQuery = $this->db->prepare( 'UPDATE `engins` SET `numeroEngin` = :numeroEngin, /* `id_equipements` = :id_equipements, */ `id_statut` = :id_statut, `dernierRevision` = :dernierRevision, `km_reel` = :km_reel, /* `heure_jour` = :heure_jour, */ `horametre` = :horametre, `prochainRevision` = :prochainRevision, `id_Clients` = :id_Clients, `image` = :image, `id_types` = :id_types WHERE `id_Engins` = :id_Engins' ); $modifyEnginsInfoQuery->bindvalue(':id_Engins', $this->id_Engins, PDO::PARAM_INT); $modifyEnginsInfoQuery->bindvalue(':numeroEngin', $this->numeroEngin, PDO::PARAM_STR); /* $modifyEnginsInfoQuery->bindvalue(':id_equipements', $this->id_equipements, PDO::PARAM_INT); */ $modifyEnginsInfoQuery->bindvalue(':id_statut', $this->id_statut, PDO::PARAM_INT); $modifyEnginsInfoQuery->bindvalue(':dernierRevision', $this->dernierRevision, PDO::PARAM_STR); $modifyEnginsInfoQuery->bindvalue(':km_reel', $this->km_reel, PDO::PARAM_INT); /* $modifyEnginsInfoQuery->bindvalue(':heure_jour', $this->heure_jour, PDO::PARAM_STR) */; $modifyEnginsInfoQuery->bindvalue(':horametre', $this->horametre, PDO::PARAM_STR); $modifyEnginsInfoQuery->bindvalue(':prochainRevision', $this->prochainRevision, PDO::PARAM_STR); $modifyEnginsInfoQuery->bindvalue(':id_Clients', $this->id_Clients, PDO::PARAM_INT); $modifyEnginsInfoQuery->bindvalue(':image', $this->image, PDO::PARAM_STR); $modifyEnginsInfoQuery->bindvalue(':id_types', $this->id_types, PDO::PARAM_INT); return $modifyEnginsInfoQuery->execute(); } public function addDebutPoste(){ $addDebutPosteQuery = $this->db->prepare( 'UPDATE `engins` SET `id_Engins` = :id_Engins, `debutPoste` = :debutPoste, `numeroEngin` = :numeroEngin, `km_reel` = :km_reel, `nomEquipements` = :nomEquipements, `imageObservation` = :imageObservation, `observation` = :observation WHERE `id_Engins` = :id_Engins' ); $addDebutPosteQuery->bindvalue(':id_Engins', $this->id_Engins, PDO::PARAM_INT); $addDebutPosteQuery->bindvalue(':debutPoste', $this->debutPoste, PDO::PARAM_STR); $addDebutPosteQuery->bindvalue(':numeroEngin', $this->numeroEngin, PDO::PARAM_STR); $addDebutPosteQuery->bindvalue(':km_reel', $this->km_reel, PDO::PARAM_INT); $addDebutPosteQuery->bindvalue(':nomEquipements', $this->nomEquipements, PDO::PARAM_STR); $addDebutPosteQuery->bindvalue(':imageObservation', $this->imageObservation, PDO::PARAM_STR); $addDebutPosteQuery->bindvalue(':observation', $this->observation, PDO::PARAM_STR); return $addDebutPosteQuery->execute(); } public function addFinPoste(){ $addFinPosteQuery = $this->db->prepare( 'UPDATE `engins` SET `id_Engins` = :id_Engins, `finPoste` = :finPoste, `numeroEngin` = :numeroEngin, `km_reel` = :km_reel, `nomEquipements` = :nomEquipements, `imageObservation` = :imageObservation, `observation` = :observation WHERE `id_Engins` = :id_Engins' ); $addFinPosteQuery->bindvalue(':id_Engins', $this->id_Engins, PDO::PARAM_INT); $addFinPosteQuery->bindvalue(':finPoste', $this->finPoste, PDO::PARAM_STR); $addFinPosteQuery->bindvalue(':numeroEngin', $this->numeroEngin, PDO::PARAM_STR); $addFinPosteQuery->bindvalue(':km_reel', $this->km_reel, PDO::PARAM_INT); $addFinPosteQuery->bindvalue(':nomEquipements', $this->nomEquipements, PDO::PARAM_STR); $addFinPosteQuery->bindvalue(':imageObservation', $this->imageObservation, PDO::PARAM_STR); $addFinPosteQuery->bindvalue(':observation', $this->observation, PDO::PARAM_STR); return $addFinPosteQuery->execute(); } public function modifyHorametre(){ $modifyHorametreQuery = $this->db->prepare( 'UPDATE engins SET horametre = horametre + TIMEDIFF(finPoste , debutPoste) WHERE id_Engins = :id_Engins' ); $modifyHorametreQuery->bindvalue(':id_Engins', $this->id_Engins, PDO::PARAM_INT); return $modifyHorametreQuery->execute(); } public function deleteEngins() { $deleteEnginsQuery = $this->db->prepare( 'DELETE FROM `engins` WHERE `id_Engins` = :id_Engins' ); $deleteEnginsQuery->bindValue(':id_Engins', $this->id_Engins, PDO::PARAM_INT); return $deleteEnginsQuery->execute(); } }<file_sep>/Controllers/ctrlDebutPoste.php <?php $formErrors = array(); $engins = new engins(); $enginsListe = $engins->getEngin(); if (isset($_POST['id_Engins'])) { $engins ->id_Engins = htmlspecialchars($_POST['id_Engins']); $enginsInfo = $engins->getEnginsInfo(); } if (isset($_POST['addDebutPoste'])) { /* NUMERO ENGIN */ if (!empty(['numeroEngin'])) { $engins->numeroEngin = htmlspecialchars($enginsInfo->numeroEngin); } else { $formErrors['numeroEngin'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> L\'information n\'est pas renseigné</div>'; } if (!empty($_POST['debutPoste'])) { $engins->debutPoste = $_POST['debutPoste']; } else { $formErrors['debutPoste'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Vous n\'avez pas renseigné le kilométrage</div>'; } /* CTRL KM REEL */ if (!empty($_POST['km_reel'])) { $engins->km_reel = $_POST['km_reel']; } else { $formErrors['km_reel'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Vous n\'avez pas renseigné le kilométrage</div>'; } /* CTRL EQUIPEMENTS */ if (!empty($_POST['nomEquipements'])) { $engins->nomEquipements = $_POST['nomEquipements']; } else { $formErrors['nomEquipements'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Vous n\'avez pas renseigné l\'equipements</div>'; } /* CTRL OBSERVATION */ if (!empty($_POST['observation'])) { $engins->observation = $_POST['observation']; } else { $formErrors['observation'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Vous n\'avez pas renseigné l\'observation</div>'; } /* IMAGE */ if (!empty($_FILES['imageObservation']) && $_FILES['imageObservation']['error'] == 0) { // On stock dans $fileInfos les informations concernant le chemin du fichier. $fileInfos = pathinfo($_FILES['imageObservation']['name']); // On crée un tableau contenant les extensions autorisées. $fileExtension = ['jpg', 'jpeg', 'png','JPG','JPEG', 'PNG']; // On verifie si l'extension de notre fichier est dans le tableau des extension autorisées. if (in_array($fileInfos['extension'], $fileExtension)) { //On définit le chemin vers lequel uploader le fichier $path = './Assets/ImgAnomalies/'; //On crée une date pour différencier les fichiers $date = date('Y-m-d_H-i-s'); //On crée le nouveau nom du fichier (celui qu'il aura une fois uploadé) $fileNewName = $_FILES['imageObservation']['name']; //On stocke dans une variable le chemin complet du fichier (chemin + nouveau nom + extension une fois uploadé) Attention : ne pas oublier le point $imageObservation = $path . $fileNewName ; //move_uploaded_files : déplace le fichier depuis son emplacement temporaire ($_FILES['file']['tmp_name']) vers son emplacement définitif ($fileFullPath) if (move_uploaded_file($_FILES['imageObservation']['tmp_name'], $imageObservation)) { //On définit les droits du fichiers uploadé (Ici : écriture et lecture pour l'utilisateur apache, lecture uniquement pour le groupe et tout le monde) chmod($imageObservation, 0644); $engins->imageObservation = $imageObservation; }else { $formErrors['imageObservation'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Votre fichier ne s\'est pas téléversé correctement</div>'; } }else { $formErrors['imageObservation'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Votre fichier n\'est pas du format attendu</div>'; } }else { /* $formErrors['imageObservation'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Veuillez selectionner un fichier</div>'; */ $engins->imageObservation = $enginsInfo->imageObservation; } if (empty($formErrors)) { if ($engins->checkIdEnginsExist() > 0 ){ if($engins->addDebutPoste()){ $addDebutPoste = '<div class="alert alert-success" role="alert"><i class="far fa-check-circle"></i> Les informations à bien été ajouté.</div>'; } else { $addDebutPoste = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Une erreur est survenue.</div>'; } } else { $addDebutPoste = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> L\'engin existe.</div>'; } } }<file_sep>/modifEngin.php <?php include 'header.php'; include_once './Models/engins.php'; include_once './Models/types.php'; include_once './Models/equipements.php'; include_once './Models/clients.php'; include_once './Models/statut.php'; include './Controllers/ctrlModifEngin.php'; ?> <div class="btnModif text-center"> <a class="btn btn-outline-primary btn-sm" href="index.php"><i class="fas fa-home fa-2x"></i> Accueil</a> <!-- Btn CRUD --> <a class="btn btn-outline-primary btn-sm" href="tableauDeBord.php"><i class="fas fa-tachometer-alt fa-2x"></i> Tableau De Bord</a> </div> <!-- Titre Formulaire --> <h1 class="text-center" id="titreModif">Modifier un Engin</h1> <div class="formModif"> <?php if(isset($enginsInfo)){ ?> <form action="modifEngin.php?id_Engins=<?= $_GET['id_Engins'] ?>" method="POST" enctype="multipart/form-data"> <!--message de succés ou d'erreur--> <p class="formMessage"><?= isset($modifEnginMessage) ? $modifEnginMessage : '' ?></p> <!-- TYPE D'ENGINE --> <div class="form-group"> <label for="typeEngin" id="labelForm">Type d'engin</label> <select id="typeEngin" class="form-control" name="id_types"> <option disabled>Choisissez le Type :</option><?php /* Récupere l'item sélectionné */ $selected = $enginsInfo->id_types; foreach($typesListe as $types){ ?> <option value="<?= $types->id_types?> " <?= ($types->id_types == $selected)? 'selected': '' ?>> <?= $types->id_types . ' . ' . $types->nomTypes?></option><?php } ?> </select> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['id_types']) ? $formErrors['id_types'] : '' ?></p> </div> <!-- NUMERO D'ENGIN --> <div class="form-group"> <label for="numeroEngin" id="labelForm">Numéro d'engin</label> <input oninput="this.value = this.value.toUpperCase()" class="form-control" id="numeroEngin" <?= count($formErrors) > 0 ? (isset($formErrors['numeroEngin']) ? 'is-invalid' : 'is-valid') : '' ?>value="<?= !empty($_POST['numeroEngin']) ? $_POST['numeroEngin'] : $enginsInfo->numeroEngin ?>" type="text" name="numeroEngin" /> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['numeroEngin']) ? $formErrors['numeroEngin'] : '' ?></p> </div> <!-- EQUIPEMENTS --> <div class="form-group"> <label for="equipements" id="labelForm">Le(s) Equipement(s)</label> <input oninput="this.value = this.value.toUpperCase()" class="form-control" id="nomEquipements" <?= count($formErrors) > 0 ? (isset($formErrors['nomEquipements']) ? 'is-invalid' : 'is-valid') : '' ?>value="<?= isset($_POST['nomEquipements']) ? $_POST['nomEquipements'] : $enginsInfo->nomEquipements ?>" type="text" name="nomEquipements" /> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['nomEquipements']) ? $formErrors['nomEquipements'] : '' ?></p> </div> <!-- STATUT --> <div class="form-group"> <label for="statut" id="labelForm">Disponibilité</label> <select class="form-control" id="statut" name="id_statut"> <option disabled>Choisissez le statut :</option><?php /* Récupere l'item sélectionné */ $statutSelected = $enginsInfo->id_statut; /* $selectedEquipements = $equipementsSelected->id_equipements; */ foreach($statutListe as $statut){ ?> <option value="<?= $statut->id_statut ?>" <?= ($statut->id_statut == $statutSelected)? "selected": "" ?>> <?= $statut->id_statut . ' . ' . $statut->nomStatut ?></option><?php } ?> </select> <p class="errorForm"><?= isset($formErrors['statut']) ? $formErrors['statut'] : '' ?></p> </div> <!-- DERNIER REVISION --> <div class="form-group"> <label for="dernierRevision" id="labelForm">Dernier Revision</label> <input class="form-control" id="dernierRevision" <?= count($formErrors) > 0 ? (isset($formErrors['dernierRevision']) ? 'is-invalid' : 'is-valid') : '' ?>value="<?= isset($_POST['dernierRevision']) ? $_POST['dernierRevision'] : $enginsInfo->dernierRevision ?>" type="date" name="dernierRevision" /> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['dernierRevision']) ? $formErrors['dernierRevision'] : '' ?></p> </div> <!-- PROCHAIN REVISION --> <div class="form-group"> <label for="prochainRevision" id="labelForm">Prochain Revision</label> <input class="form-control" id="prochainRevision" <?= count($formErrors) > 0 ? (isset($formErrors['prochainRevision']) ? 'is-invalid' : 'is-valid') : '' ?>value="<?= isset($_POST['prochainRevision']) ? $_POST['prochainRevision'] : $enginsInfo->prochainRevision ?>" type="date" name="prochainRevision" /> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['prochainRevision']) ? $formErrors['prochainRevision'] : '' ?> </p> </div> <!-- KM REEL --> <div class="form-group"> <label for="km_reel" id="labelForm">Kilométrage</label> <input class="form-control" id="km_reel" <?= count($formErrors) > 0 ? (isset($formErrors['km_reel']) ? 'is-invalid' : 'is-valid') : '' ?>value="<?= isset($_POST['km_reel']) ? $_POST['km_reel'] : $enginsInfo->km_reel ?>" type="number" name="km_reel" /> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['km_reel']) ? $formErrors['km_reel'] : '' ?></p> </div> <!-- HORAMETRE --> <div class="form-group"> <label for="horametre" id="labelForm">Horamétre</label> <input class="form-control" id="horametre" <?= count($formErrors) > 0 ? (isset($formErrors['horametre']) ? 'is-invalid' : 'is-valid') : ''?>value="<?= isset($_POST['horametre']) ? $_POST['horametre'] : $enginsInfo->horametre?>" type="time" name="horametre" /> <small>Ex : 234 H 56 M</small> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['horametre']) ? $formErrors['horametre'] : '' ?></p> </div> <!-- CLIENT --> <div class="form-group"> <label for="client" id="labelForm">Client</label> <select id="client" class="form-control" name="id_Clients"> <option disabled>Choisissez le Client :</option><?php /* Récupere l'item sélectionné */ $selectedClient = $enginsInfo->id_Clients; foreach($clientsListe as $clients){ ?> <option value="<?= $clients->id_Clients ?>" <?= ($clients->id_Clients == $selectedClient)? "selected": "" ?>> <?= $clients->id_Clients . ' . ' . $clients->nomClients ?></option><?php } ?> </select> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['id_Clients']) ? $formErrors['id_Clients'] : '' ?></p> </div> <!-- IMAGE --> <div class="form-group"> <label for="image" id="labelForm">Image</label> <input id="image" class="form-control <?= count($formErrors) > 0 ? (isset($formErrors['image']) ? 'is-invalid' : 'is-valid') : '' ?>" value="<?= isset($_POST['image']) ? $_POST['image'] :'' ?>" type="file" name="image" /> <!--message d'erreur--> <p class="errorForm"><?= isset($formErrors['image']) ? $formErrors['image'] : '' ?></p> </div> <!-- Btn validation --> <div> <button type="submit" name="modifyEngin" class="btn btn-primary btn-sm">Valider</button> <button type="reset" class="btn btn-warning btn-sm">Réinitialiser</button> </div> </form> </div> <?php } ?> <?php include 'footer.php';<file_sep>/Controllers/ctrlModifClient.php <?php if(isset($_GET['id_Clients'])){ $clients = new clients(); $updatedClients = new clients(); $clients->id_Clients = $_GET['id_Clients']; if($clients->getClientInfo()){ $clients = $clients->getClientInfo(); }else { $modifyMessageFail = '<i class="fas fa-exclamation-triangle"></i> Ce Client n\'éxiste pas'; } } $formErrors = array(); if(isset($_POST['modify'])){ //instancier notre requete de la class clients if(!empty($_POST['nomClients'])){ //J'hydrate mon instance d'objet clients $updatedClients->nomClients = htmlspecialchars($_POST['nomClients']); }else{ $formErrors['nomClients'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Renseigner le nom de client</div>' ; } if(empty($formErrors)){ // On verify si le nomClients a été modifié if ($clients->nomClients != $updatedClients->nomClients){ //On vérifie si le pseudo est libre if($updatedClients->checkClientExist()){ $formErrors['nomClients'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Le nom client déja existe</div>'; }else { $updatedClients->id_Clients = $_GET['id_Clients']; if($updatedClients->modifyClient()){ $modifyMessageSuccess = '<i class="far fa-check-circle"></i> Le Client a bien été modifié'; }else { $modifyMessageFail = '<i class="fas fa-exclamation-triangle"></i> Pas de modification'; } } }else{ $modifyMessageFail ='<i class="fas fa-exclamation-triangle"></i> Pas de changements'; } } } <file_sep>/listeAnomalies.php <?php include 'header.php'; include './Models/anomalies.php'; include './Controllers/ctrlListeAnomalies.php'; ?> <div class="btnListeClients text-center"> <a class="btn btn-outline-primary btn-sm" href="index.php"><i class="fas fa-home fa-2x"></i> Accueil</a> <a class="btn btn-outline-primary btn-sm" href="tableauDeBord.php"><i class="fas fa-tachometer-alt fa-2x"></i> Tableau De Bord</a> </div> <div> <h1 class="text-center mt-3" id="titreTdb">Modifier ou Supprimer une Anomalie</h1> </div> <!-- Avertissement avent Suppression --> <?php if(isset($_GET['idDelete'])){ ?> <div class="alert text-center alert-dismissible"> <button type="button" class="close" data-dismiss="alert">&times;</button> <h1 class="h4">Voulez-vous supprimer cette Anomalie?</h1> <form class="text-center" method="POST" action="listeAnomalies.php"> <input type="hidden" name="idDelete" value="<?= $anomalies->id_anomalies?>" /> <button type="submit" class="btn btn-primary btn-sm" name="confirmDelete">Oui</button> <button type="button" class="btn btn-danger btn-sm" data-dismiss="alert">Non</button> </form> </div><?php } ?> <div class="pl-3 pr-3 tableAnomalies table-responsive"> <table class="table table-hover" id="listeAnomalies"> <button onclick="exportCSVAnomalies('xlsx')" type="button" class="btn btn-success btn-sm float-left mb-1">Exporter en format csv</button> <thead > <tr class="tdbTr"> <th scope="col">Identifiant</th> <th scope="col">Observation</th> <th scope="col">Numéro Engin</th> <th scope="col">Image 1</th> <th scope="col">Image 2</th> <th scope="col">Image 3</th> <th scope="col">Modifier ou Supprimer</th> </tr> </thead> <tbody> <?php foreach ($listeAnomalies as $anomalies){ ?> <tr> <td><?= $anomalies->id_anomalies ?></td> <td><?= $anomalies->description ?></td> <td><?= $anomalies->numeroEngin ?></td> <td><img id="imgAnomalies" src="<?= $anomalies->imageAnom1?>" alt="ImgAnomalies1" height="30" width="30"></img></td> <td><img id="imgAnomalies" src="<?= $anomalies->imageAnom2?>" alt="ImgAnomalies2" height="30" width="30"></img></td> <td><img id="imgAnomalies" src="<?= $anomalies->imageAnom3?>" alt="ImgAnomalies3" height="30" width="30"></img></td> <td> <a href="modifAnomalies.php?&id_anomalies=<?= $anomalies->id_anomalies ?>"><i class="fas fa-edit fa-2x"></i></a> <a href="listeAnomalies.php?&idDelete=<?= $anomalies->id_anomalies ?>"><i class="far fa-trash-alt fa-2x"></i></a></td> </tr><?php } ?> </tbody> </table> </div> <!-- Footer --> <?php include 'footer.php' ?><file_sep>/Assets/Scripts/main.js /* CSV FORMAT TYPES*/ function exportCSVTypes(type, fn, dl) { var elt = document.getElementById('listeTypes'); var wb = XLSX.utils.table_to_book(elt, { sheet: "Sheet1" }); return dl ? XLSX.write(wb, { bookType: type, bookSST: true, type: 'base64' }) : XLSX.writeFile(wb, fn || ('Liste_Types_Engins.' + (type || 'xlsx'))); } /* CSV FORMAT EQUIPEMENTS*/ function exportCSVEquipements(type, fn, dl) { var elt = document.getElementById('listeEquipements'); var wb = XLSX.utils.table_to_book(elt, { sheet: "Sheet JS" }); return dl ? XLSX.write(wb, { bookType: type, bookSST: true, type: 'base64' }) : XLSX.writeFile(wb, fn || ('Liste_equipements_sur_engin.' + (type || 'xlsx'))); } /* CSV FORMAT CLIENTS*/ function exportCSVClients(type, fn, dl) { var elt = document.getElementById('listeClients'); var wb = XLSX.utils.table_to_book(elt, { sheet: "Sheet JS" }); return dl ? XLSX.write(wb, { bookType: type, bookSST: true, type: 'base64' }) : XLSX.writeFile(wb, fn || ('Liste_clients.' + (type || 'xlsx'))); } /* CSV FORMAT ANOMALIES*/ function exportCSVAnomalies(type, fn, dl) { var elt = document.getElementById('listeAnomalies'); var wb = XLSX.utils.table_to_book(elt, { sheet: "Sheet JS" }); return dl ? XLSX.write(wb, { bookType: type, bookSST: true, type: 'base64' }) : XLSX.writeFile(wb, fn || ('Liste_Anomalies.' + (type || 'xlsx'))); } /* ZOOM IMAGES */ function zoomIn() { /* console.log('test'); */ imgAnomalies.height *= 2; imgAnomalies.width *= 2; /* console.log('test2'); */ } function zoomOut() { imgAnomalies.height = imgAnomalies.height / 2; imgAnomalies.width = imgAnomalies.width / 2; } /* LIMITATION DES CHARECTEURS SUR OBSERVATION */ function textCounter(field, field2, maxlimit) { var countfield = document.getElementById(field2); if (field.value.length > maxlimit) { field.value = field.value.substring(0, maxlimit); return false; } else { countfield.value = maxlimit - field.value.length + " Caractères restent"; } } /* FILTRE TABLE */ $(document).ready(function() { $("#filter").on("keyup", function() { var value = $(this).val().toLowerCase(); $("#FiltreTable tr").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) }); }); }); /* DATE ET L'HEURE */ /* document.getElementById('dateHeure').value = new Date().toDateInputValue(); */ /* KM BY ENGIN */ function selectEngin(str) { if (str == "") { document.getElementById("prisePosteInfo").innerHTML = ""; return; } else { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("prisePosteInfo").innerHTML = this.responseText; } }; xmlhttp.open("GET", "./Models/debPoste.php?enginKm=" + str, true); xmlhttp.send(); } } /*compte*/ function checkUnavailability(input) { //Instanciation de l'objet XMLHttpRequest permettant de faire de l'AJAX var request = new XMLHttpRequest(); //Les données sont envoyés en POST et c'est le controlleur qui va les traiter request.open('POST', 'Controllers/ctrlInscription.php', true); //Au changement d'état de la demande d'AJAX request.onreadystatechange = function() { //Si on a bien fini de recevoir la réponse de PHP (4) et que le code retour HTTP est ok (200) if (request.readyState == 4 && request.status == 200) { if (request.responseText == 1) { //Dans le cas ou la valeur dans le champ est déjà en BDD input.classList.remove('is-valid'); input.classList.add('is-invalid'); } else if (request.responseText == 2) { //Dans le cas où le champ est vide input.classList.remove('is-valid', 'is-invalid'); } else { //Dans le cas ou la valeur dans le champ n'est pas en BDD input.classList.remove('is-invalid'); input.classList.add('is-valid'); } }; } // Pour dire au serveur qu'il y a des données en POST à lire dans le corps request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); //Les données envoyées en POST. Elles sont séparées par un & request.send('fieldValue=' + input.value + '&fieldName=' + input.name); }<file_sep>/Controllers/ctrlAjoutEquipement.php <?php $formErrors = array(); $equipements = new equipements(); /* if (isset($_POST['addType'])) { */ if (!empty($_POST['nomEquipements'])) { $equipements->nomEquipements = htmlspecialchars($_POST['nomEquipements']); } else { $formErrors['nomEquipements'] = 'L\'information n\'est pas renseigné'; } // Validation// if (empty($formErrors['nomEquipements'])) { if (!$equipements->checkEquipementsExist()){ if($equipements->addEquipements()){ $addEquipementMessage = '<div class="alert alert-success" role="alert"><i class="far fa-check-circle"></i> Le client a bien été ajouté</div>'; } else { $addEquipementMessage = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Une erreur est survenue.</div>'; } } else { $addEquipementMessage = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Le client existe.</div>'; } } /* } */<file_sep>/Controllers/ctrlAjoutClient.php <?php $formErrors = array(); $clients = new clients(); /* if (isset($_POST['addClient'])) { */ if (!empty($_POST['nomClients'])) { $clients->nomClients = htmlspecialchars($_POST['nomClients']); } else { $formErrors['nomClients'] = 'L\'information n\'est pas renseigné'; } // Validation// if (empty($formErrors['nomClients'])) { if (!$clients->checkClientExist()){ if($clients->addClient()){ $addClientMessage = '<div class="alert alert-success" role="alert"><i class="far fa-check-circle"></i> Le client a bien été ajouté</div>'; } else { $addClientMessage = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Une erreur est survenue.</div>'; } } else { $addClientMessage = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Le client existe.</div>'; } } /* } */<file_sep>/Controllers/ctrlModifEngin.php <?php $formErrors = array(); $types = new types(); $typesListe = $types->getType(); $statut = new statut(); $statutListe = $statut->getStatut(); $equipements = new equipements(); $equipementsListe = $equipements->getEquipements(); $clients = new clients(); $clientsListe = $clients->getClients(); if (isset($_GET ['id_Engins'])) { $engins = new engins(); $engins ->id_Engins = htmlspecialchars($_GET['id_Engins']); $enginsInfo = $engins->getEnginsInfo(); } if (isset($_POST['modifyEngin'])) { if(!empty($_POST['id_types'])){ $types->id_types = htmlspecialchars($_POST['id_types']); if($types->getType()){ $engins->id_types = $types->id_types; }else { $formErrors['id_types'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Une erreur s\'est produite.</div>'; } }else { $formErrors['id_types'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Vous n\'avez pas sélectionné un Type d\'engin</div>'; } /* NUMERO ENGIN */ if (!empty($_POST['numeroEngin'])) { $engins->numeroEngin = htmlspecialchars($_POST['numeroEngin']); } else { $formErrors['numeroEngin'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> L\'information n\'est pas renseigné</div>'; } /* CTRL STATUT */ if(!empty($_POST['id_statut'])){ $statut->id_statut = htmlspecialchars($_POST['id_statut']); if($statut->getStatut()){ $engins->id_statut = $statut->id_statut; }else { $formErrors['id_statut'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Une erreur s\'est produite.</div>'; } }else { $formErrors['id_statut'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Vous n\'avez pas sélectionné un Statut d\'engin</div>'; } /* CTRL DERNIER REVISION */ if (!empty($_POST['dernierRevision'])) { $engins->dernierRevision = $_POST['dernierRevision']; } else { $formErrors['dernierRevision'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Vous n\'avez pas sélectionné une date</div>'; } /* CTRL PROCHAIN REVISION */ if (!empty($_POST['prochainRevision'])) { $engins->prochainRevision = $_POST['prochainRevision']; } else { $formErrors['prochainRevision'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Vous n\'avez pas sélectionné une date</div>'; } /* CTRL KM REEL */ if (!empty($_POST['km_reel'])) { $engins->km_reel = $_POST['km_reel']; } else { $formErrors['km_reel'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Vous n\'avez pas renseigné le kilométrage</div>'; } /* CTRL HORAMETRE */ if (!empty($_POST['horametre'])) { $engins->horametre = $_POST['horametre']; } else { $formErrors['horametre'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Vous n\'avez pas renseigné le horametre</div>'; } /* CTRL CLIENTS */ if(!empty($_POST['id_Clients'])){ $clients->id_Clients = htmlspecialchars($_POST['id_Clients']); if($clients->getClients()){ $engins->id_Clients = $clients->id_Clients; }else { $formErrors['nomClients'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Une erreid_Clientsur s\'est produite.</div>'; } }else { $formErrors['nomClients'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Vous n\'avez pas sélectionné un client.</div>'; } /* CTRL EQUIPEMENTS */ if (!empty($_POST['nomEquipements'])) { $engins->nomEquipements = $_POST['nomEquipements']; } else { $formErrors['nomEquipements'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Vous n\'avez pas renseigné un Equipement</div>'; } /* IMAGE */ if (!empty($_FILES['image']) && $_FILES['image']['error'] == 0) { // On stock dans $fileInfos les informations concernant le chemin du fichier. $fileInfos = pathinfo($_FILES['image']['name']); // On crée un tableau contenant les extensions autorisées. $fileExtension = ['jpg', 'jpeg', 'png','JPG','JPEG', 'PNG']; // On verifie si l'extension de notre fichier est dans le tableau des extension autorisées. if (in_array($fileInfos['extension'], $fileExtension)) { //On définit le chemin vers lequel uploader le fichier $path = './Assets/Img/'; //On crée une date pour différencier les fichiers $date = date('Y-m-d_H-i-s'); //On crée le nouveau nom du fichier (celui qu'il aura une fois uploadé) $fileNewName = $_FILES['image']['name']; //On stocke dans une variable le chemin complet du fichier (chemin + nouveau nom + extension une fois uploadé) Attention : ne pas oublier le point $EnginPhoto = $path . $fileNewName ; //move_uploaded_files : déplace le fichier depuis son emplacement temporaire ($_FILES['file']['tmp_name']) vers son emplacement définitif ($fileFullPath) if (move_uploaded_file($_FILES['image']['tmp_name'], $EnginPhoto)) { //On définit les droits du fichiers uploadé (Ici : écriture et lecture pour l'utilisateur apache, lecture uniquement pour le groupe et tout le monde) chmod($EnginPhoto, 0644); $engins->image = $EnginPhoto; }else { $formErrors['image'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Votre fichier ne s\'est pas téléversé correctement</div>'; } }else { $formErrors['image'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Votre fichier n\'est pas du format attendu</div>'; } }else { /* $formErrors['image'] = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Veuillez selectionner un fichier</div>'; */ $engins->image = $enginsInfo->image; /* } */ if (empty($formErrors)) { if (0<$engins->checkIdEnginsExist()){ if($engins->modifyEnginsInfo()){ $modifEnginMessage = '<div class="alert alert-success" role="alert"><i class="far fa-check-circle"></i> l\'engin a été Modifié.</div>'; } else { $modifEnginMessage = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Une erreur est survenue.</div>'; } } else { $modifEnginMessage = '<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> L\'engin n\'existe pas.</div>'; } } } }<file_sep>/Controllers/ctrlAnomalies.php <?php $regexPrice = '^([1-9]|([1-9][0-9]+))\.[0-9]{2}$^'; $regexName = '^([A-ÿ0-9\ \%\-\.\/\,\;\:\!\?\(\)\'\"\€\&])+$^'; $regexRef = '^[[:alnum:]]+^'; $formErrors = array(); //instancier notre requete de la class categories $anomalies = new anomalies(); $anomalies = $anomalies->getAnomalies(); $engins = new engins(); $numeroEnginListe = $engins->getEnginsByNumber(); if (isset($_POST['addAnomalies'])) { //instancier notre requete de la class anomalies $anomalies = new anomalies(); //verification formulaire pour ajouter un anomalies if(!empty($_POST['numeroEngin'])){ $engins->id_Engins = htmlspecialchars($_POST['numeroEngin']); if($engins->getEnginsByNumber()){ $anomalies->id_Engins = $engins->id_Engins; }else { $formErrors['numeroEngin'] = 'Une erreur s\'est '; } }else { $formErrors['numeroEngin'] = 'Vous n\'avez pas sélectionné le '; } if (!empty($_POST['description'])) { // if (preg_match($regexName, $_POST['description'])) { $anomalies->description = $_POST['description']; // } else { // $formErrors['description'] = 'Le text est pas valide'; // } } else { $formErrors['description'] = 'L\'information n\'est pas renseigné'; } /* IMAGE */ if (!empty($_FILES['imageAnom1']) && $_FILES['imageAnom1']['error'] == 0) { // On stock dans $fileInfos les informations concernant le chemin du fichier. $fileInfos = pathinfo($_FILES['imageAnom1']['name']); // On crée un tableau contenant les extensions autorisées. $fileExtension = ['jpg', 'jpeg', 'png','JPG','JPEG', 'PNG']; // On verifie si l'extension de notre fichier est dans le tableau des extension autorisées. if (in_array($fileInfos['extension'], $fileExtension)) { //On définit le chemin vers lequel uploader le fichier $path = './Assets/Img/'; //On crée une date pour différencier les fichiers $date = date('Y-m-d_H-i-s'); //On crée le nouveau nom du fichier (celui qu'il aura une fois uploadé) $fileNewName = $_FILES['imageAnom1']['name']; //On stocke dans une variable le chemin complet du fichier (chemin + nouveau nom + extension une fois uploadé) Attention : ne pas oublier le point $EnginPhoto = $path . $fileNewName ; //move_uploaded_files : déplace le fichier depuis son emplacement temporaire ($_FILES['file']['tmp_name']) vers son emplacement définitif ($fileFullPath) if (move_uploaded_file($_FILES['imageAnom1']['tmp_name'], $EnginPhoto)) { //On définit les droits du fichiers uploadé (Ici : écriture et lecture pour l'utilisateur apache, lecture uniquement pour le groupe et tout le monde) chmod($EnginPhoto, 0644); $anomalies->imageAnom1 = $EnginPhoto; }else { $formErrors['imageAnom1'] = 'Votre fichier ne s\'est pas téléversé correctement'; } }else { $formErrors['imageAnom1'] = 'Votre fichier n\'est pas du format attendu'; } }else { $formErrors['imageAnom1'] = 'Veuillez selectionner un fichier'; } if (empty($formErrors)) { //on appelle la methode de notre model pour creer un nouveau product dans la base de données if (!$anomalies->checkAnomaliesExist()){ if($anomalies->addAnomalies()){ $addAnomaliesMessage = '<div class="alert alert-success" role="alert"><i class="far fa-check-circle"></i> L\'anomalie a bien été ajouté</div>'; } else { $addAnomaliesMessage = 'Une erreur est survenue.'; } } else { $addAnomaliesMessage = 'l\'anomalie a déjà été ajouté.'; } } }
b915405af1e66f22fd552682f02e40e0328055f6
[ "JavaScript", "PHP" ]
43
PHP
jeromedeporres/digitEngin
fdfff9aba876748e9ae2b34f3280ae364398deed
09ad8c98e1191e26cfb63855d098d580934dcac6
refs/heads/master
<repo_name>hetu-k-patel/Instagram-Clone<file_sep>/README.md # Instagram-Clone Instagram-Clone using MERN stack. <file_sep>/Instagram-backend/server.js import express, { json } from 'express'; import mongoose from 'mongoose'; import cors from 'cors'; import Pusher from 'pusher'; // AppConfig const app = express(); const port = process.env.PORT || 9000; const connection_url = ''; // Middlewares app.use(express.json()); app.use(cors()); // DBConfig mongoose.connect(connection_url, { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true, }); mongoose.connection.once('open', () => { console.log('DB Connected'); }) // API Endpoints app.get('/', (req, res) => { res.status(200).send('Hello World'); }); app.post() // Listner app.listen(port, () => console.log(`listening on localhost: ${port}`));
859d131afbbe0918a96fe402676308ab254f42c9
[ "Markdown", "JavaScript" ]
2
Markdown
hetu-k-patel/Instagram-Clone
f417d05ced7c2a36b1c53d4d54688d9fb4396213
06bcdcbe15eb14131f6a742fc6d7073076304de7
refs/heads/master
<repo_name>DivyaLalithamony/ux-chi<file_sep>/src/website/assets/scripts/globalConfigs.js window.chiCurrentVersion="3.5.0";
a51df576eda8005c6a51936ca3b65593d5ac26b0
[ "JavaScript" ]
1
JavaScript
DivyaLalithamony/ux-chi
5ccdcdcc363b16107d7b422cb84651fdf82eb92c
5310d02f00cd9169ca0a44f8669ddc61d6586caa
refs/heads/master
<repo_name>Defee/ionic4_deeplinks<file_sep>/src/app/app.component.ts import { Component } from '@angular/core'; import { Platform } from '@ionic/angular'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { StatusBar } from '@ionic-native/status-bar/ngx'; import { Deeplinks } from '@ionic-native/deeplinks/ngx'; import { Tab1Page } from './tab1/tab1.page'; import { Tab2Page } from './tab2/tab2.page'; import { Router } from '@angular/router'; @Component({ selector: 'app-root', templateUrl: 'app.component.html' }) export class AppComponent { constructor( private platform: Platform, private splashScreen: SplashScreen, private statusBar: StatusBar, protected deepLinks: Deeplinks, protected router: Router ) { this.initializeApp(); } async initializeApp() { await this.platform.ready().then(() => { this.statusBar.styleDefault(); this.splashScreen.hide(); this.deepLinks .route({ '/about-us': { someKindofData: [ { id: 1, name: 'asdads' }, { id: 2, name: 'asdads' } ] } }) .subscribe( (match) => { console.log('Successfully matched route', match); console.log('args', match.$args); console.log('link', match.$link); if (match.$link.url.includes('about-us')) { this.router.navigate([ 'tabs/tab2' ]); } // match.$route - the route we matched, which is the matched entry from the arguments to route() // match.$args - the args passed in the link // match.$link - the full link data }, (nomatch) => { // nomatch.$link - the full link data // tslint:disable-next-line:quotemark console.error("Got a deeplink that didn't match", nomatch); console.error('Link data', nomatch.$link); } ); }); } }
29a3695db828e830733bb5a2714a21806439bf40
[ "TypeScript" ]
1
TypeScript
Defee/ionic4_deeplinks
28580d98e5ef77a063ace62c57a1d131cb054604
1460c0b6fc73bec82ece6bb0a4340bf6b1aadb28
refs/heads/master
<repo_name>aspineon/spark-streaming-cassandra<file_sep>/README.md # Spark Streaming Cassandra example This is a quick example to show how to get twitter streaming data using Apache Spark Streaming and store different forms of twitter status data as time series data in Cassandra. ## Running Twitter4j needs a number of API keys that can be created [here](https://dev.twitter.com/apps). You need to specify these keys on the command line when starting the example application: -Dtwitter4j.debug=true -Dtwitter4j.oauth.consumerKey=... -Dtwitter4j.oauth.consumerSecret=... -Dtwitter4j.oauth.accessToken=... -Dtwitter4j.oauth.accessTokenSecret=... <file_sep>/lib-tweet/src/test/java/com/nibado/example/sparkstream/tweet/TweetKryoSerializerTest.java package com.nibado.example.sparkstream.tweet; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import static com.nibado.example.sparkstream.tweet.TestHelper.testSet; import static org.assertj.core.api.Assertions.assertThat; public class TweetKryoSerializerTest { private TweetKryoSerializer serializer; @Before public void setup() { serializer = new TweetKryoSerializer(); } @Test public void testSerialize() throws Exception { for(Tweet t : testSet()) { Tweet out = serializer.deserialize("", serializer.serialize("", t)); System.out.println(t); assertThat(t).isNotSameAs(out); assertThat(out).isEqualTo(out); assertThat(out).isEqualToComparingFieldByField(out); } } }<file_sep>/twitterproducer/src/main/java/com/nibado/example/sparkstream/producer/TwitterToKafka.java package com.nibado.example.sparkstream.producer; import com.nibado.example.sparkstream.tweet.Tweet; import com.nibado.example.sparkstream.tweet.TweetKryoSerializer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import twitter4j.HashtagEntity; import twitter4j.StallWarning; import twitter4j.Status; import twitter4j.StatusDeletionNotice; import twitter4j.StatusListener; import twitter4j.UserMentionEntity; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; public class TwitterToKafka implements StatusListener { private static final Logger LOG = LoggerFactory.getLogger(TwitterToKafka.class); private Properties properties; private String topic; private Producer<String, Tweet> producer; public TwitterToKafka(Properties properties, String topic) { this.properties = properties; this.topic = topic; } public void start() { properties.put("acks", "all"); properties.put("retries", 0); properties.put("batch.size", 16384); properties.put("linger.ms", 1); properties.put("buffer.memory", 33554432); properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); properties.put("value.serializer", TweetKryoSerializer.class.getName()); producer = new KafkaProducer<>(properties); } public void stop() { producer.close(); } @Override public void onStatus(Status status) { Tweet tweet = new Tweet(status.getUser().getScreenName(), status.getText(), status.getCreatedAt(), hashTags(status.getHashtagEntities())); producer.send(new ProducerRecord<>(topic, null, tweet)); LOG.debug("Tweet: {}", tweet); } private static List<String> hashTags(HashtagEntity[] hashTags) { return Arrays.asList(hashTags).stream().map(HashtagEntity::getText).collect(Collectors.toList()); } private static List<String> userMentions(UserMentionEntity[] mentions) { return Arrays.asList(mentions).stream().map(UserMentionEntity::getName).collect(Collectors.toList()); } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } @Override public void onTrackLimitationNotice(int i) { } @Override public void onScrubGeo(long l, long l1) { } @Override public void onStallWarning(StallWarning stallWarning) { } @Override public void onException(Exception e) { } }
82536d365b74474bc6ede6872491d00455b19098
[ "Markdown", "Java" ]
3
Markdown
aspineon/spark-streaming-cassandra
1eab6f9c5ea48151d138c3467b09e1fee11e754a
a330398c3125bc346f1f65fd1ff535a39f847a3c
refs/heads/master
<repo_name>alefkaditis/angular-mini-project<file_sep>/src/app/routing/currencies/currencies.component.ts import { Component, OnInit } from '@angular/core'; import { Country } from 'src/app/shared/models'; import { ServicesService } from 'src/app/shared/services.service'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-currencies', templateUrl: './currencies.component.html', styleUrls: ['./currencies.component.scss'] }) export class CurrenciesComponent implements OnInit { public countries: Array<Country>; public countriesName: Array<Country>; constructor(private service: ServicesService, private route: ActivatedRoute) { } ngOnInit() { this.service.getEuropeRegion().subscribe((data: Array<Country>) => { console.log(data); this.countries = data; }); } fetchCountriesName(currency: string) { this.service.getCountriesName(currency).subscribe((data: Array<Country>) => { console.log(data); this.countriesName = data; }); } getCountriesName() { return this.countriesName; } } <file_sep>/src/app/routing/routing.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; import { EuropeRegionComponent } from './europe-region/europe-region.component'; import { EuropeRegionDetailsComponent } from './europe-region-details/europe-region-details.component'; import { CurrenciesComponent } from './currencies/currencies.component'; import { CurrenciesChildComponent } from './currencies-child/currencies-child.component'; @NgModule({ declarations: [EuropeRegionComponent, EuropeRegionDetailsComponent, CurrenciesComponent, CurrenciesChildComponent], imports: [ CommonModule, RouterModule ], exports: [ EuropeRegionComponent, EuropeRegionDetailsComponent, CurrenciesComponent, CurrenciesChildComponent ] }) export class RoutingModule { } <file_sep>/src/app/routing/currencies/currencies.component.html <div class="row"> <div class="col-sm-6"> <ul *ngFor="let country of countries"> <li> {{country.name}} - {{country.capital}} <ul *ngFor="let currency of country.currencies"> <li> <a (click)=fetchCountriesName(currency.code) style="color: #007bff;text-decoration: none;background-color: transparent;cursor: pointer"> {{currency.code}} </a> </li> </ul> </li> </ul> </div> <div class="col-sm-6"> <app-currencies-child [countriesName]=getCountriesName()></app-currencies-child> </div> </div> <file_sep>/src/app/routing/europe-region-details/europe-region-details.component.ts import { Component, OnInit } from '@angular/core'; import { ServicesService } from 'src/app/shared/services.service'; import { ActivatedRoute } from '@angular/router'; import { CountryDetails } from 'src/app/shared/models'; @Component({ selector: 'app-europe-region-details', templateUrl: './europe-region-details.component.html', styleUrls: ['./europe-region-details.component.scss'] }) export class EuropeRegionDetailsComponent implements OnInit { private routeParams: string; public countryDetails: Array<CountryDetails>; constructor(private service: ServicesService, private route: ActivatedRoute) {} ngOnInit() { this.route.params.subscribe(p => { console.log(p); this.routeParams = p.capital; this.service.getEuropeRegionDetails(this.routeParams).subscribe((data: Array<CountryDetails>) => { console.log(data); this.countryDetails = data; }); }); } } <file_sep>/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { RoutingModule } from './routing/routing.module'; import { EuropeRegionComponent } from './routing/europe-region/europe-region.component'; import { EuropeRegionDetailsComponent } from './routing/europe-region-details/europe-region-details.component'; import { CurrenciesComponent } from './routing/currencies/currencies.component'; import { CurrenciesChildComponent } from './routing/currencies-child/currencies-child.component'; const routes: Routes = [ { path: 'europe-region', component: EuropeRegionComponent, children: [{ path: 'europe-region-details/:capital', component: EuropeRegionDetailsComponent }] }, { path: 'currencies', component: CurrenciesComponent, children: [{ path: 'currencies/:currency', component: CurrenciesChildComponent }] } ]; @NgModule({ imports: [ RouterModule.forRoot(routes), RoutingModule ], exports: [ RouterModule, RoutingModule ] }) export class AppRoutingModule { } <file_sep>/src/app/shared/services.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { environment } from 'src/environments/environment'; import { Observable } from 'rxjs'; import { Country, CountryDetails, Currency } from './models'; @Injectable({ providedIn: 'root' }) export class ServicesService { private readonly endpoint = environment.baseURL; constructor(private http: HttpClient) {} getEuropeRegion(): Observable<Country[]> { // console.log(this.httpParams); // const params = this.httpParams; return this.http.get<Country[]>(this.endpoint); } getEuropeRegionDetails(capital: string): Observable<CountryDetails[]> { return this.http.get<CountryDetails[]>(this.endpoint + '/capital/' + capital); } getCountriesName(currency: string): Observable<Country[]> { return this.http.get<Country[]>(this.endpoint + '/currency/' + currency + '/?fields=name'); } } <file_sep>/src/app/shared/models.ts export interface Country { name: string; capital: string; currencies: Currency; } export interface CountryDetails { capital: string; population: number; nativeName: string; subregion: string; } export interface Currency { code: string; name: string; symbol: string; } <file_sep>/src/app/routing/currencies-child/currencies-child.component.ts import { Component, OnInit, Input } from '@angular/core'; import { Country } from 'src/app/shared/models'; @Component({ selector: 'app-currencies-child', templateUrl: './currencies-child.component.html', styleUrls: ['./currencies-child.component.scss'] }) export class CurrenciesChildComponent implements OnInit { @Input() countriesName: Array<Country>; constructor() { } ngOnInit() { } } <file_sep>/src/app/routing/europe-region/europe-region.component.ts import { Component, OnInit } from '@angular/core'; import { ServicesService } from 'src/app/shared/services.service'; import { Country } from 'src/app/shared/models'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-europe-region', templateUrl: './europe-region.component.html', styleUrls: ['./europe-region.component.scss'] }) export class EuropeRegionComponent implements OnInit { public countries: Array<Country>; constructor(private service: ServicesService, private route: ActivatedRoute) { // this.route.queryParams.subscribe(p => console.log(p)); } ngOnInit() { this.service.getEuropeRegion().subscribe((data: Array<Country>) => { this.countries = data; }); } } <file_sep>/src/app/routing/europe-region-details/europe-region-details.component.html <p *ngFor="let country of countryDetails"> {{country.capital}} - {{country.population}} - {{country.nativeName}} - {{country.subregion}} </p>
c2606ea1713e47b4aae0493025a4805056017ee3
[ "TypeScript", "HTML" ]
10
TypeScript
alefkaditis/angular-mini-project
4500db5ac48a53fa01369339b8a19a61bff61902
9ef93b922dd7f5c641faf15c18111676abb757c6
refs/heads/main
<file_sep>aiohttp==3.7.4.post0 altgraph==0.17 appdirs==1.4.4 async-timeout==3.0.1 attrs==21.2.0 auto-py-to-exe==2.9.0 beautifulsoup4==4.9.3 bottle==0.12.19 bottle-websocket==0.2.9 certifi==2020.12.5 cffi==1.14.5 chardet==3.0.4 click==8.0.0 colorama==0.4.4 discord-webhook==0.14.0 Discord-Webhooks==1.0.4 discord.py==1.7.2 distlib==0.3.1 docopt==0.6.2 Eel==0.12.4 filelock==3.0.12 Flask==2.0.0 Flask-SQLAlchemy==2.5.1 future==0.18.2 gevent==21.1.2 gevent-websocket==0.10.1 greenlet==1.1.0 idna==2.8 itsdangerous==2.0.1 Jinja2==3.0.1 Js2Py==0.71 MarkupSafe==2.0.1 MouseInfo==0.1.3 multidict==5.1.0 numpy==1.20.3 opencv-contrib-python==4.5.2.52 opencv-python==4.5.2.52 packaging==20.9 pandas==1.2.4 pefile==2021.5.13 Pillow==8.2.0 pipwin==0.5.1 plyer==2.0.0 PyAutoGUI==0.9.52 pycparser==2.20 PyGetWindow==0.0.9 pyinstaller @ https://github.com/pyinstaller/pyinstaller/archive/develop.tar.gz pyinstaller-hooks-contrib==2021.1 pyjsparser==2.7.1 PyMsgBox==1.0.9 PyNaCl==1.4.0 pynput==1.7.3 pyparsing==2.4.7 pyperclip==1.8.2 PyPrind==2.11.3 PyRect==0.1.4 PyScreeze==0.1.27 pySmartDL==1.3.4 python-dateutil==2.8.1 python2==1.2 PyTweening==1.0.3 pytz==2020.4 pywin32-ctypes==0.2.0 requests==2.21.0 schedule==0.6.0 selenium==3.141.0 six==1.16.0 soupsieve==2.2.1 SQLAlchemy==1.4.15 typing-extensions==3.10.0.0 tzlocal==2.1 urllib3==1.24.3 virtualenv==20.4.6 Werkzeug==2.0.1 whichcraft==0.6.1 wikipedia==1.4.0 yarl==1.6.3 zope.event==4.5.0 zope.interface==5.2.0 <file_sep>from discord_webhook import DiscordWebhook, DiscordEmbed # Put your webhook url . webhook_url = "" def send_message(class_name, status, joined_time, end_time): webhook = DiscordWebhook(webhook_url) # Checking for status Joined . if status == "Joined": # Making an Embed Object . embed_joined = DiscordEmbed(title='Class Joined Successfully', description="Here's your report with :heart:") # Adding fields to the objects ! embed_joined.add_embed_field(name='Class', value=class_name) embed_joined.add_embed_field(name='Status', value=status) embed_joined.add_embed_field(name='Joined At', value=joined_time) embed_joined.add_embed_field(name='Leaving At', value=end_time) webhook.add_embed(embed_joined) # Sending the message . webhook.execute() # Checking for status Left . elif status == "Left": embed_left = DiscordEmbed(title='Class Left Successfully', description="Here's your report with :heart:") embed_left.add_embed_field(name='Class', value=class_name) embed_left.add_embed_field(name='Status', value=status) embed_left.add_embed_field(name='Left At', value=end_time) webhook.add_embed(embed_left) webhook.execute() <file_sep>import datetime firstClass = "" secondClass = "" thirdClass = "" fourthClass = "" fifthClass = "" sixthclass = "" tmp = "%H:%M" # Class running time.. you might have to modify this ! runn_time = (datetime.datetime.strptime(secondClass, tmp) - datetime.datetime.strptime(firstClass, tmp)).seconds # Put your meeting id, password, name respectively # You might have more or less subjects . english = ["meeting_id", "meeting_passwd", "meeting_name"] biology = ["", "", ""] physics = ["", "", ""] maths = ["", "", ""] hindi = ["", "", ""] computer = ["", "", ""] history = ["", "", ""] geography = ["", "", ""] economics = ["", "", ""] <file_sep># Importing the necessary packages . import datetime from selenium import webdriver from selenium.webdriver.chrome.options import Options import time from info import * import keyboard import schedule import discord_webhook CURRENT_DAY = datetime.datetime.now().strftime("%a") # Adding options . opt = Options() opt.add_argument("--disable-infobars") opt.add_argument("start-maximized") opt.add_argument("--disable-extensions") opt.add_argument("--start-maximized") # Pass the argument 1 to allow and 2 to block opt.add_experimental_option("prefs", { "profile.default_content_setting_values.media_stream_mic": 1, "profile.default_content_setting_values.media_stream_camera": 1, "profile.default_content_setting_values.geolocation": 1, "profile.default_content_setting_values.notifications": 1 }) # Creating a Driver object . # Download the driver according to your version from here https://chromedriver.chromium.org/downloads . driver = webdriver.Chrome("YOUR DRIVER PATH", options=opt) # Login Function def login_to_zoom(email, password): global driver driver.get("https://zoom.us/signin") # Zoom's Login page . time.sleep(3) driver.find_element_by_link_text("Google").click() # Login from google option time.sleep(2) email_field = driver.find_element_by_xpath( "/html/body/div[1]/div[1]/div[2]/div/div[2]/div/div/div[2]/div/div[1]/div/form/span/section/div/div/div[" "1]/div/div[1]/div/div[1]/input " ) email_field.click() email_field.send_keys(email) # Sending email key strokes ! time.sleep(.5) driver.find_element_by_xpath( "/html/body/div[1]/div[1]/div[2]/div/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div/div/button/span").click() time.sleep(2) pass_field = driver.find_element_by_xpath( "/html/body/div[1]/div[1]/div[2]/div/div[2]/div/div/div[2]/div/div[1]/div/form/span/section/div/div/div[" "1]/div[1]/div/div/div/div/div[1]/div/div[1]/input") pass_field.click() pass_field.send_keys(password) # Sending Password ! time.sleep(.5) driver.find_element_by_xpath( "/html/body/div[1]/div[1]/div[2]/div/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div/div/button/span").click() time.sleep(4) login_to_zoom("YOUR EMAIL", "YOUR PASSWORD") # Provide your gmail and password here . # Main Join Function . def join_with_id_pass(class_name, id, password): driver.get("https://us05web.zoom.us/join") time.sleep(4) id_field = driver.find_element_by_id("join-confno") id_field.click() id_field.send_keys(id) # Sending class id . time.sleep(.5) driver.find_element_by_link_text("Join").click() time.sleep(4) # 1st popup keyboard.send("enter", do_press=True, do_release=True) time.sleep(1) # Launch meeting btn driver.find_element_by_xpath("/html/body/div[3]/div[2]/div/div[1]/div").click() time.sleep(1) # 2nd popup keyboard.send("enter", do_press=True, do_release=True) time.sleep(1) # Joining from browser driver.find_element_by_link_text("Join from Your Browser").click() time.sleep(4) # Turning of Mic and Video driver.find_element_by_xpath( "/html/body/div[1]/div[3]/div[3]/div[3]/div[2]/div/div[3]/div[1]/button[1]/div").click() time.sleep(.5) driver.find_element_by_xpath("/html/body/div[1]/div[3]/div[3]/div[3]/div[2]/div/div[3]/div[2]/button/div").click() # Join btn driver.find_element_by_id("joinBtn").click() time.sleep(4) passwd_field = driver.find_element_by_xpath("/html/body/div[1]/div[3]/div[3]/div[3]/form/div/div[2]/div[1]/input") passwd_field.click() passwd_field.send_keys(password) # Sending class password . time.sleep(1) # Join btn driver.find_element_by_id("joinBtn").click() join_time = datetime.datetime.now() # Sending the Message to us via Discord-Webhook discord_webhook.send_message(class_name=class_name, status="Joined", joined_time=join_time.strftime("%H:%M"), end_time=((join_time + datetime.timedelta(minutes=40)).strftime("%H:%M"))) # Sleeping the program for the class running time. time.sleep(2400) left_time = datetime.datetime.now().strftime("%H:%M") driver.quit() # Sending the Left Message to us via Discord-Webhook discord_webhook.send_message(class_name=class_name, status="Left", joined_time=join_time, end_time=left_time) # Scheduler here , Modify it according to your timetable . # You may have less or more classes just modify the scheduler . # Pass the name, ID, Password for the meeting in the same order . # At 0 index we have our meeting ID, 1 index we have password, and the 2'nd index is the name of the class. # Note there is no timetable for Tuesday and Saturday , But you can add them also . def schedule_monday_class(): schedule.every().monday.at(firstClass).do(join_with_id_pass, maths[2], maths[0], maths[1]) schedule.every().monday.at(secondClass).do(join_with_id_pass, english[2], english[0], english[1]) # schedule.every().monday.at(thirdClass).do(join_with_id_pass) schedule.every().monday.at(fourthClass).do(join_with_id_pass, geography[2], geography[0], geography[1]) schedule.every().monday.at(fifthClass).do(join_with_id_pass, hindi[2], hindi[0], hindi[1]) schedule.every().monday.at(sixthclass).do(join_with_id_pass, economics[2], economics[0], economics[1]) while True: schedule.run_pending() time.sleep(1) def schedule_wednesday_class(): schedule.every().wednesday.at(firstClass).do(join_with_id_pass, maths[2], maths[0], maths[1]) schedule.every().wednesday.at(secondClass).do(join_with_id_pass, english[2], english[0], english[1]) schedule.every().monday.at(thirdClass).do(join_with_id_pass, biology[2], biology[0], biology[1]) schedule.every().wednesday.at(fourthClass).do(join_with_id_pass, history[2], history[0], history[1]) # schedule.every().wednesday.at(fifthClass).do(join_with_id_pass, hii[0], hin[1]) schedule.every().wednesday.at(sixthclass).do(join_with_id_pass, hindi[2], hindi[0], hindi[1]) # Here we are Constantly checking for any pending loops ! while True: schedule.run_pending() time.sleep(1) def schedule_thursday_class(): schedule.every().thursday.at(firstClass).do(join_with_id_pass, maths[2], maths[0], maths[1]) schedule.every().thursday.at(secondClass).do(join_with_id_pass, english[2], english[0], english[1]) # schedule.every().monday.at(thirdClass).do(join_with_id_pass, ) schedule.every().thursday.at(fourthClass).do(join_with_id_pass, history[2], history[0], history[1]) schedule.every().thursday.at(fifthClass).do(join_with_id_pass, biology[2], biology[0], biology[1]) schedule.every().thursday.at(sixthclass).do(join_with_id_pass, hindi[2], hindi[0], hindi[1]) while True: schedule.run_pending() time.sleep(1) def schedule_friday_class(): schedule.every().friday.at(firstClass).do(join_with_id_pass, computer[2], computer[0], computer[1]) schedule.every().friday.at(secondClass).do(join_with_id_pass, physics[2], physics[0], physics[1]) schedule.every().monday.at(thirdClass).do(join_with_id_pass, english[2], english[0], english[1]) schedule.every().thursday.at(fourthClass).do(join_with_id_pass, history[2], history[0], history[1]) schedule.every().thursday.at(firstClass).do(join_with_id_pass, maths[2], maths[0], maths[1]) schedule.every().thursday.at(fifthClass).do(join_with_id_pass, biology[2], biology[0], biology[1]) while True: schedule.run_pending() time.sleep(1) # According to the day We are setting the scheduler ! if CURRENT_DAY == "Mon": schedule_monday_class() elif CURRENT_DAY == "Tue": schedule_monday_class() elif CURRENT_DAY == "Wed": schedule_wednesday_class() elif CURRENT_DAY == "Thu": schedule_thursday_class() elif CURRENT_DAY == "Fri": schedule_friday_class() elif CURRENT_DAY == "Sat": schedule_friday_class() else: print("Sunday ..... ") <file_sep># Automatic Zoom Class Attender This bot will attend all your zoom online classes according to your timetable. ## Installation Clone the repository git clone **https://github.com/anonymous1232424/online_zoom_class_taker** Install the requirements **Pip install requirements.txt** ## Usage **Just change the Time table and according to your Time Table and then run the script.**
4ad6ddc0abf056ca4b4f6871514a142707bb9e66
[ "Markdown", "Python", "Text" ]
5
Text
anonymous1232424/online_zoom_class_taker
fe97f4b6cc51f5db84345fba8903d449ee055b71
c6f8a173c37a5ed1855622be6042c0ab0953d581
refs/heads/master
<file_sep><div class="page-head-wrap"> <h4 class="margin0"> Form Barang </h4> <div class="breadcrumb-right"> <ol class="breadcrumb"> <li><a href="#">Form</a></li> <li class="active">Form Barang</li> </ol> </div> </div> <!--page header end--> <div class="ui-content-body"> <div class="panel"> <div class="panel-body "> <div class="row"> <div class="col-md-8 col-md-offset-2"> <form class="form-horizontal" role="form" action="<?php echo base_url() . 'Barang/input'; ?>" method="post"> <div class="form-group"> <label class="col-lg-3 col-sm-3 control-label">Kode Barang</label> <div class="col-lg-9"> <input class="form-control" name="KodeBarang" placeholder="Kode Barang" type="text"> </div> </div> <div class="form-group"> <label class="col-lg-3 col-sm-3 control-label">Nama Barang</label> <div class="col-lg-9"> <input class="form-control" name="NamaBarang" placeholder="Nama Barang" type="text"> </div> </div> <!-- <div class="form-group"> <label class="col-lg-3 col-sm-3 control-label">Jumlah Barang</label> <div class="col-lg-9"> <input class="form-control" name="JumlahBarang" placeholder="Jumlah Barang" type="text"> </div> </div>--> <div class="form-group"> <label class="col-lg-3 col-sm-3 control-label">Jenis Barang</label> <div class="col-lg-9"> <select class="form-control" name="id_kategori"> <?php foreach ($kategori as $u) { ?> <option value="<?= $u->id_kategori; ?>"> <?= $u->nama_kategori; ?></option> <?php } ?> </select> </div> </div> <br><br> <!-- <div class="form-group"> <label class="col-lg-3 col-sm-3 control-label">Harga Barang</label> <div class="col-lg-9"> <input class="form-control" name="HargaBarang" placeholder="Harga Barang" type="text"> </div> </div>--> <div class="form-group"> <div class="col-lg-offset-3 col-lg-9"> <a href="<?php echo site_url() . 'Barang'; ?>" type="button" class="btn btn-warning">Cancel</a> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> </div> </div> </div> </div> </div> <file_sep><div class="page-head-wrap"> <h4 class="margin0"> Detail Eclat </h4> <div class="breadcrumb-right"> <ol class="breadcrumb"> <li><a href="#">Detail Eclat</a></li> <li class="active">Hasil</li> </ol> </div> </div> <div class="ui-content-body"> <div class="ui-container"> <div class="row"> <div class="col-sm-12"> <section class="panel"> <header class="panel-heading panel-border"> Tabel Hasil <span class="tools pull-right"> <a class="refresh-box fa fa-repeat" href="javascript:;"></a> <a class="collapse-box fa fa-chevron-down" href="javascript:;"></a> <a class="close-box fa fa-times" href="javascript:;"></a> </span> </header> <div class="panel-body table-responsive"> <table class="table colvis-data-table table-striped"> <thead> <tr> <th> No </th> <th> Kategori </th> <th> Support </th> <th> Confidence </th> <th> Total </th> </tr> </thead> <tbody> <?php $no = 1; $eclat_value = array(); $eclat_data = array(); foreach ($eclat['support'] as $key => $value) { foreach ($value as $key2 => $value2) { if($eclat['support'] >= $support && $eclat['confidence'][$key2][$key] >= $confidence){ ?> <tr> <td><?php echo $no++ ?></td> <td><?php echo $eclat['kategori'][$key]['name'] . ' ->' . $eclat['kategori'][$key2]['name'] ?></td> <td><?php echo $value2 ?> </td> <td><?php echo $eclat['confidence'][$key2][$key] ?> </td> <td><?php echo $eclat['confidence'][$key2][$key] + $value2 ?> </td> </tr> <?php } array_push($eclat_data, array($key, $key2)); array_push($eclat_value, ($eclat['confidence'][$key2][$key] + $value2)); } } // print_r($eclat[support]); ?> </tbody> </table> </div> </section> </div> </div> </div> </div><file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- <link rel="shortcut icon" type="image/png" href="/imgs/favicon.png" /> --> <title>Home</title> <!-- inject:css --> <link rel="stylesheet" href="<?= base_url('includes') ?>/bower_components/bootstrap/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="<?= base_url('includes') ?>/bower_components/font-awesome/css/font-awesome.min.css"> <link rel="stylesheet" href="<?= base_url('includes') ?>/bower_components/simple-line-icons/css/simple-line-icons.css"> <link rel="stylesheet" href="<?= base_url('includes') ?>/bower_components/weather-icons/css/weather-icons.min.css"> <link rel="stylesheet" href="<?= base_url('includes') ?>/bower_components/themify-icons/css/themify-icons.css"> <!-- endinject --> <!--highcharts--> <script src="<?= base_url('includes') ?>/bower_components/highcharts/highcharts.js"></script> <script src="<?= base_url('includes') ?>/bower_components/highcharts/highcharts-more.js"></script> <script src="<?= base_url('includes') ?>/bower_components/highcharts/modules/exporting.js"></script> <script src="<?= base_url('includes') ?>/assets/js/init-highcharts-inner.js"></script> <!-- Main Style --> <link rel="stylesheet" href="<?= base_url('includes') ?>/dist/css/main.css"> <!--C3 Charts Depencencies --> <link rel="stylesheet" href="<?= base_url('includes') ?>/bower_components/c3/c3.min.css"> <link rel="stylesheet" href="<?= base_url('includes') ?>/dist/css/main.css"> <script src="<?= base_url('includes') ?>/assets/js/modernizr-custom.js"></script> <!-- Rickshaw Chart Depencencies --> <link rel="stylesheet" href="<?= base_url('includes') ?>/bower_components/rickshaw/rickshaw.min.css"> <!--easypiechart--> <link rel="stylesheet" href="<?= base_url('includes') ?>/assets/js/jquery-easy-pie-chart/easypiechart.css"> <!--horizontal-timeline--> <link rel="stylesheet" href="<?= base_url('includes') ?>/assets/js/horizontal-timeline/css/style.css"> <script src="<?= base_url('includes') ?>/assets/js/modernizr-custom.js"></script> <!--Data Table--> <link href="<?= base_url('includes') ?>/bower_components/datatables/media/css/jquery.dataTables.css" rel="stylesheet"> <link href="<?= base_url('includes') ?>/bower_components/datatables-tabletools/css/dataTables.tableTools.css" rel="stylesheet"> <link href="<?= base_url('includes') ?>/bower_components/datatables-colvis/css/dataTables.colVis.css" rel="stylesheet"> <link href="<?= base_url('includes') ?>/bower_components/datatables-responsive/css/responsive.dataTables.scss" rel="stylesheet"> <link href="<?= base_url('includes') ?>/bower_components/datatables-scroller/css/scroller.dataTables.scss" rel="stylesheet"> <script src="<?= base_url('includes') ?>/assets/js/modernizr-custom.js"></script> <!--jQuery Nestable Dependencies --> <link rel="stylesheet" href="<?= base_url('includes') ?>/assets/css/jquery.nestable.css"> <!--Fuelux Tree Depencencies --> <link rel="stylesheet" type="text/css" href="<?= base_url('includes') ?>/assets/js/fuelux/css/tree-style.css" /> <!--grafik--> <!-- Load plotly.js into the DOM --> <!--<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>--> <script src='<?= base_url('includes') ?>/assets/plot.js'> </script> </head> <body> <div id="ui" class="ui"> <!--header start--> <header id="header" class="ui-header"> <div class="navbar-header"> <!--logo start--> <a href="<?php echo site_url() . 'Dashboard'; ?>" class="navbar-brand"> <span class="logo"><img src="<?= base_url('includes') ?>/imgs/logo-dark.png" alt=""/></span> <span class="logo-compact"><img src="<?= base_url('includes') ?>/imgs/logo-icon-dark.png" alt=""/></span> </a> <!--logo end--> </div> <!-- <div class="search-dropdown dropdown pull-right visible-xs"> <button type="button" class="btn dropdown-toggle" data-toggle="dropdown" aria-expanded="true"><i class="fa fa-search"></i></button> <div class="dropdown-menu"> <form > <input class="form-control" placeholder="Search here..." type="text"> </form> </div> </div>--> <div class="navbar-collapse nav-responsive-disabled"> <!--toggle buttons start--> <ul class="nav navbar-nav"> <li> <a class="toggle-btn" data-toggle="ui-nav" href=""> <i class="fa fa-bars"></i> </a> </li> </ul> <!-- toggle buttons end --> <!--notification start--> <ul class="nav navbar-nav navbar-right"> <li class="dropdown dropdown-usermenu"> <a href="#" class=" dropdown-toggle" data-toggle="dropdown" aria-expanded="true"> <div class="user-avatar"><img src="<?= base_url('includes') ?>/imgs/a0.jpg" alt="..."></div> <span class="hidden-sm hidden-xs"><?php echo $this->session->userdata("jabatan") ?></span> <!--<i class="fa fa-angle-down"></i>--> <span class="caret hidden-sm hidden-xs"></span> </a> <ul class="dropdown-menu dropdown-menu-usermenu pull-right"> <li><a href="<?= site_url('Template/logout') ?>"><i class="fa fa-sign-out"></i> Log Out</a></li> </ul> </li> </ul> <!--notification end--> </div> </header> <!--header end--> <!--sidebar start--> <aside id="aside" class="ui-aside"> <ul class="nav" ui-nav> <li class="active"> <a href="<?= site_url('dashboard') ?>"><i class="fa fa-home"></i><span>Dashboard</span></a> </li> <li> <a href=""><i class="fa fa-table"></i><span>Data Latih</span><i class="fa fa-angle-right pull-right"></i></a> <ul class="nav nav-sub"> <li class="nav-sub-header"><a href=""><span>Data Latih</span></a></li> <li><a href="<?= site_url('kategori') ?>"><span>Data Kategori </span></a></li> <!-- <li><a href="<?= site_url('rak') ?>"><span>Data Rak</span></a></li>--> <li><a href="<?= site_url('barang') ?>"><span>Data Barang</span></a></li> <li><a href="<?= site_url('transaksi') ?>"><span>Data Transaksi</span></a></li> <li><a href="<?= site_url('akun') ?>"><span>Data Akun</span></a></li> </ul> </li> <!-- <li> <a href=""><i class="fa fa-list-alt"></i><span>Form</span><i class="fa fa-angle-right pull-right"></i></a> <ul class="nav nav-sub"> <li class="nav-sub-header"><a href=""><span>Form</span></a></li> <li><a href="<?= site_url('kategori/form') ?>"><span>Form Kategori </span></a></li> <li><a href="<?= site_url('rak/form') ?>"><span>Form Rak</span></a></li> <li><a href="<?= site_url('barang/form') ?>"><span>Form Barang</span></a></li> <li><a href="<?= site_url('transaksi/form') ?>"><span>Form Transaksi</span></a></li> <li><a href="<?= site_url('akun/form') ?>"><span>Form Akun</span></a></li> </ul> </li>--> <li> <a href="<?= site_url('tatlek') ?>"><i class="fa fa-bullseye"></i><span>Tata Letak</span></a> </li> </ul> </aside> <!--sidebar end--> <!--main content start--> <div id="content" class="ui-content ui-content-aside-overlay"> <div class="ui-content-body"> <?php $this->load->view($konten); ?> </div> </div> <!--main content end--> <!--footer start--> <div id="footer" class="ui-footer"> 2017 &copy; MegaDin by ThemeBucket. </div> <!--footer end--> </div> <!-- inject:js --> <script src="<?= base_url('includes') ?>/bower_components/jquery/dist/jquery.min.js"></script> <script src="<?= base_url('includes') ?>/bower_components/bootstrap/dist/js/bootstrap.min.js"></script> <script src="<?= base_url('includes') ?>/bower_components/jquery.nicescroll/dist/jquery.nicescroll.min.js"></script> <script src="<?= base_url('includes') ?>/bower_components/autosize/dist/autosize.min.js"></script> <!-- endinject --> <!--highcharts--> <script src="<?= base_url('includes') ?>/bower_components/highcharts/highcharts.js"></script> <script src="<?= base_url('includes') ?>/bower_components/highcharts/highcharts-more.js"></script> <script src="<?= base_url('includes') ?>/bower_components/highcharts/modules/exporting.js"></script> <!--horizontal-timeline--> <script src="<?= base_url('includes') ?>/assets/js/horizontal-timeline/js/jquery.mobile.custom.min.js"></script> <script src="<?= base_url('includes') ?>/assets/js/horizontal-timeline/js/main.js"></script> <!-- Common Script --> <script src="<?= base_url('includes') ?>/dist/js/main.js"></script> <!-- Data Table--> <script src="<?= base_url('includes') ?>/bower_components/datatables.net/js/jquery.dataTables.min.js"></script> <script src="<?= base_url('includes') ?>/bower_components/datatables-tabletools/js/dataTables.tableTools.js"></script> <script src="<?= base_url('includes') ?>/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script> <script src="<?= base_url('includes') ?>/bower_components/datatables-colvis/js/dataTables.colVis.js"></script> <script src="<?= base_url('includes') ?>/bower_components/datatables-responsive/js/dataTables.responsive.js"></script> <script src="<?= base_url('includes') ?>/bower_components/datatables-scroller/js/dataTables.scroller.js"></script> <!--init data tables--> <script src="<?= base_url('includes') ?>/assets/js/init-datatables.js"></script> <!--Fuelux Tree Depencencies --> <script src="<?= base_url('includes') ?>/assets/js/fuelux/js/tree.min.js"></script> <script src="<?= base_url('includes') ?>/assets/js/fuelux/js/init-tree.js"></script> <!--jQuery Nestable Dependencies --> <script src="<?= base_url('includes') ?>/bower_components/Nestable/jquery.nestable.js"></script> <script src="<?= base_url('includes') ?>/assets/js/init-nestable.js"></script> <!--grafik--> <!-- Load plotly.js into the DOM --> <script src='https://cdn.plot.ly/plotly-latest.min.js'></script> </body> </html> <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Sample extends CI_Controller { function __construct() { parent::__construct(); if (!$this->session->userdata("username")) { redirect('Template/login'); } $this->load->model('m_kategori'); $this->load->model('m_barang'); $this->load->model('m_transaksi'); $this->load->helper('url'); } // function eclat_dinamis() { // echo '<pre>'; // //$transaksi = $this->db->select('id_barang')->get('detail_transaksi')->result_array() ; // $barang = $this->db->select(' barang.nama_barang , detail_transaksi.id_transaksi ')->from('detail_transaksi')->join('barang', 'detail_transaksi.id_barang = barang.id_barang', 'LEFT')->get()->result_array(); // // echo 'data barang'; // echo '<br>'; // // return print_r($barang); // } // // function eclat_dinamis2() { // $this->eclat_dinamis(); // // echo '<pre>'; // $id_transaksi = $this->db->select('id_transaksi') // ->from('detail_transaksi') // ->group_by('id_transaksi') // ->get() // ->result_array(); // // foreach ($id_transaksi as $id_t) { // $id_barang = $this->db->select('id_barang') // ->from('detail_transaksi') // ->where('id_transaksi', $id_t['id_transaksi']) // ->get() // ->result_array(); // $data1[][$id_t['id_transaksi']] = $id_barang; // } // // return print_r($data1); // } function eclat_d() { echo '<pre>'; $barang_data = $this->m_barang->tampil_data(); foreach ($barang_data as $key => $value) { $barang[$value->id_barang]['name'] = $value->nama_barang; $barang[$value->id_barang]['id_transaksi'] = array(); // $barang[$value->id_barang]['total_transaksi'] = count($this->m_transaksi->ambil_data_transaksi($value->id_barang)); } // print_r($barang); $data_transaksi = $this->m_transaksi->tampil_data(); foreach ($data_transaksi as $key => $value) { $transaksi[$value->id_transaksi]['id_barang'] = array(); $barang_transaksi = $this->m_transaksi->tampil_detail($value->id_transaksi); foreach ($barang_transaksi as $key2 => $value2) { array_push($transaksi[$value->id_transaksi]['id_barang'], $value2->id_barang); foreach ($barang_transaksi as $key3 => $value3) { if ($value2->id_barang != $value3->id_barang) { if (empty($silang[$value2->id_barang][$value3->id_barang])) { $silang[$value2->id_barang][$value3->id_barang] = array(); array_push($silang[$value2->id_barang][$value3->id_barang], $value->id_transaksi); } else { array_push($silang[$value2->id_barang][$value3->id_barang], $value->id_transaksi); } } } } } echo '---------------------------------------------------------------------------------------------------'; echo 'data Transaksi'; echo '<br>'; print_r($transaksi); foreach ($transaksi as $id_transaksi => $value) { foreach ($value['id_barang'] as $key => $id_barang) { array_push($barang[$id_barang]['id_transaksi'], $id_transaksi); } } echo '---------------------------------------------------------------------------------------------------'; echo 'List Item'; echo '<br>'; print_r($barang); echo '<br>'; echo '---------------------------------------------------------------------------------------------------'; echo 'Silang'; echo '<br>'; // foreach ($barang as $id_barang1 => $value) { //// echo '<br>'; //// echo $id_barang; // foreach ($barang as $id_barang2 => $value2) { // if ($id_barang1 != $id_barang2) { //// $silang[$id_barang1][$id_barang2] = array(); //// //// echo '<br>'; //// echo $id_barang1.'*'.$id_barang2; // } // } // } print_r($silang); $total_transaksi = count($transaksi); $max_support['value'] = 0; $max_support['id_barang1'] = 0; $max_support['id_barang2'] = 0; $max_confidence['value'] = 0; $max_confidence['id_barang1'] = 0; $max_confidence['id_barang2'] = 0; echo '<br>'; foreach ($silang as $id_barang1 => $array1) { foreach ($array1 as $id_barang2 => $value) { echo '<br>' . $id_barang1 . '=>' . $id_barang2 . ' = ' . count($silang[$id_barang1][$id_barang2]); if (count($silang[$id_barang1][$id_barang2]) > 1) { $silang_seleksi[$id_barang1][$id_barang2] = $value; $support[$id_barang1][$id_barang2] = count($silang[$id_barang1][$id_barang2]) / $total_transaksi; $confidence[$id_barang1][$id_barang2] = count($silang[$id_barang1][$id_barang2]) / count($barang[$id_barang1]['id_transaksi']); if ($max_support['value'] < $support[$id_barang1][$id_barang2]) { $max_support['value'] = $support[$id_barang1][$id_barang2]; $max_support['id_barang1'] = $id_barang1; $max_support['id_barang2'] = $id_barang2; } if ($max_confidence['value'] < $confidence[$id_barang1][$id_barang2]) { $max_confidence['value'] = $confidence[$id_barang1][$id_barang2]; $max_confidence['id_barang1'] = $id_barang1; $max_confidence['id_barang2'] = $id_barang2; } } } } echo '<br>'; echo '---------------------------------------------------------------------------------------------------'; echo '<br>'; echo 'Hasil Seleksi'; echo '<br>'; print_r($silang_seleksi); echo '<br>'; echo '---------------------------------------------------------------------------------------------------'; echo '<br>'; echo '<br>'; echo 'Total Transaksi'; echo '<br>'; print_r($total_transaksi); echo '<br>'; echo '---------------------------------------------------------------------------------------------------'; echo '<br>'; echo 'Support'; echo '<br>'; print_r($support); echo '<br>'; echo '---------------------------------------------------------------------------------------------------'; echo '<br>'; echo 'confidence'; echo '<br>'; echo '<br>'; print_r($confidence); echo '<br>'; echo '---------------------------------------------------------------------------------------------------'; echo '<br>'; echo 'Support Terbaik'; echo '<br>'; echo '<br>'; print_r($max_support); echo '<br>'; echo '---------------------------------------------------------------------------------------------------'; echo '<br>'; echo 'Confidence Terbaik'; echo '<br>'; echo '<br>'; print_r($max_confidence); echo '</pre>'; } function eclat_dk() { echo '<pre>'; $data_kategori = $this->m_kategori->tampil_data(); foreach ($data_kategori as $key => $value) { $kategori[$value->id_kategori]['name'] = $value->nama_kategori; $kategori[$value->id_kategori]['id_transaksi'] = array(); } print_r($kategori); // $barang_data = $this->m_barang->tampil_data(); // // foreach ($barang_data as $key => $value) { // $barang[$value->id_barang]['name'] = $value->nama_barang; // $barang[$value->id_barang]['id_transaksi'] = array(); // } // //// print_r($barang); // // $data_transaksi = $this->m_transaksi->tampil_data(); foreach ($data_transaksi as $key => $value) { $transaksi[$value->id_transaksi]['id_kategori'] = array(); $barang_transaksi = $this->m_transaksi->tampil_detail($value->id_transaksi); foreach ($barang_transaksi as $key2 => $value2) { array_push($transaksi[$value->id_transaksi]['id_kategori'], $value2->id_kategori); foreach ($barang_transaksi as $key3 => $value3) { if ($value2->id_kategori != $value3->id_kategori) { if (empty($silang[$value2->id_kategori][$value3->id_kategori])) { $silang[$value2->id_kategori][$value3->id_kategori] = array(); array_push($silang[$value2->id_kategori][$value3->id_kategori], $value->id_transaksi); } else { array_push($silang[$value2->id_kategori][$value3->id_kategori], $value->id_transaksi); } } } } } echo '<br>'; echo '---------------------------------------------------------------------------------------------------'; echo 'data Transaksi'; echo '<br>'; print_r($transaksi); // // foreach ($transaksi as $id_transaksi => $value) { // // foreach ($value['id_barang'] as $key => $id_barang) { // // array_push($barang[$id_barang]['id_transaksi'], $id_transaksi); // } // } // // echo '---------------------------------------------------------------------------------------------------'; // echo 'List Item'; // echo '<br>'; // // print_r($barang); // // echo '<br>'; // echo '---------------------------------------------------------------------------------------------------'; // // echo 'Silang'; // echo '<br>'; // print_r($silang); // $total_transaksi = count($transaksi); // // // $max_support['value'] = 0; // $max_support['id_barang1'] = 0; // $max_support['id_barang2'] = 0; // // $max_confidence['value'] = 0; // $max_confidence['id_barang1'] = 0; // $max_confidence['id_barang2'] = 0; // echo '<br>'; // foreach ($silang as $id_barang1 => $array1) { // foreach ($array1 as $id_barang2 => $value) { // echo '<br>' . $id_barang1 . '=>' . $id_barang2 . ' = ' . count($silang[$id_barang1][$id_barang2]); // // if (count($silang[$id_barang1][$id_barang2]) > 1) { // $silang_seleksi[$id_barang1][$id_barang2] = $value; // $support[$id_barang1][$id_barang2] = count($silang[$id_barang1][$id_barang2]) / $total_transaksi; // $confidence[$id_barang1][$id_barang2] = count($silang[$id_barang1][$id_barang2]) / count($barang[$id_barang1]['id_transaksi']); // // if ($max_support['value'] < $support[$id_barang1][$id_barang2]) { // $max_support['value'] = $support[$id_barang1][$id_barang2]; // $max_support['id_barang1'] = $id_barang1; // $max_support['id_barang2'] = $id_barang2; // } // // if ($max_confidence['value'] < $confidence[$id_barang1][$id_barang2]) { // $max_confidence['value'] = $confidence[$id_barang1][$id_barang2]; // $max_confidence['id_barang1'] = $id_barang1; // $max_confidence['id_barang2'] = $id_barang2; // } // } // } // } // echo '<br>'; // echo '---------------------------------------------------------------------------------------------------'; // // echo '<br>'; // echo 'Hasil Seleksi'; // echo '<br>'; // // print_r($silang_seleksi); // echo '<br>'; // echo '---------------------------------------------------------------------------------------------------'; // // echo '<br>'; // echo '<br>'; // echo 'Total Transaksi'; // echo '<br>'; // // print_r($total_transaksi); // // echo '<br>'; // echo '---------------------------------------------------------------------------------------------------'; // // // echo '<br>'; // echo 'Support'; // echo '<br>'; // // print_r($support); // // echo '<br>'; // echo '---------------------------------------------------------------------------------------------------'; // echo '<br>'; // echo 'confidence'; // echo '<br>'; // echo '<br>'; // print_r($confidence); // echo '<br>'; // echo '---------------------------------------------------------------------------------------------------'; // echo '<br>'; // echo 'Support Terbaik'; // echo '<br>'; // echo '<br>'; // print_r($max_support); // echo '<br>'; // echo '---------------------------------------------------------------------------------------------------'; // echo '<br>'; // echo 'Confidence Terbaik'; // echo '<br>'; // echo '<br>'; // print_r($max_confidence); echo '</pre>'; } function eclat() { echo '<pre>'; $barang[1]['name'] = 'PENSIL HB METALIK KIKO'; $barang[1]['id_transaksi'] = array(); // $barang[1]['id_barang'] = 1; $barang[2]['name'] = 'LIP/EYE PENSIL'; $barang[2]['id_transaksi'] = array(); $barang[3]['name'] = '<NAME> 12C MINI'; $barang[3]['id_transaksi'] = array(); $barang[4]['name'] = 'HVS A4S 80 SIDU'; $barang[4]['id_transaksi'] = array(); $barang[5]['name'] = 'PENSIL LCS JAPAN'; $barang[5]['id_transaksi'] = array(); $barang[6]['name'] = 'PENSIL INTERFANY 2B'; $barang[6]['id_transaksi'] = array(); $barang[7]['name'] = 'MECH PENSIL KENKO MP-808'; $barang[7]['id_transaksi'] = array(); $barang[8]['name'] = 'HVS A4S 80 SIDU'; $barang[8]['id_transaksi'] = array(); $barang[9]['name'] = 'ISI PENSIL D^BEST 2B'; $barang[9]['id_transaksi'] = array(); $barang[10]['name'] = 'MECH.PENSIL BP-899/BP-836'; $barang[10]['id_transaksi'] = array(); $barang[11]['name'] = '<NAME>'; $barang[11]['id_transaksi'] = array(); $barang[12]['name'] = '<NAME> CT-507'; $barang[12]['id_transaksi'] = array(); $barang[13]['name'] = 'HVS A4S 70 E PAPER'; $barang[13]['id_transaksi'] = array(); $barang[14]['name'] = 'MECH.PENSIL UNICORN'; $barang[14]['id_transaksi'] = array(); $barang[15]['name'] = 'HVS A4 80 SIDU'; $barang[15]['id_transaksi'] = array(); $barang[16]['name'] = 'BUKU FOLIO 50 SRITI'; $barang[16]['id_transaksi'] = array(); $barang[17]['name'] = 'PENSIL B<NAME>'; $barang[17]['id_transaksi'] = array(); $barang[18]['name'] = 'SPIDOL 12W PELANGI'; $barang[18]['id_transaksi'] = array(); $barang[19]['name'] = 'PENSIL L.TREE 0818-2B'; $barang[19]['id_transaksi'] = array(); $barang[20]['name'] = 'BUKU KAS FOLIO 100/3/2 GK'; $barang[20]['id_transaksi'] = array(); $barang[21]['name'] = '<NAME> PAEW-M9'; $barang[21]['id_transaksi'] = array(); $barang[22]['name'] = '<NAME> PG200'; $barang[22]['id_transaksi'] = array(); $barang[23]['name'] = 'KERTAS HVS 70 F4 SIDU ECER'; $barang[23]['id_transaksi'] = array(); $barang[24]['name'] = '<NAME>'; $barang[24]['id_transaksi'] = array(); $barang[25]['name'] = 'MECH.PENSIL BP-1070 YIBAI BIYE'; $barang[25]['id_transaksi'] = array(); $barang[26]['name'] = 'PENSIL'; $barang[26]['id_transaksi'] = array(); $barang[27]['name'] = '<NAME>'; $barang[27]['id_transaksi'] = array(); $barang[28]['name'] = '<NAME>'; $barang[28]['id_transaksi'] = array(); $barang[29]['name'] = 'MECH.PENSIL BP-1070 YIBAI BIYE'; $barang[29]['id_transaksi'] = array(); $barang[30]['name'] = 'MECH.PENSIL'; $barang[30]['id_transaksi'] = array(); $barang[31]['name'] = '<NAME> MS-55 PENSIL'; $barang[31]['id_transaksi'] = array(); $barang[32]['name'] = 'STANDARD BUKU POHON MC 6200'; $barang[32]['id_transaksi'] = array(); $barang[33]['name'] = 'SPIDOL SWMAN MARKER G-12'; $barang[33]['id_transaksi'] = array(); $barang[34]['name'] = '<NAME>'; $barang[34]['id_transaksi'] = array(); $barang[35]['name'] = '<NAME>'; $barang[35]['id_transaksi'] = array(); $barang[36]['name'] = '<NAME> (144)'; $barang[36]['id_transaksi'] = array(); $barang[37]['name'] = 'BLP+MECH PENSIL'; $barang[37]['id_transaksi'] = array(); $barang[38]['name'] = 'PENGHAPUS W/B+2 SPIDOL TF 222'; $barang[38]['id_transaksi'] = array(); $barang[39]['name'] = 'PENGGARIS EXCLUSIVE 30 CM'; $barang[39]['id_transaksi'] = array(); $barang[40]['name'] = '<NAME> HB'; $barang[40]['id_transaksi'] = array(); echo 'data barang'; echo '<br>'; print_r($barang); $transaksi[1]['id_barang'] = array(1, 2, 40, 11, 20); $transaksi[2]['id_barang'] = array(3, 4, 40, 20, 23); $transaksi[3]['id_barang'] = array(5, 6, 40, 12, 21); $transaksi[4]['id_barang'] = array(7, 8, 11, 20, 30); $transaksi[5]['id_barang'] = array(9, 4, 10, 21, 31); $transaksi[6]['id_barang'] = array(2, 10, 15, 26, 32); $transaksi[7]['id_barang'] = array(11, 12, 13, 22, 30); $transaksi[8]['id_barang'] = array(14, 4, 30, 40, 20); $transaksi[9]['id_barang'] = array(15, 2, 30, 21, 11); $transaksi[10]['id_barang'] = array(16, 2, 5, 10, 30); $transaksi[11]['id_barang'] = array(17, 18, 15, 20, 30); $transaksi[12]['id_barang'] = array(19, 20, 4, 2, 30); $transaksi[13]['id_barang'] = array(21, 22, 34, 36, 2); $transaksi[14]['id_barang'] = array(8, 2, 22, 34, 36); $transaksi[15]['id_barang'] = array(2, 8, 22, 30, 11); $transaksi[16]['id_barang'] = array(2, 9, 19, 39, 20); $transaksi[17]['id_barang'] = array(2, 23, 4, 11, 30); $transaksi[18]['id_barang'] = array(5, 23, 6, 17, 31); $transaksi[19]['id_barang'] = array(24, 25, 9, 13, 22); $transaksi[20]['id_barang'] = array(26, 23, 24, 15, 16); $transaksi[21]['id_barang'] = array(27, 28, 29, 40, 39, 21); $transaksi[22]['id_barang'] = array(30, 31, 13, 21, 38, 1); $transaksi[23]['id_barang'] = array(32, 33, 1, 7, 10); $transaksi[24]['id_barang'] = array(34, 35, 13, 20, 5); $transaksi[25]['id_barang'] = array(36, 37, 1, 10, 12); $transaksi[26]['id_barang'] = array(38, 39, 2, 40, 15); $transaksi[27]['id_barang'] = array(11, 23, 24, 15, 10); $transaksi[28]['id_barang'] = array(25, 27, 18, 11, 5); $transaksi[29]['id_barang'] = array(2, 23, 39, 28, 13); $transaksi[30]['id_barang'] = array(3, 40, 1, 2, 15); echo 'data Transaksi'; echo '<br>'; print_r($transaksi); foreach ($transaksi as $id_transaksi => $value) { foreach ($value['id_barang'] as $key => $id_barang) { array_push($barang[$id_barang]['id_transaksi'], $id_transaksi); } } echo 'List Item'; echo '<br>'; print_r($barang); $silang[1][2] = array(1, 30); $silang[1][3] = array(30); $silang[1][4] = array(); $silang[1][5] = array(); $silang[1][6] = array(); $silang[1][7] = array(23); $silang[1][8] = array(); $silang[1][9] = array(); $silang[1][10] = array(23, 25); $silang[1][11] = array(1); $silang[1][12] = array(25); $silang[1][13] = array(22); $silang[1][14] = array(); $silang[1][15] = array(30); $silang[1][16] = array(); $silang[1][17] = array(); $silang[1][18] = array(); $silang[1][19] = array(); $silang[1][20] = array(1); $silang[1][21] = array(22); $silang[1][22] = array(); $silang[1][23] = array(); $silang[1][24] = array(); $silang[1][25] = array(); $silang[1][26] = array(); $silang[1][27] = array(); $silang[1][28] = array(); $silang[1][29] = array(); $silang[1][30] = array(22); $silang[1][31] = array(22); $silang[1][32] = array(23); $silang[1][33] = array(23); $silang[1][34] = array(); $silang[1][35] = array(); $silang[1][36] = array(25); $silang[1][37] = array(25); $silang[1][38] = array(22); $silang[1][39] = array(); $silang[1][40] = array(1, 30); $silang[2][1] = array(1, 30); $silang[2][3] = array(30); $silang[2][4] = array(12, 17); $silang[2][5] = array(10); $silang[2][6] = array(); $silang[2][7] = array(); $silang[2][8] = array(14, 15); $silang[2][9] = array(16); $silang[2][10] = array(10); $silang[2][11] = array(1, 15, 17); $silang[2][12] = array(); $silang[2][13] = array(); $silang[2][14] = array(); $silang[2][15] = array(6, 9, 26, 30); $silang[2][16] = array(10); $silang[2][17] = array(); $silang[2][18] = array(); $silang[2][19] = array(12, 16); $silang[2][20] = array(1, 12, 16); $silang[2][21] = array(9, 13); $silang[2][22] = array(13, 14, 15); $silang[2][23] = array(17, 29); $silang[2][24] = array(); $silang[2][25] = array(); $silang[2][26] = array(6); $silang[2][27] = array(29); $silang[2][28] = array(); $silang[2][29] = array(); $silang[2][30] = array(9, 10, 12, 15, 17); $silang[2][31] = array(); $silang[2][32] = array(6); $silang[2][33] = array(); $silang[2][34] = array(); $silang[2][35] = array(); $silang[2][36] = array(13, 14); $silang[2][37] = array(); $silang[2][38] = array(26); $silang[2][39] = array(16, 26, 29); $silang[2][40] = array(1, 26, 30); $silang[3][1] = array(30); $silang[3][2] = array(30); $silang[3][4] = array(2); $silang[3][5] = array(); $silang[3][6] = array(); $silang[3][7] = array(); $silang[3][8] = array(); $silang[3][9] = array(); $silang[3][10] = array(); $silang[3][11] = array(); $silang[3][12] = array(); $silang[3][13] = array(); $silang[3][14] = array(); $silang[3][15] = array(30); $silang[3][16] = array(); $silang[3][17] = array(); $silang[3][18] = array(); $silang[3][19] = array(); $silang[3][20] = array(2); $silang[3][21] = array(); $silang[3][22] = array(); $silang[3][23] = array(2); $silang[3][24] = array(); $silang[3][25] = array(); $silang[3][26] = array(); $silang[3][27] = array(); $silang[3][28] = array(); $silang[3][29] = array(); $silang[3][30] = array(); $silang[3][31] = array(); $silang[3][32] = array(); $silang[3][33] = array(); $silang[3][34] = array(); $silang[3][35] = array(); $silang[3][36] = array(); $silang[3][37] = array(); $silang[3][38] = array(); $silang[3][39] = array(); $silang[3][40] = array(2, 30); $silang[4][1] = array(); $silang[4][2] = array(12, 17); $silang[4][3] = array(2); $silang[4][5] = array(10); $silang[4][6] = array(); $silang[4][7] = array(); $silang[4][8] = array(); $silang[4][9] = array(5); $silang[4][10] = array(5); $silang[4][11] = array(); $silang[4][12] = array(); $silang[4][13] = array(); $silang[4][14] = array(8); $silang[4][15] = array(); $silang[4][16] = array(); $silang[4][17] = array(); $silang[4][18] = array(); $silang[4][19] = array(); $silang[4][20] = array(2, 8, 12); $silang[4][21] = array(5); $silang[4][22] = array(); $silang[4][23] = array(2, 17); $silang[4][24] = array(); $silang[4][25] = array(); $silang[4][26] = array(); $silang[4][27] = array(); $silang[4][28] = array(); $silang[4][29] = array(); $silang[4][30] = array(8, 12, 17); $silang[4][31] = array(5); $silang[4][32] = array(); $silang[4][33] = array(); $silang[4][34] = array(); $silang[4][35] = array(); $silang[4][36] = array(); $silang[4][37] = array(); $silang[4][38] = array(); $silang[4][39] = array(); $silang[4][40] = array(2, 8); //(3,10,18,24,28) $silang[5][1] = array(); $silang[5][2] = array(10); $silang[5][3] = array(); $silang[5][4] = array(); $silang[5][6] = array(3, 18); $silang[5][7] = array(); $silang[5][8] = array(); $silang[5][9] = array(); $silang[5][10] = array(10); $silang[5][11] = array(17); $silang[5][12] = array(3); $silang[5][13] = array(); $silang[5][14] = array(); $silang[5][15] = array(); $silang[5][16] = array(10); $silang[5][17] = array(); $silang[5][18] = array(); $silang[5][19] = array(); $silang[5][20] = array(24); $silang[5][21] = array(3); $silang[5][22] = array(); $silang[5][23] = array(18); $silang[5][24] = array(); $silang[5][25] = array(); $silang[5][26] = array(); $silang[5][27] = array(28); $silang[5][28] = array(); $silang[5][29] = array(); $silang[5][30] = array(10); $silang[5][31] = array(18); $silang[5][32] = array(); $silang[5][33] = array(); $silang[5][34] = array(24); $silang[5][35] = array(24); $silang[5][36] = array(); $silang[5][37] = array(); $silang[5][38] = array(); $silang[5][39] = array(); $silang[5][40] = array(); // (3,18) $silang[6][1] = array(); $silang[6][2] = array(); $silang[6][3] = array(); $silang[6][4] = array(); $silang[6][5] = array(3, 18); $silang[6][7] = array(); $silang[6][8] = array(); $silang[6][9] = array(); $silang[6][10] = array(); $silang[6][11] = array(); $silang[6][12] = array(3); $silang[6][13] = array(); $silang[6][14] = array(); $silang[6][15] = array(); $silang[6][16] = array(); $silang[6][17] = array(18); $silang[6][18] = array(); $silang[6][19] = array(); $silang[6][20] = array(); $silang[6][21] = array(3); $silang[6][22] = array(); $silang[6][23] = array(); $silang[6][24] = array(); $silang[6][25] = array(); $silang[6][26] = array(); $silang[6][27] = array(); $silang[6][28] = array(); $silang[6][29] = array(); $silang[6][30] = array(); $silang[6][31] = array(); $silang[6][32] = array(18); $silang[6][33] = array(); $silang[6][34] = array(); $silang[6][35] = array(); $silang[6][36] = array(13, 14); $silang[6][37] = array(); $silang[6][38] = array(); $silang[6][39] = array(); $silang[6][40] = array(3); //(4,23) $silang[7][1] = array(23); $silang[7][2] = array(); $silang[7][3] = array(); $silang[7][4] = array(); $silang[7][5] = array(); $silang[7][6] = array(); $silang[7][8] = array(); $silang[7][9] = array(); $silang[7][10] = array(23); $silang[7][11] = array(4); $silang[7][12] = array(); $silang[7][13] = array(); $silang[7][14] = array(); $silang[7][15] = array(); $silang[7][16] = array(); $silang[7][17] = array(); $silang[7][18] = array(); $silang[7][19] = array(); $silang[7][20] = array(4); $silang[7][21] = array(); $silang[7][22] = array(); $silang[7][23] = array(); $silang[7][24] = array(); $silang[7][25] = array(); $silang[7][26] = array(); $silang[7][27] = array(); $silang[7][28] = array(); $silang[7][29] = array(); $silang[7][30] = array(4); $silang[7][31] = array(); $silang[7][32] = array(23); $silang[7][33] = array(23); $silang[7][34] = array(); $silang[7][35] = array(); $silang[7][36] = array(); $silang[7][37] = array(); $silang[7][38] = array(); $silang[7][39] = array(); $silang[7][40] = array(); //(4,14,15) $silang[8][1] = array(); $silang[8][2] = array(14); $silang[8][3] = array(); $silang[8][4] = array(10); $silang[8][5] = array(); $silang[8][6] = array(); $silang[8][7] = array(); $silang[8][9] = array(); $silang[8][10] = array(); $silang[8][11] = array(4); $silang[8][12] = array(); $silang[8][13] = array(); $silang[8][14] = array(); $silang[8][15] = array(); $silang[8][16] = array(); $silang[8][17] = array(); $silang[8][18] = array(); $silang[8][19] = array(); $silang[8][20] = array(4); $silang[8][21] = array(); $silang[8][22] = array(14, 15); $silang[8][23] = array(); $silang[8][24] = array(); $silang[8][25] = array(); $silang[8][26] = array(); $silang[8][27] = array(); $silang[8][28] = array(); $silang[8][29] = array(); $silang[8][30] = array(14, 15); $silang[8][31] = array(); $silang[8][32] = array(); $silang[8][33] = array(); $silang[8][34] = array(14); $silang[8][35] = array(); $silang[8][36] = array(14); $silang[8][37] = array(); $silang[8][38] = array(); $silang[8][39] = array(); $silang[8][40] = array(); //(5,16,19) $silang[9][1] = array(); $silang[9][2] = array(16); $silang[9][3] = array(); $silang[9][4] = array(5); $silang[9][5] = array(); $silang[9][6] = array(); $silang[9][7] = array(); $silang[9][8] = array(); $silang[9][10] = array(5); $silang[9][11] = array(); $silang[9][12] = array(); $silang[9][13] = array(); $silang[9][14] = array(); $silang[9][15] = array(); $silang[9][16] = array(); $silang[9][17] = array(); $silang[9][18] = array(); $silang[9][19] = array(16); $silang[9][20] = array(16); $silang[9][21] = array(); $silang[9][22] = array(19); $silang[9][23] = array(); $silang[9][24] = array(19); $silang[9][25] = array(19); $silang[9][26] = array(); $silang[9][27] = array(); $silang[9][28] = array(); $silang[9][29] = array(); $silang[9][30] = array(); $silang[9][31] = array(5); $silang[9][32] = array(); $silang[9][33] = array(); $silang[9][34] = array(); $silang[9][35] = array(); $silang[9][36] = array(); $silang[9][37] = array(); $silang[9][38] = array(); $silang[9][39] = array(); $silang[9][40] = array(); //(5,6,10,23,25,27) $silang[10][1] = array(23, 25); $silang[10][2] = array(10); $silang[10][3] = array(); $silang[10][4] = array(5); $silang[10][5] = array(10); $silang[10][6] = array(); $silang[10][7] = array(23); $silang[10][8] = array(); $silang[10][9] = array(5); $silang[10][11] = array(27); $silang[10][12] = array(25); $silang[10][13] = array(); $silang[10][14] = array(); $silang[10][15] = array(6, 27); $silang[10][16] = array(10); $silang[10][17] = array(); $silang[10][18] = array(); $silang[10][19] = array(); $silang[10][20] = array(); $silang[10][21] = array(5); $silang[10][22] = array(); $silang[10][23] = array(27); $silang[10][24] = array(27); $silang[10][25] = array(); $silang[10][26] = array(6); $silang[10][27] = array(); $silang[10][28] = array(); $silang[10][29] = array(); $silang[10][30] = array(10); $silang[10][31] = array(5); $silang[10][32] = array(23); $silang[10][33] = array(23); $silang[10][34] = array(); $silang[10][35] = array(); $silang[10][36] = array(25); $silang[10][37] = array(25); $silang[10][38] = array(); $silang[10][39] = array(); $silang[10][40] = array(30); //(1,4,7,9,15,17,27,28) $silang[11][1] = array(1); $silang[11][2] = array(1, 9, 15, 17); $silang[11][3] = array(); $silang[11][4] = array(17); $silang[11][5] = array(28); $silang[11][6] = array(); $silang[11][7] = array(4); $silang[11][8] = array(4, 15); $silang[11][9] = array(); $silang[11][10] = array(27); $silang[11][12] = array(7); $silang[11][13] = array(7); $silang[11][14] = array(); $silang[11][15] = array(27); $silang[11][16] = array(); $silang[11][17] = array(); $silang[11][18] = array(28); $silang[11][19] = array(); $silang[11][20] = array(1, 4); $silang[11][21] = array(9); $silang[11][22] = array(7, 15); $silang[11][23] = array(17, 27); $silang[11][24] = array(27); $silang[11][25] = array(28); $silang[11][26] = array(); $silang[11][27] = array(28); $silang[11][28] = array(); $silang[11][29] = array(); $silang[11][30] = array(4, 7, 9, 15, 17); //(1,4,7,9,15,17,27,28) $silang[11][31] = array(); $silang[11][32] = array(); $silang[11][33] = array(); $silang[11][34] = array(); $silang[11][35] = array(); $silang[11][36] = array(); $silang[11][37] = array(); $silang[11][38] = array(); $silang[11][39] = array(); $silang[11][40] = array(1); //(3,7,25) $silang[12][1] = array(25); $silang[12][2] = array(); $silang[12][3] = array(); $silang[12][4] = array(); $silang[12][5] = array(3); $silang[12][6] = array(3); $silang[12][7] = array(); $silang[12][8] = array(); $silang[12][9] = array(); $silang[12][10] = array(25); $silang[12][11] = array(7); $silang[12][13] = array(7); $silang[12][14] = array(); $silang[12][15] = array(); $silang[12][16] = array(); $silang[12][17] = array(); $silang[12][18] = array(); $silang[12][19] = array(); $silang[12][20] = array(); $silang[12][21] = array(3); $silang[12][22] = array(7); $silang[12][23] = array(); //(3,7,25) $silang[12][24] = array(); $silang[12][25] = array(); $silang[12][26] = array(); $silang[12][27] = array(); $silang[12][28] = array(); $silang[12][29] = array(); $silang[12][30] = array(7); $silang[12][31] = array(); $silang[12][32] = array(); $silang[12][33] = array(); $silang[12][34] = array(); $silang[12][35] = array(); $silang[12][36] = array(25); $silang[12][37] = array(25); $silang[12][38] = array(); $silang[12][39] = array(); $silang[12][40] = array(3); //(7,19,22,24,29) $silang[13][1] = array(); $silang[13][2] = array(29); $silang[13][3] = array(); $silang[13][4] = array(); $silang[13][5] = array(24); $silang[13][6] = array(); $silang[13][7] = array(); $silang[13][8] = array(); $silang[13][9] = array(19); $silang[13][10] = array(); $silang[13][11] = array(7); $silang[13][12] = array(7); $silang[13][14] = array(); $silang[13][15] = array(); $silang[13][16] = array(); $silang[13][17] = array(); $silang[13][18] = array(); $silang[13][19] = array(); $silang[13][20] = array(24); //(7,19,22,24,29) $silang[13][21] = array(22); $silang[13][22] = array(7, 19); $silang[13][23] = array(29); $silang[13][24] = array(19); $silang[13][25] = array(19); $silang[13][26] = array(); $silang[13][27] = array(); $silang[13][28] = array(29); $silang[13][29] = array(); $silang[13][30] = array(7, 22); $silang[13][31] = array(22); $silang[13][32] = array(); $silang[13][33] = array(); $silang[13][34] = array(24); $silang[13][35] = array(24); $silang[13][36] = array(); $silang[13][37] = array(); $silang[13][38] = array(22); $silang[13][39] = array(29); $silang[13][40] = array(); //(8) $silang[14][1] = array(); $silang[14][2] = array(); $silang[14][3] = array(); $silang[14][4] = array(8); $silang[14][5] = array(); $silang[14][6] = array(); $silang[14][7] = array(); $silang[14][8] = array(); $silang[14][9] = array(); $silang[14][10] = array(); $silang[14][11] = array(); $silang[14][12] = array(); $silang[14][13] = array(); $silang[14][15] = array(); $silang[14][16] = array(); $silang[14][17] = array(); $silang[14][18] = array(); $silang[14][19] = array(); $silang[14][20] = array(8); $silang[14][21] = array(); $silang[14][22] = array(); $silang[14][23] = array(); $silang[14][24] = array(); $silang[14][25] = array(); $silang[14][26] = array(); $silang[14][27] = array(); $silang[14][28] = array(); $silang[14][29] = array(); $silang[14][30] = array(8); $silang[14][31] = array(); $silang[14][32] = array(); $silang[14][33] = array(); $silang[14][34] = array(); $silang[14][35] = array(); $silang[14][36] = array(); $silang[14][37] = array(); $silang[14][38] = array(); $silang[14][39] = array(); $silang[14][40] = array(); //(6,9,11,20,26,27,30) $silang[15][1] = array(30); $silang[15][2] = array(6, 9, 26, 30); $silang[15][3] = array(30); $silang[15][4] = array(); $silang[15][5] = array(); $silang[15][6] = array(); $silang[15][7] = array(); $silang[15][8] = array(); $silang[15][9] = array(); $silang[15][10] = array(6, 27); $silang[15][11] = array(9, 27); $silang[15][12] = array(); $silang[15][13] = array(); $silang[15][14] = array(); $silang[15][16] = array(20); $silang[15][17] = array(11); $silang[15][18] = array(11); $silang[15][19] = array(); $silang[15][20] = array(11); //(6,9,11,20,26,27,30) $silang[15][21] = array(9); $silang[15][22] = array(); $silang[15][23] = array(20, 27); $silang[15][24] = array(20, 27); $silang[15][25] = array(); $silang[15][26] = array(6, 20); $silang[15][27] = array(); $silang[15][28] = array(); $silang[15][29] = array(); $silang[15][30] = array(9, 11); $silang[15][31] = array(); $silang[15][32] = array(6); $silang[15][33] = array(); $silang[15][34] = array(); $silang[15][35] = array(); $silang[15][36] = array(); $silang[15][37] = array(); $silang[15][38] = array(26); $silang[15][39] = array(26); $silang[15][40] = array(26, 30); //(10,20) $silang[16][1] = array(); $silang[16][2] = array(10); $silang[16][3] = array(); $silang[16][4] = array(); $silang[16][5] = array(10); $silang[16][6] = array(); $silang[16][7] = array(); $silang[16][8] = array(); $silang[16][9] = array(); $silang[16][10] = array(10); $silang[16][11] = array(); $silang[16][12] = array(); $silang[16][13] = array(); $silang[16][14] = array(); $silang[16][15] = array(20); $silang[16][17] = array(); $silang[16][18] = array(); $silang[16][19] = array(); $silang[16][20] = array(); $silang[16][21] = array(); $silang[16][22] = array(); $silang[16][23] = array(20); $silang[16][24] = array(20); $silang[16][25] = array(); $silang[16][26] = array(); $silang[16][27] = array(20); $silang[16][28] = array(); $silang[16][29] = array(); $silang[16][30] = array(10); $silang[16][31] = array(); $silang[16][32] = array(); $silang[16][33] = array(); $silang[16][34] = array(); $silang[16][35] = array(); $silang[16][36] = array(); $silang[16][37] = array(); $silang[16][38] = array(); $silang[16][39] = array(); $silang[16][40] = array(); // (11,18) $silang[17][1] = array(); $silang[17][2] = array(); $silang[17][3] = array(); $silang[17][4] = array(); $silang[17][5] = array(); $silang[17][6] = array(18); $silang[17][7] = array(18); $silang[17][8] = array(); $silang[17][9] = array(); $silang[17][10] = array(); $silang[17][11] = array(); $silang[17][12] = array(); $silang[17][13] = array(); $silang[17][14] = array(); $silang[17][15] = array(); $silang[17][16] = array(); $silang[17][18] = array(11); $silang[17][19] = array(); $silang[17][20] = array(11); $silang[17][21] = array(); $silang[17][22] = array(); $silang[17][23] = array(18); $silang[17][24] = array(); $silang[17][25] = array(); $silang[17][26] = array(); $silang[17][27] = array(); $silang[17][28] = array(); $silang[17][29] = array(); $silang[17][30] = array(11); $silang[17][31] = array(); $silang[17][32] = array(); $silang[17][33] = array(); $silang[17][34] = array(); $silang[17][35] = array(); $silang[17][36] = array(); $silang[17][37] = array(); $silang[17][38] = array(); $silang[17][39] = array(); $silang[17][40] = array(); //(11,28) $silang[18][1] = array(); $silang[18][2] = array(); $silang[18][3] = array(); $silang[18][4] = array(); $silang[18][5] = array(28); $silang[18][6] = array(); $silang[18][7] = array(); $silang[18][8] = array(); $silang[18][9] = array(); $silang[18][10] = array(); $silang[18][11] = array(); $silang[18][12] = array(28); $silang[18][13] = array(); $silang[18][14] = array(11); $silang[18][15] = array(); $silang[18][16] = array(11); $silang[18][17] = array(); $silang[18][19] = array(); $silang[18][20] = array(11); $silang[18][21] = array(); $silang[18][22] = array(); $silang[18][23] = array(); $silang[18][24] = array(); $silang[18][25] = array(); $silang[18][26] = array(); $silang[18][27] = array(28); $silang[18][28] = array(); $silang[18][29] = array(); $silang[18][30] = array(); $silang[18][31] = array(11); $silang[18][32] = array(); $silang[18][33] = array(); $silang[18][34] = array(); $silang[18][35] = array(); $silang[18][36] = array(); $silang[18][37] = array(); $silang[18][38] = array(); $silang[18][39] = array(); $silang[18][40] = array(); //(12,16) $silang[19][1] = array(); $silang[19][2] = array(16); $silang[19][3] = array(); $silang[19][4] = array(12); $silang[19][5] = array(); $silang[19][6] = array(); $silang[19][7] = array(); $silang[19][8] = array(); $silang[19][9] = array(); $silang[19][10] = array(); $silang[19][11] = array(); $silang[19][12] = array(); $silang[19][13] = array(); $silang[19][14] = array(); $silang[19][15] = array(); $silang[19][16] = array(); $silang[19][17] = array(); $silang[19][18] = array(); $silang[19][20] = array(12, 16); $silang[19][21] = array(); $silang[19][22] = array(); $silang[19][23] = array(); $silang[19][24] = array(); $silang[19][25] = array(); $silang[19][26] = array(); $silang[19][27] = array(); $silang[19][28] = array(); $silang[19][29] = array(); $silang[19][30] = array(12); $silang[19][31] = array(); $silang[19][32] = array(); $silang[19][33] = array(); $silang[19][34] = array(); $silang[19][35] = array(); $silang[19][36] = array(); $silang[19][37] = array(); $silang[19][38] = array(); $silang[19][39] = array(16); $silang[19][40] = array(); //(1,2,4,8,11,12,16,24) $silang[20][1] = array(1); $silang[20][2] = array(1, 12, 16); $silang[20][3] = array(2); $silang[20][4] = array(2, 8, 12); $silang[20][5] = array(24); $silang[20][6] = array(); $silang[20][7] = array(4); $silang[20][8] = array(4); $silang[20][9] = array(16); $silang[20][10] = array(); //(1,2,4,8,11,12,16,24) $silang[20][11] = array(1, 4); $silang[20][12] = array(); $silang[20][13] = array(24); $silang[20][14] = array(); $silang[20][15] = array(11); $silang[20][16] = array(); $silang[20][17] = array(11); $silang[20][18] = array(11); $silang[20][19] = array(12, 16); $silang[20][21] = array(); //(1,2,4,8,11,12,16,24) $silang[20][22] = array(); $silang[20][23] = array(2); $silang[20][24] = array(); $silang[20][25] = array(); $silang[20][26] = array(); $silang[20][27] = array(); $silang[20][28] = array(); $silang[20][29] = array(); $silang[20][30] = array(4, 8, 11, 12); $silang[20][31] = array(); $silang[20][32] = array(); $silang[20][33] = array(); $silang[20][34] = array(); $silang[20][35] = array(24); $silang[20][36] = array(); $silang[20][37] = array(); $silang[20][38] = array(); $silang[20][39] = array(16); $silang[20][40] = array(1, 2, 8); //(3,5,9,13,21,22) $silang[21][1] = array(22); $silang[21][2] = array(9, 13); $silang[21][3] = array(); $silang[21][4] = array(5); $silang[21][5] = array(3); $silang[21][6] = array(3); $silang[21][7] = array(); $silang[21][8] = array(); $silang[21][9] = array(5); $silang[21][10] = array(5); $silang[21][11] = array(9); $silang[21][12] = array(3); $silang[21][13] = array(22); $silang[21][14] = array(); $silang[21][15] = array(9); $silang[21][16] = array(); $silang[21][17] = array(); $silang[21][18] = array(); $silang[21][19] = array(); $silang[21][20] = array(); //(3,5,9,13,21,22) $silang[21][22] = array(); $silang[21][23] = array(); $silang[21][24] = array(); $silang[21][25] = array(); $silang[21][26] = array(); $silang[21][27] = array(21); $silang[21][28] = array(21); $silang[21][29] = array(21); $silang[21][30] = array(9); //(3,5,9,13,21,22) $silang[21][31] = array(5, 22); $silang[21][32] = array(); $silang[21][33] = array(); $silang[21][34] = array(13); $silang[21][35] = array(); $silang[21][36] = array(13); $silang[21][37] = array(); $silang[21][38] = array(22); $silang[21][39] = array(21); $silang[21][40] = array(3, 21); //(7,13,14,15,19) $silang[22][1] = array(); $silang[22][2] = array(13, 14, 15); $silang[22][3] = array(); $silang[22][4] = array(); $silang[22][5] = array(); $silang[22][6] = array(); $silang[22][7] = array(); $silang[22][8] = array(14, 15); $silang[22][9] = array(19); $silang[22][10] = array(); $silang[22][11] = array(7, 15); $silang[22][12] = array(7); $silang[22][13] = array(7, 19); $silang[22][14] = array(); $silang[22][15] = array(); $silang[22][16] = array(); $silang[22][17] = array(); $silang[22][18] = array(); $silang[22][19] = array(); $silang[22][20] = array(); $silang[22][21] = array(13); $silang[22][23] = array(); $silang[22][24] = array(19); $silang[22][25] = array(19); $silang[22][26] = array(); $silang[22][27] = array(); $silang[22][28] = array(); $silang[22][29] = array(); $silang[22][30] = array(7, 15); $silang[22][31] = array(); $silang[22][32] = array(); $silang[22][33] = array(); $silang[22][34] = array(13, 14); $silang[22][35] = array(); $silang[22][36] = array(13, 14); $silang[22][37] = array(); $silang[22][38] = array(); $silang[22][39] = array(); $silang[22][40] = array(); //(2,17,18,20,27,29) $silang[23][1] = array(); $silang[23][2] = array(17, 29); $silang[23][3] = array(2); $silang[23][4] = array(2, 17); $silang[23][5] = array(18); $silang[23][6] = array(18); $silang[23][7] = array(); $silang[23][8] = array(); $silang[23][9] = array(); $silang[23][10] = array(27); //(2,17,18,20,27,29) $silang[23][11] = array(17, 27); $silang[23][12] = array(); $silang[23][13] = array(29); $silang[23][14] = array(); $silang[23][15] = array(20); $silang[23][16] = array(20); $silang[23][17] = array(18); $silang[23][18] = array(); $silang[23][19] = array(); $silang[23][20] = array(2); //(2,17,18,20,27,29) $silang[23][21] = array(); $silang[23][22] = array(); $silang[23][24] = array(20, 27); $silang[23][25] = array(); $silang[23][26] = array(); $silang[23][27] = array(); $silang[23][28] = array(29); $silang[23][29] = array(); $silang[23][30] = array(17); //(2,17,18,20,27,29) $silang[23][31] = array(18); $silang[23][32] = array(); $silang[23][33] = array(); $silang[23][34] = array(); $silang[23][35] = array(); $silang[23][36] = array(); $silang[23][37] = array(); $silang[23][38] = array(); $silang[23][39] = array(29); $silang[23][40] = array(2); //(19,20,27) $silang[24][1] = array(); $silang[24][2] = array(); $silang[24][3] = array(); $silang[24][4] = array(); $silang[24][5] = array(); $silang[24][6] = array(); $silang[24][7] = array(); $silang[24][8] = array(); $silang[24][9] = array(19); $silang[24][10] = array(27); //(19,20,27) $silang[24][11] = array(27); $silang[24][12] = array(); $silang[24][13] = array(19); $silang[24][14] = array(); $silang[24][15] = array(20); $silang[24][16] = array(); $silang[24][17] = array(); $silang[24][18] = array(); $silang[24][19] = array(); $silang[24][20] = array(5); //(19,20,27) $silang[24][21] = array(); $silang[24][22] = array(19); $silang[24][23] = array(20, 27); $silang[24][25] = array(19); $silang[24][26] = array(20); $silang[24][27] = array(); $silang[24][28] = array(); $silang[24][29] = array(); $silang[24][30] = array(); //(19,20,27) $silang[24][31] = array(); $silang[24][32] = array(); $silang[24][33] = array(); $silang[24][34] = array(); $silang[24][35] = array(); $silang[24][36] = array(); $silang[24][37] = array(); $silang[24][38] = array(); $silang[24][39] = array(); $silang[24][40] = array(); //(19,28) $silang[25][1] = array(); $silang[25][2] = array(); $silang[25][3] = array(); $silang[25][4] = array(); $silang[25][5] = array(); $silang[25][6] = array(); $silang[25][7] = array(); $silang[25][8] = array(19); $silang[25][9] = array(); $silang[25][10] = array(); //(19,28) $silang[25][11] = array(28); $silang[25][12] = array(); $silang[25][13] = array(19); $silang[25][14] = array(); $silang[25][15] = array(); $silang[25][16] = array(); $silang[25][17] = array(); $silang[25][18] = array(28); $silang[25][19] = array(); $silang[25][20] = array(); //(19,28) $silang[25][21] = array(); $silang[25][22] = array(19); $silang[25][23] = array(); $silang[25][24] = array(19); $silang[25][26] = array(19); $silang[25][27] = array(28); $silang[25][28] = array(); $silang[25][29] = array(); $silang[25][30] = array(); //(19,28) $silang[25][31] = array(); $silang[25][32] = array(); $silang[25][33] = array(); $silang[25][34] = array(); $silang[25][35] = array(); $silang[25][36] = array(); $silang[25][37] = array(); $silang[25][38] = array(); $silang[25][39] = array(); $silang[25][40] = array(); // (6,20) $silang[26][1] = array(); $silang[26][2] = array(6); $silang[26][3] = array(); $silang[26][4] = array(); $silang[26][5] = array(); $silang[26][6] = array(); $silang[26][7] = array(); $silang[26][8] = array(); $silang[26][9] = array(); // (6,20) $silang[26][10] = array(6); $silang[26][11] = array(); $silang[26][12] = array(); $silang[26][13] = array(); $silang[26][14] = array(); $silang[26][15] = array(6, 20); $silang[26][16] = array(20); $silang[26][17] = array(); $silang[26][18] = array(); $silang[26][19] = array(); // (6,20) $silang[26][20] = array(); $silang[26][21] = array(); $silang[26][22] = array(); $silang[26][23] = array(20); $silang[26][24] = array(20); $silang[26][25] = array(); $silang[26][27] = array(); $silang[26][28] = array(); $silang[26][29] = array(); $silang[26][30] = array(); // (6,20) $silang[26][31] = array(); $silang[26][32] = array(6); $silang[26][33] = array(); $silang[26][34] = array(); $silang[26][35] = array(); $silang[26][36] = array(); $silang[26][37] = array(); $silang[26][38] = array(); $silang[26][39] = array(); $silang[26][40] = array(); //(21,28) $silang[27][1] = array(); $silang[27][2] = array(); $silang[27][3] = array(); $silang[27][4] = array(); $silang[27][5] = array(28); $silang[27][6] = array(); $silang[27][7] = array(); $silang[27][8] = array(); $silang[27][9] = array(); //(21,28) $silang[27][10] = array(28); $silang[27][11] = array(); $silang[27][12] = array(); $silang[27][13] = array(); $silang[27][14] = array(); $silang[27][15] = array(); $silang[27][16] = array(); $silang[27][17] = array(28); $silang[27][18] = array(); $silang[27][19] = array(); //(21,28) $silang[27][20] = array(21); $silang[27][21] = array(); $silang[27][22] = array(); $silang[27][23] = array(); $silang[27][24] = array(); $silang[27][25] = array(28); $silang[27][26] = array(); $silang[27][28] = array(21); $silang[27][29] = array(21); $silang[27][30] = array(); //(21,28) $silang[27][31] = array(); $silang[27][32] = array(); $silang[27][33] = array(); $silang[27][34] = array(); $silang[27][35] = array(); $silang[27][36] = array(); $silang[27][37] = array(); $silang[27][38] = array(); $silang[27][39] = array(21); $silang[27][40] = array(); //(21,29) $silang[28][1] = array(); $silang[28][2] = array(29); $silang[28][3] = array(); $silang[28][4] = array(); $silang[28][5] = array(); $silang[28][6] = array(); $silang[28][7] = array(); $silang[28][8] = array(); $silang[28][9] = array(); //(21,29) $silang[28][10] = array(); $silang[28][11] = array(); $silang[28][12] = array(); $silang[28][13] = array(29); $silang[28][14] = array(); $silang[28][15] = array(); $silang[28][16] = array(); $silang[28][17] = array(); $silang[28][18] = array(); $silang[28][19] = array(); //(21,29) $silang[28][20] = array(); $silang[28][21] = array(21); $silang[28][22] = array(); $silang[28][23] = array(29); $silang[28][24] = array(); $silang[28][25] = array(); $silang[28][26] = array(); $silang[28][27] = array(21); $silang[28][29] = array(21); $silang[28][30] = array(); //(21,29) $silang[28][31] = array(); $silang[28][32] = array(); $silang[28][33] = array(); $silang[28][34] = array(); $silang[28][35] = array(); $silang[28][36] = array(); $silang[28][37] = array(); $silang[28][38] = array(); $silang[28][39] = array(21, 29); $silang[28][40] = array(21); //(21) $silang[29][1] = array(); $silang[29][2] = array(); $silang[29][3] = array(); $silang[29][4] = array(); $silang[29][5] = array(); $silang[29][6] = array(); $silang[29][7] = array(); $silang[29][8] = array(); $silang[29][9] = array(); //(21) $silang[29][10] = array(); $silang[29][11] = array(); $silang[29][12] = array(); $silang[29][13] = array(); $silang[29][14] = array(); $silang[29][15] = array(); $silang[29][16] = array(); $silang[29][17] = array(); $silang[29][18] = array(); $silang[29][19] = array(); //(21) $silang[29][20] = array(); $silang[29][21] = array(21); $silang[29][22] = array(); $silang[29][23] = array(); $silang[29][24] = array(); $silang[29][25] = array(); $silang[29][26] = array(); $silang[29][27] = array(21); $silang[29][28] = array(); $silang[29][30] = array(); //(21) $silang[29][31] = array(); $silang[29][32] = array(); $silang[29][33] = array(); $silang[29][34] = array(); $silang[29][35] = array(); $silang[29][36] = array(); $silang[29][37] = array(); $silang[29][38] = array(); $silang[29][39] = array(21); $silang[29][40] = array(21); //(4,7,8,9,10,11,12,15,17,22) $silang[30][1] = array(22); $silang[30][2] = array(9, 10, 12, 15, 17); $silang[30][3] = array(); $silang[30][4] = array(8, 12, 17); $silang[30][5] = array(10); $silang[30][6] = array(); $silang[30][7] = array(4); $silang[30][8] = array(4, 14, 25); $silang[30][9] = array(); $silang[30][10] = array(10); //(4,7,8,9,10,11,12,15,17,22) $silang[30][11] = array(4, 7, 9, 15, 17); $silang[30][12] = array(7); $silang[30][13] = array(7, 22); $silang[30][14] = array(8); $silang[30][15] = array(9, 11); $silang[30][16] = array(10); $silang[30][17] = array(11); $silang[30][18] = array(11); $silang[30][19] = array(12); //(4,7,8,9,10,11,12,15,17,22) $silang[30][20] = array(4, 8, 11, 12); $silang[30][21] = array(9, 22); $silang[30][22] = array(7, 15); $silang[30][23] = array(17); $silang[30][24] = array(); $silang[30][25] = array(); $silang[30][26] = array(); $silang[30][27] = array(); $silang[30][28] = array(); $silang[30][29] = array(7); //(4,7,8,9,10,11,12,15,17,22) $silang[30][31] = array(22); $silang[30][32] = array(); $silang[30][33] = array(); $silang[30][34] = array(); $silang[30][35] = array(); $silang[30][36] = array(); $silang[30][37] = array(); $silang[30][38] = array(22); $silang[30][39] = array(); $silang[30][40] = array(8); //(5,18,22) $silang[31][1] = array(22); $silang[31][2] = array(); $silang[31][3] = array(); $silang[31][4] = array(5); $silang[31][5] = array(18); $silang[31][6] = array(18); $silang[31][7] = array(); $silang[31][8] = array(); $silang[31][9] = array(5); $silang[31][10] = array(5); //(5,18,22) $silang[31][11] = array(); $silang[31][12] = array(22); $silang[31][13] = array(); $silang[31][14] = array(); $silang[31][15] = array(); $silang[31][16] = array(18); $silang[31][17] = array(); $silang[31][18] = array(); $silang[31][19] = array(); //(5,18,22) $silang[31][20] = array(22); $silang[31][21] = array(18); $silang[31][22] = array(); $silang[31][23] = array(); $silang[31][24] = array(); $silang[31][25] = array(); $silang[31][26] = array(); $silang[31][27] = array(); $silang[31][28] = array(); $silang[31][29] = array(); //(5,18,22) $silang[31][30] = array(22); $silang[31][32] = array(); $silang[31][33] = array(); $silang[31][34] = array(); $silang[31][35] = array(); $silang[31][36] = array(); $silang[31][37] = array(); $silang[31][38] = array(22); $silang[31][39] = array(); $silang[31][40] = array(); //(6,23) $silang[32][1] = array(23); $silang[32][2] = array(6); $silang[32][3] = array(); $silang[32][4] = array(); $silang[32][5] = array(); $silang[32][6] = array(); $silang[32][7] = array(); $silang[32][8] = array(); $silang[32][9] = array(); $silang[32][10] = array(6, 23); //(6,23) $silang[32][11] = array(); $silang[32][12] = array(); $silang[32][13] = array(); $silang[32][14] = array(); $silang[32][15] = array(6); $silang[32][16] = array(); $silang[32][17] = array(); $silang[32][18] = array(); $silang[32][19] = array(); //(6,23) $silang[32][20] = array(); $silang[32][21] = array(); $silang[32][22] = array(); $silang[32][23] = array(); $silang[32][24] = array(); $silang[32][25] = array(); $silang[32][26] = array(6); $silang[32][27] = array(); $silang[32][28] = array(); $silang[32][29] = array(); //(6,23) $silang[32][30] = array(); $silang[32][31] = array(); $silang[32][33] = array(23); $silang[32][34] = array(); $silang[32][35] = array(); $silang[32][36] = array(); $silang[32][37] = array(); $silang[32][38] = array(); $silang[32][39] = array(); $silang[32][40] = array(); //(23) $silang[33][1] = array(23); $silang[33][2] = array(); $silang[33][3] = array(); $silang[33][4] = array(); $silang[33][5] = array(); $silang[33][6] = array(); $silang[33][7] = array(); $silang[33][8] = array(); $silang[33][9] = array(); $silang[33][10] = array(23); //(23) $silang[33][11] = array(); $silang[33][12] = array(); $silang[33][13] = array(); $silang[33][14] = array(); $silang[33][15] = array(); $silang[33][16] = array(); $silang[33][17] = array(); $silang[33][18] = array(); $silang[33][19] = array(); //(23) $silang[33][20] = array(); $silang[33][21] = array(); $silang[33][22] = array(); $silang[33][23] = array(); $silang[33][24] = array(); $silang[33][25] = array(); $silang[33][26] = array(); $silang[33][27] = array(); $silang[33][28] = array(); $silang[33][29] = array(); //(23) $silang[33][30] = array(); $silang[33][31] = array(); $silang[33][32] = array(23); $silang[33][34] = array(); $silang[33][35] = array(); $silang[33][36] = array(); $silang[33][37] = array(); $silang[33][38] = array(); $silang[33][39] = array(); $silang[33][40] = array(); //(13,14,24) $silang[34][1] = array(); $silang[34][2] = array(13, 14); $silang[34][3] = array(); $silang[34][4] = array(); $silang[34][5] = array(24); $silang[34][6] = array(); $silang[34][7] = array(); $silang[34][8] = array(14); $silang[34][9] = array(); $silang[34][10] = array(); //(13,14,24) $silang[34][11] = array(); $silang[34][12] = array(); $silang[34][13] = array(24); $silang[34][14] = array(); $silang[34][15] = array(); $silang[34][16] = array(); $silang[34][17] = array(); $silang[34][18] = array(); $silang[34][19] = array(24); //(13,14,24) $silang[34][20] = array(13); $silang[34][21] = array(13, 14); $silang[34][22] = array(); $silang[34][23] = array(); $silang[34][24] = array(); $silang[34][25] = array(); $silang[34][26] = array(); $silang[34][27] = array(); $silang[34][28] = array(); $silang[34][29] = array(); //(13,14,24) $silang[34][30] = array(); $silang[34][31] = array(); $silang[34][32] = array(); $silang[34][33] = array(); $silang[34][35] = array(); $silang[34][36] = array(13, 14); $silang[34][37] = array(); $silang[34][38] = array(); $silang[34][39] = array(); $silang[34][40] = array(); //(24) $silang[35][1] = array(); $silang[35][2] = array(); $silang[35][3] = array(); $silang[35][4] = array(); $silang[35][5] = array(24); $silang[35][6] = array(); $silang[35][7] = array(); $silang[35][8] = array(); $silang[35][9] = array(); $silang[35][10] = array(); //(24) $silang[35][11] = array(); $silang[35][12] = array(); $silang[35][13] = array(24); $silang[35][14] = array(); $silang[35][15] = array(); $silang[35][16] = array(); $silang[35][17] = array(); $silang[35][18] = array(); $silang[35][19] = array(24); //(24) $silang[35][20] = array(); $silang[35][21] = array(); $silang[35][22] = array(); $silang[35][23] = array(); $silang[35][24] = array(); $silang[35][25] = array(); $silang[35][26] = array(); $silang[35][27] = array(); $silang[35][28] = array(); $silang[35][29] = array(); //(24) $silang[35][30] = array(); $silang[35][31] = array(); $silang[35][32] = array(); $silang[35][33] = array(); $silang[35][34] = array(24); $silang[35][36] = array(); $silang[35][37] = array(); $silang[35][38] = array(); $silang[35][39] = array(); $silang[35][40] = array(); //(13,14,25) $silang[36][1] = array(25); $silang[36][2] = array(13, 14); $silang[36][3] = array(); $silang[36][4] = array(); $silang[36][5] = array(); $silang[36][6] = array(); $silang[36][7] = array(); $silang[36][8] = array(14); $silang[36][9] = array(); $silang[36][10] = array(25); //(13,14,25) $silang[36][11] = array(); $silang[36][12] = array(); $silang[36][13] = array(); $silang[36][14] = array(); $silang[36][15] = array(); $silang[36][16] = array(); $silang[36][17] = array(); $silang[36][18] = array(); $silang[36][19] = array(); //(13,14,25) $silang[36][20] = array(13); $silang[36][21] = array(13, 14); $silang[36][22] = array(); $silang[36][23] = array(); $silang[36][24] = array(); $silang[36][25] = array(); $silang[36][26] = array(); $silang[36][27] = array(); $silang[36][28] = array(); $silang[36][29] = array(); //(13,14,25) $silang[36][30] = array(); $silang[36][31] = array(); $silang[36][32] = array(); $silang[36][33] = array(); $silang[36][34] = array(13, 14); $silang[36][35] = array(); $silang[36][37] = array(); $silang[36][38] = array(); $silang[36][39] = array(); $silang[36][40] = array(); //(25) $silang[37][1] = array(25); $silang[37][2] = array(); $silang[37][3] = array(); $silang[37][4] = array(); $silang[37][5] = array(); $silang[37][6] = array(); $silang[37][7] = array(); $silang[37][8] = array(); $silang[37][9] = array(); $silang[37][10] = array(25); //(25) $silang[37][11] = array(); $silang[37][12] = array(); $silang[37][13] = array(); $silang[37][14] = array(); $silang[37][15] = array(); $silang[37][16] = array(); $silang[37][17] = array(); $silang[37][18] = array(); $silang[37][19] = array(); //(25) $silang[37][20] = array(); $silang[37][21] = array(); $silang[37][22] = array(); $silang[37][23] = array(); $silang[37][24] = array(); $silang[37][25] = array(); $silang[37][26] = array(); $silang[37][27] = array(); $silang[37][28] = array(); $silang[37][29] = array(); //(25) $silang[37][30] = array(); $silang[37][31] = array(); $silang[37][32] = array(); $silang[37][33] = array(); $silang[37][34] = array(); $silang[37][35] = array(); $silang[37][36] = array(); $silang[37][38] = array(); $silang[37][39] = array(); $silang[37][40] = array(); //(22,26) $silang[38][1] = array(22); $silang[38][2] = array(26); $silang[38][3] = array(); $silang[38][4] = array(); $silang[38][5] = array(); $silang[38][6] = array(); $silang[38][7] = array(); $silang[38][8] = array(); $silang[38][9] = array(); $silang[38][10] = array(); //(22,26) $silang[38][11] = array(); $silang[38][12] = array(); $silang[38][13] = array(22); $silang[38][14] = array(); $silang[38][15] = array(26); $silang[38][16] = array(); $silang[38][17] = array(); $silang[38][18] = array(); $silang[38][19] = array(); //(22,26) $silang[38][20] = array(22); $silang[38][21] = array(); $silang[38][22] = array(); $silang[38][23] = array(); $silang[38][24] = array(); $silang[38][25] = array(); $silang[38][26] = array(); $silang[38][27] = array(); $silang[38][28] = array(); $silang[38][29] = array(22); //(22,26) $silang[38][30] = array(22); $silang[38][31] = array(); $silang[38][32] = array(); $silang[38][33] = array(); $silang[38][34] = array(); $silang[38][35] = array(); $silang[38][36] = array(); $silang[38][37] = array(); $silang[38][39] = array(26); $silang[38][40] = array(26); //(16,21,26,29) $silang[39][1] = array(); $silang[39][2] = array(16, 26, 29); $silang[39][3] = array(); $silang[39][4] = array(); $silang[39][5] = array(); $silang[39][6] = array(); $silang[39][7] = array(); $silang[39][8] = array(); $silang[39][9] = array(16); $silang[39][10] = array(); //(16,21,26,29) $silang[39][11] = array(); $silang[39][12] = array(); $silang[39][13] = array(29); $silang[39][14] = array(); $silang[39][15] = array(26); $silang[39][16] = array(); $silang[39][17] = array(); $silang[39][18] = array(); $silang[39][19] = array(16); //(16,21,26,29) $silang[39][20] = array(16); $silang[39][21] = array(21); $silang[39][22] = array(); $silang[39][23] = array(29); $silang[39][24] = array(); $silang[39][25] = array(); $silang[39][26] = array(); $silang[39][27] = array(21); $silang[39][28] = array(21, 29); $silang[39][29] = array(21); //(16,21,26,29) $silang[39][30] = array(); $silang[39][31] = array(); $silang[39][32] = array(); $silang[39][33] = array(); $silang[39][34] = array(); $silang[39][35] = array(); $silang[39][36] = array(); $silang[39][37] = array(); $silang[39][38] = array(26); $silang[39][40] = array(26); //(1,2,3,8,21,26,30) $silang[40][1] = array(1, 30); $silang[40][2] = array(1, 30); $silang[40][3] = array(2, 30); $silang[40][4] = array(2, 8); $silang[40][5] = array(3); $silang[40][6] = array(3); $silang[40][7] = array(); $silang[40][8] = array(); $silang[40][9] = array(); $silang[40][10] = array(); //(1,2,3,8,21,26,30) $silang[40][11] = array(1); $silang[40][12] = array(3); $silang[40][13] = array(); $silang[40][14] = array(8); $silang[40][15] = array(26, 30); $silang[40][16] = array(); $silang[40][17] = array(); $silang[40][18] = array(); $silang[40][19] = array(); $silang[40][20] = array(1, 2, 8); //(1,2,3,8,21,26,30) $silang[40][21] = array(3, 21); $silang[40][22] = array(); $silang[40][23] = array(2); $silang[40][24] = array(); $silang[40][25] = array(); $silang[40][26] = array(); $silang[40][27] = array(21); $silang[40][28] = array(21); $silang[40][29] = array(21); $silang[40][30] = array(8); $silang[40][31] = array(); $silang[40][32] = array(); $silang[40][33] = array(); $silang[40][34] = array(); $silang[40][35] = array(); $silang[40][36] = array(); $silang[40][37] = array(); $silang[40][38] = array(26); $silang[40][39] = array(21, 26); echo 'Peyilangan'; echo '<br>'; print_r($silang); echo '<br>'; echo 'Seleksi'; echo '<br>'; foreach ($silang as $id_barang1 => $array1) { foreach ($array1 as $id_barang2 => $value) { echo '<br>' . $id_barang1 . '=>' . $id_barang2 . ' = ' . count($silang[$id_barang1][$id_barang2]); if (count($silang[$id_barang1][$id_barang2]) > 1) { $silang_seleksi[$id_barang1][$id_barang2] = $value; } } } echo '<br>'; echo '<br>'; echo 'Hasil Seleksi'; echo '<br>'; print_r($silang_seleksi); // echo count($silang[1][2]); } function fpgrowth() { $data['kategori'] = $this->m_kategori->tampil_data(); $data['konten'] = 'kategori/v_table'; $this->load->view('template/v_template', $data); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Kategori extends CI_Controller { function __construct() { parent::__construct(); if (!$this->session->userdata("username")) { redirect('Template/login'); } $this->load->model('m_kategori'); $this->load->helper('url'); } function index() { $data['kategori'] = $this->m_kategori->tampil_data(); $data['konten'] = 'kategori/v_table'; $this->load->view('template/v_template', $data); } function form() { $data['konten'] = 'kategori/v_form'; $this->load->view('template/v_template', $data); } function input() { $nama_kategori = $this->input->post('NamaKategori'); $data = array( 'nama_kategori' => $nama_kategori ); $this->m_kategori->input_data($data, 'kategori'); redirect('kategori'); } function hapus($id_kategori) { $where = array('id_kategori' => $id_kategori); $this->m_kategori->hapus_data($where, 'kategori'); redirect('kategori'); } function edit($id_kategori) { $where = array('id_kategori' => $id_kategori); $data['kategori'] = $this->m_kategori->edit_data($where, 'kategori')->result(); $data['konten'] = 'kategori/v_edit'; $this->load->view('template/v_template', $data); } function update() { $id_kategori = $this->input->post('id_kategori'); $nama_kategori = $this->input->post('NamaKategori'); $data = array( 'nama_kategori' => $nama_kategori, ); $where = array( 'id_kategori' => $id_kategori ); $this->m_kategori->update_data($where, $data, 'kategori'); redirect('Kategori'); } } <file_sep><div class="page-head-wrap"> <h4 class="margin0"> Welcome <?php echo $this->session->userdata("jabatan") ?> </h4> <div class="breadcrumb-right"> <ol class="breadcrumb"> <li><a href="#">Dashboard</a></li> <li class="active">Welcome </li> </ol> </div> </div> <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Dashboard extends CI_Controller { function __construct() { parent::__construct(); if (!$this->session->userdata("username")) { redirect('Template/login'); } } function index() { $data['konten'] = 'dashboard/v_index'; $this->load->view('template/v_template', $data); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Template extends CI_Controller { function __construct() { parent::__construct(); $this->load->model('m_login'); } public function index() { $this->load->view('welcome_message'); } public function login() { if ($this->session->userdata("username")) { redirect('Dashboard'); } $this->load->view('template/v_login'); } function aksi_login() { $username = $this->input->post('username'); $password = $this->input->post('password'); $where = array( 'username' => $username, 'password' => md5($password) ); $cek = $this->m_login->cek_login("akun", $where)->row(); if (count($cek) > 0) { $data_session = array( 'username' => $username, 'jabatan' => $cek->jabatan ); $this->session->set_userdata($data_session); redirect('Dashboard'); } else { echo "Username dan password salah !"; } } function logout() { $this->session->sess_destroy(); redirect('Template/login'); } // public function dashboard() { // $this->load->view('template/v_dashboard'); // } // // public function table() { // $this->load->view('template/v_table'); // } // // public function form() { // $this->load->view('template/v_form'); // } } <file_sep><div class="page-head-wrap"> <h4 class="margin0"> Edit Transaksi </h4> <div class="breadcrumb-right"> <ol class="breadcrumb"> <li><a href="#">Data Latih</a></li> <li><a href="#">Edit</a></li> <li class="active">Edit Transaksi</li> </ol> </div> </div> <!--page header end--> <div class="ui-content-body"> <div class="panel"> <div class="panel-body"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <?php foreach ($transaksi as $u) { ?> <form class="form-horizontal" role="form" action="<?php echo base_url() . 'Transaksi/update'; ?>" method="post"> <div class="form-group"> <label class="col-lg-3 col-sm-3 control-label">No. Transaksi</label> <div class="col-lg-9"> <input type="hidden" name="id_transaksi" value="<?php echo $u->id_transaksi ?>"> <input class="form-control" name="no_transaksi" value="<?php echo $u->no_transaksi ?>"> </div> </div> <div class="form-group"> <label class="col-lg-3 col-sm-3 control-label">Tanggal</label> <div class="col-lg-9"> <input class="form-control" name="tanggal" value="<?php echo $u->tanggal ?>" type="date"> </div> </div> <div class="form-group"> <div class="col-lg-offset-3 col-lg-9"> <a href="<?php echo site_url() . 'Transaksi'; ?>" type="button" class="btn btn-warning">Cancel</a> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> <?php } ?> </div> </div> </div> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Transaksi extends CI_Controller { function __construct() { parent::__construct(); if (!$this->session->userdata("username")) { redirect('Template/login'); } $this->load->model('m_transaksi'); $this->load->model('m_barang'); $this->load->helper('url'); } function index() { $data['konten'] = 'transaksi/v_table'; // $data['konten'] = 'transaksi/v_form_detail'; $data['transaksi'] = $this->m_transaksi->tampil_data(); $this->load->view('template/v_template', $data); } function form() { //$data['konten'] = 'transaksi/v_table'; // $data['transaksi'] = $this->m_transaksi->view_barang(); $data['konten'] = 'transaksi/v_form'; // var_dump($data); die; $this->load->view('template/v_template', $data); } function form_detail($id_transaksi) { $data['id_transaksi'] = $id_transaksi; $data['detail_transaksi'] = $this->m_transaksi->tampil_detail($id_transaksi); $data['barang'] = $this->m_barang->tampil_data(); $data['konten'] = 'transaksi/v_form_detail'; //var_dump($data); die; $this->load->view('template/v_template', $data); } function input() { $tgl = $this->input->post('Tanggal'); $no_transaksi = $this->input->post('NoTransaksi'); $dataTransaksi = array( 'tanggal' => $tgl, 'no_transaksi' => $no_transaksi ); $id_transaksi = $this->m_transaksi->insert($dataTransaksi); redirect('transaksi/form_detail/' . $id_transaksi); // echo $id_transaksi; // die(); //var_dump($sql->); die; // // $transaksi = $this->m_transaksi->view_transaksi(); // $query = $this->db->get('transaksi'); // // // $counttransaksi = $query->num_rows(); // $idtransaksi = ($transaksi[$counttransaksi - 1]->id_transaksi); // var_dump($idtransaksi); die; // end transaksi // detail transaksi // $total = $this->input->post('Total'); // $total_harga = $this->input->post('TotalHarga'); // $id_barang = $this->input->post('transaksi'); // // $datadetailTransaksi = array( // 'total_harga' => $total_harga, // 'total' => $total, // 'id_transaksi' => intval($idtransaksi), // 'id_barang' => $id_barang // ); // // $this->m_transaksi->input_data($datadetailTransaksi, 'detail_transaksi'); // $this->db->insert('detail_transaksi', $datadetailTransaksi); // end detail transaksi // $no_transaksi = $this->input->post('NoTransaksi'); // $tanggal = $this->input->post('Tanggal'); // $nama_barang = $this->input->post('NamaBarang'); // $total = $this->input->post('Total'); // $total_harga = $this->input->post('TotalHarga'); // // $data = array( // 'no_transaksi' => $no_transaksi, // 'tanggal' => $tanggal, // 'nama_barang' => $nama_barang, // 'total' => $total, // 'total_harga' => $total_harga // ); // // $this->m_transaksi->input_data($data, 'transaksi'); // redirect('transaksi'); } function input_detail() { //ambil data harga barang $id_transaksi = $this->input->post('id_transaksi'); $id_barang = $this->input->post('id_barang'); // $jumlah = $this->input->post('jumlah'); $dataTransaksi = array( 'id_transaksi' => $id_transaksi, 'id_barang' => $id_barang // 'jumlah' => $jumlah ); $this->m_transaksi->insert_detail($dataTransaksi); redirect('transaksi/form_detail/' . $id_transaksi); // var_dump($id_detail); die; } function hapus($id_transaksi) { $where = array('id_transaksi' => $id_transaksi); $this->m_transaksi->hapus_data($where, 'transaksi'); redirect('transaksi'); } function hapus_detail($id_detail_transaksi, $id_transaksi) { $where = array('id_detail_transaksi' => $id_detail_transaksi); $this->m_transaksi->hapus_data($where, 'detail_transaksi'); redirect('transaksi/form_detail/' . $id_transaksi); } function edit($id_transaksi) { $where = array('id_transaksi' => $id_transaksi); $data['transaksi'] = $this->m_transaksi->edit_data($where, 'transaksi')->result(); $data['konten'] = 'transaksi/v_edit'; $this->load->view('template/v_template', $data); } function update() { $id_transaksi = $this->input->post('id_transaksi'); $no_transaksi = $this->input->post('no_transaksi'); $tanggal = $this->input->post('tanggal'); $data = array( 'no_transaksi' => $no_transaksi, 'tanggal' => $tanggal ); $where = array( 'id_transaksi' => $id_transaksi ); $this->m_transaksi->update_data($where, $data, 'transaksi'); redirect('Transaksi'); } function edit_detail($id_detail_transaksi) { $where = array('id_detail_transaksi' => $id_detail_transaksi); $data['detail_transaksi'] = $this->m_transaksi->edit_data($where, 'detail_transaksi')->row(); $data['barang'] = $this->m_barang->tampil_data(); // print_r($data); // die(); $data['konten'] = 'transaksi/v_edit_detail'; $this->load->view('template/v_template', $data); } function update_detail() { // die(); $id_transaksi = $this->input->post('id_transaksi'); $id_detail_transaksi = $this->input->post('id_detail_transaksi'); $id_barang = $this->input->post('id_barang'); $jumlah = $this->input->post('jumlah'); $data = array( 'id_barang' => $id_barang, 'jumlah' => $jumlah ); $where = array( 'id_detail_transaksi' => $id_detail_transaksi ); $this->m_transaksi->update_data($where, $data, 'detail_transaksi'); redirect('transaksi/form_detail/' . $id_transaksi); } } <file_sep><div class="page-head-wrap"> <h4 class="margin0"> Edit Rak </h4> <div class="breadcrumb-right"> <ol class="breadcrumb"> <li><a href="#">Data Table</a></li> <li><a href="#">Edit</a></li> <li class="active">Edit Rak</li> </ol> </div> </div> <!--page header end--> <div class="ui-content-body"> <div class="panel"> <div class="panel-body"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <?php foreach ($rak as $u) { ?> <form class="form-horizontal" role="form" action="<?php echo base_url() . 'Rak/update'; ?>" method="post"> <div class="form-group"> <label class="col-lg-3 col-sm-3 control-label">No. Rak</label> <div class="col-lg-9"> <input type="hidden" name="id_rak" value="<?php echo $u->id_rak ?>"> <input class="form-control" name="NoRak" value="<?php echo $u->no_rak ?>"> </div> </div> <div class="form-group"> <label class="col-lg-3 col-sm-3 control-label">Lokasi</label> <div class="col-lg-9"> <input class="form-control" name="Lokasi" value="<?php echo $u->lokasi ?>"> </div> </div> <div class="form-group"> <label class="col-lg-3 col-sm-3 control-label">Nama Barang</label> <div class="col-lg-9"> <select class="form-control" name="id_barang"> <?php foreach ($barang as $u) { ?> <option value="<?= $u->id_barang; ?>"> <?= $u->nama_barang; ?></option> <?php } ?> </select> </div> </div> <br><br> <div class="form-group"> <div class="col-lg-offset-3 col-lg-9"> <a href="<?php echo site_url() . 'Rak'; ?>" type="button" class="btn btn-warning">Cancel</a> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> <?php } ?> </div> </div> </div> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Barang extends CI_Controller { function __construct() { parent::__construct(); if (!$this->session->userdata("username")) { redirect('Template/login'); } $this->load->model('m_barang'); $this->load->model('m_kategori'); $this->load->helper('url'); } function index() { $data['konten'] = 'barang/v_table'; $data['barang'] = $this->m_barang->tampil_data(); $this->load->view('template/v_template', $data); } function form() { $data['kategori'] = $this->m_kategori->tampil_data(); $data['konten'] = 'barang/v_form'; $this->load->view('template/v_template', $data); // var_dump($data); die(); } function input() { $id_kategori = $this->input->post('id_kategori'); $kode_barang = $this->input->post('KodeBarang'); $nama_barang = $this->input->post('NamaBarang'); // $jum_barang = $this->input->post('JumlahBarang'); // $harga_barang = $this->input->post('HargaBarang'); $data = array( 'id_kategori' => $id_kategori, 'kode_barang' => $kode_barang, 'nama_barang' => $nama_barang // 'jum_barang' => $jum_barang, // 'harga_barang' => $harga_barang ); $this->m_barang->input_data($data); redirect('barang'); } function hapus($id_barang) { $where = array('id_barang' => $id_barang); $this->m_barang->hapus_data($where, 'barang'); redirect('barang'); } function edit($id_barang) { $where = array('id_barang' => $id_barang); $data['barang'] = $this->m_barang->edit_data($where, 'barang')->result(); $data['kategori'] = $this->m_kategori->tampil_data(); $data['konten'] = 'barang/v_edit'; $this->load->view('template/v_template', $data); } function update() { $id_barang = $this->input->post('id_barang'); $id_kategori = $this->input->post('id_kategori'); $kode_barang = $this->input->post('KodeBarang'); $nama_barang = $this->input->post('NamaBarang'); // $jum_barang = $this->input->post('JumlahBarang'); // // $harga_barang = $this->input->post('HargaBarang'); $data = array( 'kode_barang' => $kode_barang, 'nama_barang' => $nama_barang, // 'jum_barang' => $jum_barang, 'id_kategori' => $id_kategori // 'harga_barang' => $harga_barang ); $where = array( 'id_barang' => $id_barang ); $this->m_barang->update_data($where, $data, 'barang'); redirect('Barang'); } } <file_sep><div class="page-head-wrap"> <h4 class="margin0"> Edit Detail </h4> <div class="breadcrumb-right"> <ol class="breadcrumb"> <li><a href="#">Data Latih</a></li> <li><a href="#">Detail</a></li> <li><a href="#">Edit</a></li> <li class="active">Edit Detail</li> </ol> </div> </div> <!--page header end--> <div class="ui-content-body"> <div class="panel"> <div class="panel-body"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <form class="form-horizontal" role="form" action="<?php echo base_url() . 'Transaksi/update_detail'; ?>" method="post"> <div class="form-group"> <label class="col-lg-3 col-sm-3 control-label">Nama Barang</label> <div class="col-lg-9"> <input type="hidden" name="id_detail_transaksi" value="<?php echo $detail_transaksi->id_detail_transaksi ?>"> <input type="hidden" name="id_transaksi" value="<?php echo $detail_transaksi->id_transaksi ?>"> <select class="form-control" name="id_barang"> <?php foreach ($barang as $t) { if ($t->id_barang == $detail_transaksi->id_barang) { ?> <option value="<?= $t->id_barang; ?>" selected><?= $t->nama_barang ?></option> <?php } else { ?> <option value="<?= $t->id_barang; ?>"><?= $t->nama_barang ?></option> <?php } } ?> </select> </div> </div> <!--. ' Rp.' . number_format($t->harga_barang, 0, ',', '.')--> <!-- <div class="form-group"> <label for="JumlahBarang" class="col-lg-3 col-sm-3 control-label">Jumlah Barang</label> <div class="col-lg-9"> <input class="form-control" name="jumlah" value="<?php echo $detail_transaksi->jumlah ?>"> </div> </div>--> <div class="form-group"> <div class="col-lg-offset-3 col-lg-9"> <a href="<?php echo site_url() . 'transaksi/form_detail/' . $detail_transaksi->id_transaksi; ?>" type="button" class="btn btn-warning">Cancel</a> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> </div> </div> </div> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Akun extends CI_Controller { function __construct() { parent::__construct(); if (!$this->session->userdata("username")) { redirect('Template/login'); } $this->load->model('m_akun'); $this->load->helper('url'); } function index() { $data['akun'] = $this->m_akun->tampil_data()->result(); $data['konten'] = 'akun/v_table'; $this->load->view('template/v_template', $data); } function form() { $data['konten'] = 'akun/v_form'; $this->load->view('template/v_template', $data); } function input() { $username = $this->input->post('Username'); $password = $<PASSWORD>('<PASSWORD>'); $jabatan = $this->input->post('Jabatan'); $data = array( 'username' => $username, 'password' => $<PASSWORD>, 'jabatan' => $jabatan ); $this->m_akun->input_data($data, 'akun'); redirect('akun'); } function hapus($id_akun) { $where = array('id_akun' => $id_akun); $this->m_akun->hapus_data($where, 'akun'); redirect('akun'); } function edit($id_akun) { $where = array('id_akun' => $id_akun); $data['akun'] = $this->m_akun->edit_data($where, 'akun')->result(); $data['konten'] = 'akun/v_edit'; $this->load->view('template/v_template', $data); } function update() { $id_akun = $this->input->post('id_akun'); $username = $this->input->post('Username'); $password = $this->input->post('Password'); $jabatan = $this->input->post('Jabatan'); $data = array( 'Username' => $username, 'Password' => <PASSWORD>, 'Jabatan' => $jabatan ); $where = array( 'id_akun' => $id_akun ); $this->m_akun->update_data($where, $data, 'akun'); redirect('Akun'); } } <file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- <link rel="shortcut icon" type="image/png" href="/imgs/favicon.png" /> --> <title>Login</title> <!-- inject:css --> <link rel="stylesheet" href="<?=base_url('includes')?>/bower_components/bootstrap/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="<?=base_url('includes')?>/bower_components/font-awesome/css/font-awesome.min.css"> <link rel="stylesheet" href="<?=base_url('includes')?>/bower_components/simple-line-icons/css/simple-line-icons.css"> <link rel="stylesheet" href="<?=base_url('includes')?>/bower_components/weather-icons/css/weather-icons.min.css"> <link rel="stylesheet" href="<?=base_url('includes')?>/bower_components/themify-icons/css/themify-icons.css"> <!-- endinject --> <!-- Main Style --> <link rel="stylesheet" href="<?=base_url('includes')?>/dist/css/main.css"> <script src="<?=base_url('includes')?>/assets/js/modernizr-custom.js"></script> </head> <body> <div class="sign-in-wrapper"> <div class="sign-container"> <div class="text-center"> <h2 class="logo"><img src="<?=base_url('includes')?>/imgs/logo-dark.png" width="130px" alt=""/></h2> <h4>Login to Admin</h4> </div> <form class="sign-in-form" role="form" action="<?php echo base_url() .('Template/aksi_login'); ?> " method="post"> <div class="form-group"> <input type="text" class="form-control" placeholder="Username" required="" name="username"> </div> <div class="form-group"> <input type="password" class="form-control" placeholder="<PASSWORD>" required="" name="password"> </div> <div class="form-group text-center"> <label class="i-checks"> <input type="checkbox"> <i></i> </label> Remember me </div> <button type="submit" class="btn btn-info btn-block">Login</button> <!-- <div class="text-center help-block"> <a href="<?=base_url('includes')?>/forgot-password.html"><small>Forgot password?</small></a> <p class="text-muted help-block"><small>Do not have an account?</small></p> </div> <a class="btn btn-md btn-default btn-block" href="registration.html">Create an account</a>--> </form> <div class="text-center copyright-txt"> <small>MegaDin - Copyright © 2017</small> </div> </div> </div> <!-- inject:js --> <script src="<?=base_url('includes')?>/bower_components/jquery/dist/jquery.min.js"></script> <script src="<?=base_url('includes')?>/bower_components/bootstrap/dist/js/bootstrap.min.js"></script> <script src="<?=base_url('includes')?>/bower_components/jquery.nicescroll/dist/jquery.nicescroll.min.js"></script> <script src="<?=base_url('includes')?>/bower_components/autosize/dist/autosize.min.js"></script> <!-- endinject --> <!-- Common Script --> <script src="<?=base_url('includes')?>/dist/js/main.js"></script> </body> </html> <file_sep><div class="page-head-wrap"> <h4 class="margin0"> Form Transaksi </h4> <div class="breadcrumb-right"> <ol class="breadcrumb"> <li><a href="#">Form</a></li> <li class="active">Form Transaksi</li> </ol> </div> </div> <!--page header end--> <div class="ui-content-body"> <div class="panel"> <div class="panel-body "> <div class="row"> <div class="col-md-8 col-md-offset-2"> <form class="form-horizontal" role="form" action="<?php echo base_url() . 'Transaksi/input'; ?>" method="post"> <div class="form-group"> <label for="NoTransaksi" class="col-lg-3 col-sm-3 control-label">No. Transaksi</label> <div class="col-lg-9"> <input class="form-control" name="NoTransaksi" placeholder="No Transaksi" type="number"> </div> </div> <div class="form-group"> <label for="Tanggal" class="col-lg-3 col-sm-3 control-label">Tanggal</label> <div class="col-lg-9"> <?php $tanggal = date('Y-m-d'); ?> <input class="form-control" name="Tanggal" placeholder="Tanggal" value="<?= $tanggal ?>" type="date" > </div> </div> <div class="form-group"> <div class="col-lg-offset-3 col-lg-9"> <a href="<?php echo site_url() . 'Transaksi'; ?>" type="button" class="btn btn-warning">Cancel</a> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> </div> </div> </div> </div> </div> <file_sep><div class="page-head-wrap"> <h4 class="margin0"> Edit Kategori </h4> <div class="breadcrumb-right"> <ol class="breadcrumb"> <li><a href="#">Data Table</a></li> <li><a href="#">Edit</a></li> <li class="active">Edit Kategori</li> </ol> </div> </div> <!--page header end--> <div class="ui-content-body"> <div class="panel"> <div class="panel-body"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <?php foreach ($kategori as $u) { ?> <form class="form-horizontal" role="form" action="<?php echo base_url() . 'Kategori/update'; ?>" method="post"> <div class="form-group"> <label for="NamaKategori" class="col-lg-3 col-sm-3 control-label">Nama Kategori</label> <div class="col-lg-9"> <input type="hidden" name="id_kategori" value="<?php echo $u->id_kategori ?>"> <input class="form-control" name="NamaKategori" value="<?php echo $u->nama_kategori ?>"> </div> </div> <div class="form-group"> <div class="col-lg-offset-3 col-lg-9"> <a href="<?php echo site_url() . 'Kategori'; ?>" type="button" class="btn btn-warning">Cancel</a> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> <?php } ?> </div> </div> </div> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Rak extends CI_Controller { function __construct() { parent::__construct(); $this->load->model('m_rak'); $this->load->model('m_barang'); $this->load->helper('url'); } function index() { $data['rak'] = $this->m_rak->tampil_data(); $data['konten'] = 'rak/v_table'; $this->load->view('template/v_template', $data); } function form() { $data['barang'] = $this->m_barang->tampil_data(); $data['konten'] = 'rak/v_form'; $this->load->view('template/v_template', $data); } function input() { $no_rak = $this->input->post('NoRak'); $lokasi = $this->input->post('Lokasi'); $id_barang = $this->input->post('id_barang'); $data = array( 'no_rak' => $no_rak, 'lokasi' => $lokasi, 'id_barang' => $id_barang ); $this->m_rak->input_data($data, 'rak'); redirect('rak'); } function hapus($id_rak) { $where = array('id_rak' => $id_rak); $this->m_rak->hapus_data($where, 'rak'); redirect('rak'); } function edit($id_rak) { $where = array('id_rak' => $id_rak); $data['rak'] = $this->m_rak->edit_data($where, 'rak')->result(); $data['barang'] = $this->m_barang->tampil_data(); $data['konten'] = 'rak/v_edit'; $this->load->view('template/v_template', $data); } function update() { $id_rak = $this->input->post('id_rak'); $id_barang = $this->input->post('id_barang'); $no_rak = $this->input->post('NoRak'); $lokasi = $this->input->post('Lokasi'); $data = array( 'no_rak' => $no_rak, 'lokasi' => $lokasi, 'id_barang' => $id_barang ); $where = array( 'id_rak' => $id_rak ); $this->m_rak->update_data($where, $data, 'rak'); redirect('Rak'); } } <file_sep><?php class M_transaksi extends CI_Model { function tampil_data() { // SUM(barang.harga_barang*detail_transaksi.jumlah) as harga $this->db->select('transaksi.*, '); $this->db->join('detail_transaksi', 'detail_transaksi.id_transaksi = transaksi.id_transaksi', 'LEFT'); $this->db->join('barang', 'barang.id_barang = detail_transaksi.id_barang', 'LEFT'); $this->db->limit(2000, 0); $this->db->group_by('transaksi.id_transaksi'); $query = $this->db->get('transaksi'); return $query->result(); } // function view_transaksi() { // $query = $this->db->query("SELECT * FROM transaksi"); // return $query->result(); // } function tampil_detail($id_transaksi) { $this->db->join('barang', 'barang.id_barang = detail_transaksi.id_barang', 'LEFT'); $this->db->where('detail_transaksi.id_transaksi', $id_transaksi); $query = $this->db->get('detail_transaksi'); return $query->result(); } function tampil_detail_kategori($id_transaksi) { $this->db->join('barang', 'barang.id_barang = detail_transaksi.id_barang', 'LEFT'); $this->db->where('detail_transaksi.id_transaksi', $id_transaksi); $this->db->group_by('barang.id_kategori'); $query = $this->db->get('detail_transaksi'); return $query->result(); } function hapus_data($where, $table) { $this->db->where($where); $this->db->delete($table); } function edit_data($where, $table) { return $this->db->get_where($table, $where); } function update_data($where, $data, $table) { $this->db->where($where); $this->db->update($table, $data); } function insert($data) { $this->db->insert('transaksi', $data); return $this->db->insert_id(); } function insert_detail($data) { $this->db->insert('detail_transaksi', $data); return $this->db->insert_id(); } function ambil_data_transaksi($id_barang) { $this->db->where('detail_transaksi.id_barang', $id_barang); $query = $this->db->get('detail_transaksi'); return $query->result(); } }
5e4ac4e9058db4510c531c2cc1dfa510498f5662
[ "PHP" ]
19
PHP
Rasoki/skripsi-tatlek
2e1a9cab841182fb6efc72dd30c373145332d4c3
db53187ece6febe9627d67ae002d8e0a18d9e8b4
refs/heads/master
<file_sep>var user = prompt("Please enter your name:"); if (user == null || user == "") { txt = "there!."; } var salutation = 'Hello '; var greeting = salutation + user; var greetingEl = document.getElementById('greeting'); greetingEl.textContent = greeting;<file_sep># eric-strackbein homework repo <file_sep>var user = 'Eric'; var salutation = 'Hello '; var greeting = salutation + user; var greetingEl = document.getElementById('greeting'); greetingEl.textContent = greeting; var price = 20, studentDiscount = 0.1, studentPrice = price - (price * studentDiscount), priceEl = document.getElementById('price'), studentPriceEl = document.getElementById('studentPrice'); priceEl.textContent = price.toFixed(2); studentPriceEl.textContent = studentPrice;
7c8333e391871499d84e572f87922f2d9be3b8ef
[ "JavaScript", "Markdown" ]
3
JavaScript
itdev160-sp2019/eric-strackbein
8a7e40cb99f88b471a0c11483612850a4b6d70f0
76b9788e1167d8d5f7b010eeead3ee6275e39eaa
refs/heads/main
<repo_name>Kateryna-Mykhailova/goit-react-hw-03-image-finder-test<file_sep>/src/components/Form/Form.js import React from 'react'; import { Component } from 'react'; import { v4 as uuid } from 'uuid'; import styles from '../Form/Form.module.css'; export class Form extends Component { state = { name: '', number: '', }; idName = uuid(); idNumber = uuid(); handleChange = e => { const { name, value } = e.target; this.setState({ [name]: value, // [e.target.name]: e.target.value, }); }; handleSubmit = e => { e.preventDefault(); const { name, number } = this.state; const newContact = { name, number, id: uuid(), }; this.props.addNewContact(newContact); this.resetForm(); }; resetForm = () => { // this.setState({...this.state}); this.setState({ name: '', number: '' }); }; render() { const { name, number } = this.state; return ( <form className={styles.form} onSubmit={this.handleSubmit}> <label className={styles.form_name} htmlFor={this.idName}> Name </label> <input className={styles.form_input} id={this.idName} name="name" value={name} type="text" onChange={this.handleChange} pattern="^[a-zA-Zа-яА-Я]+(([' -][a-zA-Zа-яА-Я ])?[a-zA-Zа-яА-Я]*)*$" title="Имя может состоять только из букв, апострофа, тире и пробелов. Например Adrian, <NAME>, <NAME> и т. п." required /> <label className={styles.form_name} htmlFor={this.idNumber}> Number </label> <input className={styles.form_input} id={this.idNumber} name="number" value={number} type="text" onChange={this.handleChange} pattern="\+?\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}" title="Номер телефона должен состоять цифр и может содержать пробелы, тире, круглые скобки и может начинаться с +" required /> <button className={styles.form_btn} type="submit"> Add </button> </form> ); } } <file_sep>/src/components/ImageGalleryItem/ImageGalleryItem.js import React from 'react'; import { Component } from 'react'; export default class ImageGalleryItem extends Component{ state = { searchInfo: null, error: null, status:'idle' } componentDidUpdate(prevProps, prevState) { if (prevProps.searchName !== this.props.searchName) { console.log('change name'); this.setState({status: 'pending'}) fetch(`https://pixabay.com/api/?q=${this.props.searchName}&page=&key=23204413-d213403835507960634485f04&image_type=photo&orientation=horizontal&per_page=12`) .then(response => { if (response.ok) { return response.json() } return Promise.reject( new Error (`There is no information for this query ${this.props.searchName}}`) ) } ) .then(searchInfo => this.setState({ searchInfo, status: 'resolved' })) .catch(error => this.setState({error, status: 'rejected'})) // .then(picture => this.setState({picture})).finally(() => this.setState({loading: false})) } } // 'idle' // 'pending' // 'resolved' // 'rejected' render() { const { searchInfo, error, status } = this.state; // const { searchName } = this.props; if (status === 'idle') { return <div>Enter a search name</div> } if (status === 'pending') { return <div>Loading...</div> } if (status === 'rejected') { return <h1>{error.message}</h1> } if (status === 'resolved') { return <p>{searchInfo.total}</p> } // return <div> // {error && <h1>{error.message}</h1>} // {loading && <div>Loading...</div>} // {!searchName && <div>Enter a search name</div>} // {searchInfo && <p>{searchInfo.total}</p>} // </div> } }<file_sep>/src/components/Searchbar/Searchbar.js import React from 'react'; import { Component } from 'react'; import { AiOutlineSearch } from "react-icons/ai"; import { toast } from 'react-toastify'; import '../Searchbar/Searchbar.module.css' export default class Searchbar extends Component{ state = { searchName: '', }; handleChange = e => { // const { name, value } = e.target; this.setState({ searchName: e.currentTarget.value.toLowerCase() }); }; handleSubmit = e => { e.preventDefault(); if (this.state.searchName.trim() === '') { // alert('Enter a search name') toast.warn("Enter a search name") return } this.props.onSubmit(this.state.searchName) this.resetForm(); // const newContact = { // name, // number, // id: uuid(), }; // this.props.addNewContact(newContact); // // }; resetForm = () => { this.setState({ searchName: '' }); }; render() { return ( <header className="Searchbar"> <form onSubmit={this.handleSubmit}className="SearchForm"> <button type="submit" className="SearchForm-button"> <AiOutlineSearch /> <span className="SearchForm-button-label">Search</span> </button> <input className="SearchForm-input" type="text" autoComplete="off" autoFocus placeholder="Search images and photos" value={this.state.searchName} onChange={this.handleChange} /> </form> </header> // <form > // <label > // Name // </label> // <input // type="text" // /> // <button type="submit"> // <AiOutlineSearch /> // Add // </button> // </form> ); } } <file_sep>/src/components/Filter/Filter.js import React from 'react'; import styles from '../Filter/Filter.module.css'; const Filter = ({ value, onChange }) => ( <label className={styles.form_name}> Find contacts by name <input className={styles.form_input} // id={this.idFilter } name="filter" value={value} type="text" onChange={onChange} // pattern="^[a-zA-Zа-яА-Я]+(([' -][a-zA-Zа-яА-Я ])?[a-zA-Zа-яА-Я]*)*$" // title="Имя может состоять только из букв, апострофа, тире и пробелов. Например Adrian, <NAME>, <NAME> и т. п." required /> </label> ); export default Filter; // export class Filter extends Component{ // state = { // filter: '' // }; // idFilter = uuid(); // handleChange = e => { // const { name, value } = e.target; // this.setState({ // [name]: value, // }); // console.log(this.state.filter); // // const {name} = this.state // // const findContact = { // // name // // }; // // console.log('kjh'); // // this.props.filterContacts(value); // this.props.filterContacts(this.state.filter); // }; // render() { // const { filter} = this.state; // return (<div> // <label>Find contacts by name // <input // id={this.idFilter } // name="filter" // value={filter} // type="text" // onChange={this.handleChange} // pattern="^[a-zA-Zа-яА-Я]+(([' -][a-zA-Zа-яА-Я ])?[a-zA-Zа-яА-Я]*)*$" // title="Имя может состоять только из букв, апострофа, тире и пробелов. Например Adrian, <NAME>, <NAME>'Artagnan и т. п." // required // /></label></div> // ) // } // } // <p>Find contacts by name</p> // <label htmlFor={this.idName}>Name</label> // <input // id={this.idName} // name="name" // value={this.state.name} // type="text" // onChange={this.handleChange} // pattern="^[a-zA-Zа-яА-Я]+(([' -][a-zA-Zа-яА-Я ])?[a-zA-Zа-яА-Я]*)*$" // title="Имя может состоять только из букв, апострофа, тире и пробелов. Например Adrian, <NAME>, <NAME>'Artagnan и т. п." // required // />
9c74cf84cb64317cd734565ea34e33ed793f3cdb
[ "JavaScript" ]
4
JavaScript
Kateryna-Mykhailova/goit-react-hw-03-image-finder-test
985da88c2387bf9754582f16238d4efb3ba29e5e
3c21a68ae90b378ee8ffe60775bc3c980925116a
refs/heads/master
<file_sep>package com.javarush.task.task19.task1904; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; /* И еще один адаптер */ public class Solution { public static void main(String[] args) throws Exception { //Scanner scanner = new Scanner(new File("D://1.txt")); //System.out.println(scanner.nextLine()); } public static class PersonScannerAdapter implements PersonScanner { private final Scanner fileScanner; public PersonScannerAdapter(Scanner fileScanner) { this.fileScanner = fileScanner; } @Override public Person read() throws IOException { String [] lines = fileScanner.nextLine().split(" "); String sDate = lines[3] + " " + lines[4] + " " + lines [5]; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy"); Date date = new Date(); try { date = simpleDateFormat.parse(sDate); } catch (ParseException pe){ System.out.println(pe); } return new Person(lines[1], lines[2], lines[0], date); } @Override public void close() throws IOException { fileScanner.close(); } } } <file_sep>package com.javarush.task.task39.task3913; import com.javarush.task.task39.task3913.query.*; import java.io.*; import java.nio.file.Path; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.stream.Collectors; public class LogParser implements IPQuery, UserQuery, DateQuery, EventQuery, QLQuery { static class Entry { private Map <String, Object> params = new HashMap<>(); String ip; String user; Date date; Event event; int taskNumber; Status status; public Entry(String ip, String user, Date date, Event event, int taskNumber, Status status) { this.ip = ip; this.user = user; this.date = date; this.event = event; this.taskNumber = taskNumber; this.status = status; params.put("ip" , ip); params.put("user", user); params.put("date", date); params.put("event", event); params.put("status", status); } } Path logDir; ArrayList<Entry> entries; public LogParser(Path logDir) { this.logDir = logDir; entries = new ArrayList<>(); parseData(logDir.toFile()); } private void parseData(File directory) { for (File file : directory.listFiles()) { if (file.isDirectory()) { parseData(file); continue; } if (!file.getName().endsWith(".log")) continue; try { BufferedReader fileReader = new BufferedReader(new FileReader(file)); while (fileReader.ready()) { String[] data = fileReader.readLine().split("\t"); DateFormat dateFormat = new SimpleDateFormat("d.M.y H:m:s"); Date date = null; try { date = dateFormat.parse(data[2]); } catch (ParseException e) { System.out.println("Неверный формат даты"); } Event event = null; String additionalEvent = null; String[] sEvent = data[3].split(" "); for (Event value : Event.values()) { if (value == Event.valueOf(sEvent[0])) event = Event.valueOf(sEvent[0]); } if (sEvent.length > 1) additionalEvent = sEvent[1]; Status status = null; for (Status value : Status.values()) { if (value == Status.valueOf(data[4])) status = Status.valueOf(data[4]); } int taskNumber = -1; if (additionalEvent != null) taskNumber = Integer.parseInt(additionalEvent); Entry entry = new Entry(data[0], data[1], date, event, taskNumber, status); entries.add(entry); } } catch (IOException e) { e.printStackTrace(); } } } private Set<Entry> filterByDate(Date after, Date before) { return entries.stream().filter(entry -> { if (after == null && before == null) return true; if (after == null) return entry.date.before(before); if (before == null) return entry.date.after(after); return (entry.date.after(after) && entry.date.before(before)); }).collect(Collectors.toSet()); } @Override public int getNumberOfUniqueIPs(Date after, Date before) { return getUniqueIPs(after, before).size(); } @Override public Set<String> getUniqueIPs(Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<String> result = new HashSet<>(); for (Entry entry : filteredEntries) result.add(entry.ip); return result; } @Override public Set<String> getIPsForUser(String user, Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<String> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.user.equals(user)) result.add(entry.ip); } return result; } @Override public Set<String> getIPsForEvent(Event event, Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<String> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.event.equals(event)) result.add(entry.ip); } return result; } @Override public Set<String> getIPsForStatus(Status status, Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<String> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.status.equals(status)) result.add(entry.ip); } return result; } @Override public Set<String> getAllUsers() { Set<String> result = new HashSet<>(); for (Entry entry : entries) result.add(entry.user); return result; } @Override public int getNumberOfUsers(Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<String> result = new HashSet<>(); for (Entry entry : filteredEntries) { result.add(entry.user); } return result.size(); } @Override public int getNumberOfUserEvents(String user, Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<Event> events = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.user.equals(user)) events.add(entry.event); } return events.size(); } @Override public Set<String> getUsersForIP(String ip, Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<String> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.ip.equals(ip)) result.add(entry.user); } return result; } @Override public Set<String> getLoggedUsers(Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<String> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.event == Event.LOGIN) result.add(entry.user); } return result; } @Override public Set<String> getDownloadedPluginUsers(Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<String> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.event == Event.DOWNLOAD_PLUGIN) result.add(entry.user); } return result; } @Override public Set<String> getWroteMessageUsers(Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<String> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.event == Event.WRITE_MESSAGE) result.add(entry.user); } return result; } @Override public Set<String> getSolvedTaskUsers(Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<String> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.event == Event.SOLVE_TASK) result.add(entry.user); } return result; } @Override public Set<String> getSolvedTaskUsers(Date after, Date before, int task) { Set<Entry> filteredEntries = filterByDate(after, before); Set<String> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.event == Event.SOLVE_TASK) if (entry.taskNumber == task) result.add(entry.user); } return result; } @Override public Set<String> getDoneTaskUsers(Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<String> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.event == Event.DONE_TASK) result.add(entry.user); } return result; } @Override public Set<String> getDoneTaskUsers(Date after, Date before, int task) { Set<Entry> filteredEntries = filterByDate(after, before); Set<String> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.event == Event.DONE_TASK) if (entry.taskNumber == task) result.add(entry.user); } return result; } @Override public Set<Date> getDatesForUserAndEvent(String user, Event event, Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<Date> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.user.equals(user) && entry.event.equals(event)) result.add(entry.date); } return result; } @Override public Set<Date> getDatesWhenSomethingFailed(Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<Date> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.status == Status.FAILED) result.add(entry.date); } return result; } @Override public Set<Date> getDatesWhenErrorHappened(Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<Date> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.status == Status.ERROR) result.add(entry.date); } return result; } private List<Entry> getSortedEntriesByDate(Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); List<Entry> sortedEntriesByDate = new ArrayList<>(filteredEntries); sortedEntriesByDate.sort((Entry entry1, Entry entry2) -> { if (entry1.date.before(entry2.date)) return -1; else if (entry2.date.before(entry1.date)) return 1; return 0; }); return sortedEntriesByDate; } @Override public Date getDateWhenUserLoggedFirstTime(String user, Date after, Date before) { List<Entry> sortedEntriesByDate = getSortedEntriesByDate(after, before); for (Entry entry : sortedEntriesByDate) { if (entry.user.equals(user) && entry.event == Event.LOGIN) return entry.date; } return null; } @Override public Date getDateWhenUserSolvedTask(String user, int task, Date after, Date before) { List<Entry> sortedEntriesByDate = getSortedEntriesByDate(after, before); for (Entry entry : sortedEntriesByDate) { if (entry.user.equals(user) && entry.event == Event.SOLVE_TASK && entry.taskNumber == task) return entry.date; } return null; } @Override public Date getDateWhenUserDoneTask(String user, int task, Date after, Date before) { List<Entry> sortedEntriesByDate = getSortedEntriesByDate(after, before); for (Entry entry : sortedEntriesByDate) { if (entry.user.equals(user) && entry.event == Event.DONE_TASK && entry.taskNumber == task) return entry.date; } return null; } @Override public Set<Date> getDatesWhenUserWroteMessage(String user, Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<Date> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.user.equals(user) && entry.event == Event.WRITE_MESSAGE) result.add(entry.date); } return result; } @Override public Set<Date> getDatesWhenUserDownloadedPlugin(String user, Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<Date> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.user.equals(user) && entry.event == Event.DOWNLOAD_PLUGIN) result.add(entry.date); } return result; } @Override public int getNumberOfAllEvents(Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<Event> result = new HashSet<>(); for (Entry entry : filteredEntries) { result.add(entry.event); } return result.size(); } @Override public Set<Event> getAllEvents(Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<Event> result = new HashSet<>(); for (Entry entry : filteredEntries) { result.add(entry.event); } return result; } @Override public Set<Event> getEventsForIP(String ip, Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<Event> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.ip.equals(ip)) result.add(entry.event); } return result; } @Override public Set<Event> getEventsForUser(String user, Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<Event> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.user.equals(user)) result.add(entry.event); } return result; } @Override public Set<Event> getFailedEvents(Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<Event> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.status == Status.FAILED) result.add(entry.event); } return result; } @Override public Set<Event> getErrorEvents(Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Set<Event> result = new HashSet<>(); for (Entry entry : filteredEntries) { if (entry.status == Status.ERROR) result.add(entry.event); } return result; } @Override public int getNumberOfAttemptToSolveTask(int task, Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); int counter = 0; for (Entry entry : filteredEntries) { if (entry.event == Event.SOLVE_TASK && entry.taskNumber == task) counter++; } return counter; } @Override public int getNumberOfSuccessfulAttemptToSolveTask(int task, Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); int counter = 0; for (Entry entry : filteredEntries) { if (entry.event == Event.DONE_TASK && entry.taskNumber == task) counter++; } return counter; } @Override public Map<Integer, Integer> getAllSolvedTasksAndTheirNumber(Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Map<Integer, Integer> result = new HashMap<>(); int counter = 1; for (Entry entry : filteredEntries) { if (entry.event == Event.SOLVE_TASK) if (result.containsKey(entry.taskNumber)) { counter = result.get(entry.taskNumber); result.put(entry.taskNumber, ++counter); counter = 1; } else result.put(entry.taskNumber, counter); } return result; } @Override public Map<Integer, Integer> getAllDoneTasksAndTheirNumber(Date after, Date before) { Set<Entry> filteredEntries = filterByDate(after, before); Map<Integer, Integer> result = new HashMap<>(); int counter = 1; for (Entry entry : filteredEntries) { if (entry.event == Event.DONE_TASK) if (result.containsKey(entry.taskNumber)) { counter = result.get(entry.taskNumber); result.put(entry.taskNumber, ++counter); counter = 1; } else result.put(entry.taskNumber, counter); } return result; } private Set<Date> getAllDates() { Set<Date> result = new HashSet<>(); for (Entry entry : entries) result.add(entry.date); return result; } private Set<Status> getAllStatuses() { Set<Status> result = new HashSet<>(); for (Entry entry : entries) result.add(entry.status); return result; } // @Override // public Set<Object> execute(String query) { // String [] queryArray = query.split(" "); // String [] fields = new String[]{"ip", "user", "date", "event", "status"}; // // Set<Object> result = new HashSet<>(); // // if (query.startsWith("get " + fields[0])) // result.addAll(getUniqueIPs(null, null)); // // else if (query.startsWith("get " + fields[1])) // result.addAll(getAllUsers()); // // else if (query.startsWith("get " + fields[2])) // result.addAll(getAllDates()); // // else if (query.startsWith("get " + fields[3])) // result.addAll(getAllEvents(null, null)); // // else if (query.startsWith("get " + fields[4])) // result.addAll(getAllStatuses()); // // if (query.contains(" for ")) // result.stream().filter(new Predicate<Object>() { // @Override // public boolean test(Object o) { // // return false; // } // }); // // return result; // } private Set<Object> getShortQuery(String query) { Set<Object> result = new HashSet<>(); if (query.equals("ip")) { result.addAll(getUniqueIPs(null, null)); } else if (query.equals("user")) result.addAll(getAllUsers()); else if (query.equals("date")) result.addAll(getAllDates()); else if (query.equals("event")) result.addAll(getAllEvents(null, null)); else if (query.equals("status")) result.addAll(getAllStatuses()); return result; } @Override public Set<Object> execute(String query) throws ParseException { String [] fieldArray = query.split(" "); String [] paramArray = query.split("\""); if (!query.contains(" = \"")) return getShortQuery(fieldArray[1]); Set<Object> result = new HashSet<>(); String field1 = fieldArray[1]; String field2 = fieldArray[3]; String value = paramArray[1]; Date dateValue = null; DateFormat dateFormat = new SimpleDateFormat("d.M.y H:m:s"); if (field2.equals("date")) { dateValue = dateFormat.parse(value); } Set<Entry> filteredEntries = null; if (query.contains(" and date between ")) filteredEntries = filterByDate(dateFormat.parse(paramArray[3]), dateFormat.parse(paramArray[5])); else filteredEntries = filterByDate(null, null); for (Entry entry : filteredEntries){ // String d = getStringValue(entry.params.get(field2)); if (entry.params.get(field2).toString().equals(value) || entry.params.get(field2).equals(dateValue)) result.add(entry.params.get(field1)); } return result; } }<file_sep>package com.javarush.task.task17.task1710; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; /* CRUD */ public class Solution { public static List<Person> allPeople = new ArrayList<Person>(); static { allPeople.add(Person.createMale("<NAME>", new Date())); //сегодня родился id=0 allPeople.add(Person.createMale("<NAME>", new Date())); //сегодня родился id=1 } public static void main(String[] args) throws Exception { //DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH); //Date birthDate = dateFormat.parse(args[3]); if (args[0].equals("-c")){ Date birthDate = setDate(args[3]); if (args[2].equals("м")) { allPeople.add(Person.createMale(args[1], birthDate)); System.out.println(allPeople.size()-1); } else if (args[2].equals("ж")) { allPeople.add(Person.createFemale(args[1], birthDate)); System.out.println(allPeople.size()-1); } } else if (args[0].equals("-u")){ Date birthDate = setDate(args[4]); if (args[3].equals("м")) allPeople.set(Integer.parseInt(args[1]), Person.createMale(args[2], birthDate)); else if (args[3].equals("ж")) allPeople.set(Integer.parseInt(args[1]), Person.createFemale(args[2], birthDate)); } else if (args[0].equals("-d")){ allPeople.set(Integer.parseInt(args[1]), Person.createMale(null, null)); allPeople.get(Integer.parseInt(args[1])).setSex(null); } else if (args[0].equals("-i")){ Person person = allPeople.get(Integer.parseInt(args[1])); System.out.println(person.getName() + " " + person.getSexStr() + " " + person.getDateStr()); } } public static Date setDate (String sDate) throws Exception { DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH); Date birthDate = dateFormat.parse(sDate); return birthDate; } } <file_sep>package com.javarush.task.task08.task0815; import java.util.HashMap; import java.util.HashSet; /* Перепись населения */ public class Solution { public static HashMap<String, String> createMap() { HashMap <String, String> map = new HashMap<String, String>(); map.put("Иванов", "Брюс"); map.put("Сидоров", "Владимир"); map.put("Зюганов", "Геннадий"); map.put("Путин", "Владимир"); map.put("Сталин", "Иосиф"); map.put("Чубайс", "Анатолий"); map.put("Путинов", "Николай"); map.put("Уиллис", "Брюс"); map.put("Путинидзе", "Брюс"); map.put("Мэнсон", "Мэрлин"); return map; } public static int getCountTheSameFirstName(HashMap<String, String> map, String name) { int sfn = 0; for (String mapname : map.values()){ if (mapname.equals(name)) sfn++; } return sfn; } public static int getCountTheSameLastName(HashMap<String, String> map, String lastName) { int sln = 0; for (String maplname : map.keySet()) { if (maplname.equals(lastName)) sln++; } return sln; } public static void main(String[] args) { } } <file_sep>package com.javarush.task.task01.task0132; /* Сумма цифр трехзначного числа */ public class Solution { public static void main(String[] args) { System.out.println(sumDigitsInNumber(546)); } public static int sumDigitsInNumber(int number) { int l = number % 10; int a = number / 10; int f = a % 10; int b = a / 10; int j = b % 10; return l + f + j; } }<file_sep>package com.javarush.task.task18.task1815; import java.util.List; /* Таблица */ public class Solution { public class TableInterfaceWrapper implements ATableInterface { ATableInterface original; String headertext; TableInterfaceWrapper(ATableInterface original){ this.original = original; } @Override public void setModel(List rows) { int counter = 0; for (Object row : rows) counter++; System.out.println(counter); original.setModel(rows); } @Override public String getHeaderText() { return original.getHeaderText().toUpperCase(); } @Override public void setHeaderText(String newHeaderText) { original.setHeaderText(newHeaderText); } } public interface ATableInterface { void setModel(List rows); String getHeaderText(); void setHeaderText(String newHeaderText); } public static void main(String[] args) { } }<file_sep>package com.javarush.task.task08.task0828; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.*; /* Номер месяца */ public class Solution { public static void main(String[] args) throws IOException { SimpleDateFormat month = new SimpleDateFormat("MMMM", Locale.ENGLISH); Date date = new Date(); ArrayList<String> list = new ArrayList<String>(); for (int i = 0; i < 12; i++){ date.setMonth(i); list.add(month.format(date)); } BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String inStr = reader.readLine(); for (int i = 0; i < 12; i++){ if (inStr.equals(list.get(i))) System.out.println(inStr + " is " + (i+1) + " month"); } } } <file_sep>package com.javarush.task.task33.task3310.strategy; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.FileAttribute; public class FileBucket { private Path path; public FileBucket() throws IOException { this.path = Files.createTempFile("", ""); Files.deleteIfExists(path); Files.createFile(path); File tmp = path.toFile(); tmp.deleteOnExit(); } public long getFileSize() { long size = 0; try { size = Files.size(path);; } catch (Exception e){ } return size; } public void putEntry(Entry entry){ try { OutputStream outputStream = Files.newOutputStream(path); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(entry); objectOutputStream.close(); outputStream.close(); } catch (Exception e){ } } public Entry getEntry() { Entry result = null; try { if (this.getFileSize() == 0) return null; InputStream inputStream = Files.newInputStream(path); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); result = (Entry) objectInputStream.readObject(); objectInputStream.close(); inputStream.close(); } catch (Exception e){ } return result; } public void remove() throws IOException { Files.delete(path); } } <file_sep>package com.javarush.task.task08.task0817; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.ArrayList; /* Нам повторы не нужны */ public class Solution { public static HashMap<String, String> createMap() { HashMap <String, String> map = new HashMap<String, String>(); map.put("Пупкин0", "Вася"); map.put("Пупкин1", "Вася1"); map.put("Пупкин2", "Вася"); map.put("Пупкин3", "Вася1"); map.put("Пупкин4", "Вася2"); map.put("Пупкин5", "Вася"); map.put("Пупкин6", "Вася1"); map.put("Пупкин7", "Вася33"); map.put("Пупкин8", "Вася"); map.put("Пупкин9", "Вася2"); return map; } public static void removeTheFirstNameDuplicates(HashMap<String, String> map) { ArrayList<String> list = new ArrayList<>(); for (Map.Entry<String, String> pair: map.entrySet()){ list.add(pair.getValue()); } int count = 0; for (int i = 0; i < list.size() ; i++) { for (int j = i + 1; j < list.size() ; j++) { if (list.get(i).equals(list.get(j))) count++; } if (count == 0){ list.remove(list.get(i)); i--; } else count = 0; } for (int i = 0; i < list.size(); i++) { removeItemFromMapByValue(map, list.get(i)); } } public static void removeItemFromMapByValue(HashMap<String, String> map, String value) { HashMap<String, String> copy = new HashMap<String, String>(map); for (Map.Entry<String, String> pair : copy.entrySet()) { if (pair.getValue().equals(value)) map.remove(pair.getKey()); } } public static void main(String[] args) { } } <file_sep>package com.javarush.task.task17.task1721; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /* Транзакционность */ public class Solution { public static List<String> allLines = new ArrayList<String>(); public static List<String> forRemoveLines = new ArrayList<String>(); public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String fileName1, fileName2; fileName1 = reader.readLine(); fileName2 = reader.readLine(); BufferedReader fileReader1 = new BufferedReader(new FileReader(fileName1)); BufferedReader fileReader2 = new BufferedReader(new FileReader(fileName2)); String str; while ((str = fileReader1.readLine()) != null){ allLines.add(str); } while ((str = fileReader2.readLine()) != null){ forRemoveLines.add(str); } Solution solution = new Solution(); solution.joinData(); for (String s : allLines) System.out.println(s); } public void joinData () throws CorruptedDataException { //ArrayList<Integer> strToRemove = new ArrayList<Integer>(); int counter = 0; for (int i = 0; i < forRemoveLines.size(); i++) if (allLines.contains(forRemoveLines.get(i))) counter++; //strToRemove.add(i); if (counter == forRemoveLines.size()) allLines.removeAll(forRemoveLines); /*if (strToRemove.size() == forRemoveLines.size()){ for (int i = 0; i < strToRemove.size(); i++) allLines.remove(strToRemove.get(i)); }*/ else { allLines.removeAll(allLines); throw new CorruptedDataException(); } } } <file_sep>package com.javarush.task.task08.task0824; /* Собираем семейство */ import java.util.ArrayList; public class Solution { public static void main(String[] args) { ArrayList <Human> family = new ArrayList<Human>(); ArrayList <Human> mother_child = new ArrayList<Human>(); ArrayList <Human> father_child = new ArrayList<Human>(); ArrayList <Human> children = new ArrayList<Human>(); Human child1 = new Human("Олег", true, 15); family.add(child1); Human child2 = new Human("Мария", false, 16); family.add(child2); Human child3 = new Human("Степан", true, 12); family.add(child3); children.add(child1); children.add(child2); children.add(child3); Human father = new Human("Георгий", true, 35, children); family.add(father); Human mother = new Human("Ольга", false, 30, children); family.add(mother); mother_child.add(mother); father_child.add(father); Human grandfather1 = new Human("Василий", true, 70, mother_child); family.add(grandfather1); Human grandmother1 = new Human("Елена", false, 65, mother_child); family.add(grandmother1); Human grandfather2 = new Human("Михаил", true, 71, father_child); family.add(grandfather2); Human grandmother2 = new Human("Жанна", false, 64, father_child); family.add(grandmother2); for (int i = 0; i < family.size(); i++){ System.out.println(family.get(i).toString()); } } public static class Human { public String name; public boolean sex; public int age; public ArrayList<Human> children; public Human(String name, boolean sex, int age){ this.name = name; this.sex = sex; this.age = age; } public Human(String name, boolean sex, int age, ArrayList<Human> children){ this.name = name; this.sex = sex; this.age = age; this.children = children; } public String toString() { String text = ""; text += "Имя: " + this.name; text += ", пол: " + (this.sex ? "мужской" : "женский"); text += ", возраст: " + this.age; /*int childCount = this.children.size(); if (childCount > 0) { text += ", дети: " + this.children.get(0).name; for (int i = 1; i < childCount; i++) { Human child = this.children.get(i); text += ", " + child.name; } }*/ return text; } } } <file_sep>package com.javarush.task.task18.task1823; import java.io.*; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /* Нити и байты */ public class Solution { public static Map<String, Integer> resultMap = new HashMap<String, Integer>(); public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true){ String fileName = reader.readLine(); if (fileName.equals("exit")) break; new ReadThread(fileName).start(); } for (Map.Entry<String, Integer> pair : resultMap.entrySet()) System.out.println(pair.getKey() + " " + pair.getValue()); } public static class ReadThread extends Thread { String filename; public ReadThread(String fileName){ //implement constructor body this.filename = fileName; } // implement file reading here - реализуйте чтение из файла тут public void run() { try { FileInputStream fileInputStream = new FileInputStream(filename); byte [] data = new byte[fileInputStream.available()]; fileInputStream.read(data); int max = 0; int maxbyte = 0; for (int i = 0; i < data.length; i++){ int counter = 0; for (int j = 0; j < data.length; j++){ if (data[i] == data[j]) counter++; } if (counter > max){ max = counter; maxbyte = data[i]; } } resultMap.put(filename, maxbyte); fileInputStream.close(); } catch (FileNotFoundException e){ System.out.println("File not found"); } catch (Exception e){ System.out.println(e); } //System.out.println(currentThread() + " " + filename); } } } <file_sep>package com.javarush.task.task18.task1817; /* Пробелы */ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class Solution { public static void main(String[] args) throws FileNotFoundException, IOException { FileInputStream fileInputStream = new FileInputStream(args[0]); int ch = 0; int sp = 0; while (fileInputStream.available() > 0){ int data = fileInputStream.read(); ch++; if (data == 32) sp++; } fileInputStream.close(); System.out.printf("%.2f", (double) sp/ch *100); } } <file_sep>package com.javarush.task.task04.task0417; /* Существует ли пара? */ import java.io.*; public class Solution { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String snumber1 = reader.readLine(); int number1 = Integer.parseInt(snumber1); String snummber2 = reader.readLine(); int number2 = Integer.parseInt(snummber2); String snumber3 = reader.readLine(); int number3 = Integer.parseInt(snumber3); pair(number1, number2, number3); } public static void pair(int number1, int number2, int number3){ if ( number1 == number2 && number2 == number3) System.out.println(number1 + " " + number2 + " " + number3); else if (number1 == number2) System.out.println(number1 + " " + number2); else if (number1 == number3) System.out.println(number1 + " " + number3); else if (number2 == number3) System.out.println(number2 + " " + number3); } }<file_sep>package com.javarush.task.task04.task0420; /* Сортировка трех чисел */ import java.io.*; public class Solution { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = 3; String [] snumbers = new String[n]; int [] numbers = new int[n]; for (int i = 0; i < n; i++) { snumbers [i] = reader.readLine(); numbers [i] = Integer.parseInt(snumbers[i]); } for (int i = 0; i < n; i++){ int max = i; for (int j = i+1; j < n ; j++){ if (numbers[j] > numbers[max]) max = j; } if (max != i){ int buf = numbers[max]; numbers[max] = numbers[i]; numbers[i] = buf; } } for (int i = 0; i < n; i++){ System.out.print(numbers[i] + " "); } } } <file_sep>package com.javarush.task.task19.task1908; /* Выделяем числа */ import java.io.*; import java.util.regex.*; public class Solution { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedReader fileReader = new BufferedReader(new FileReader(reader.readLine())); BufferedWriter fileWriter = new BufferedWriter(new FileWriter(reader.readLine())); reader.close(); String text = ""; while (fileReader.ready()){ text += (char) fileReader.read(); } fileReader.close(); Pattern p = Pattern.compile("\\s\\d+\\s|\\d\\d+\\s|\\s\\d+"); Matcher m = p.matcher(text); String number = ""; String s = ""; while (m.find()){ number = (text.substring(m.start(), m.end())); number = number.replaceAll(" ", ""); //System.out.print(number + " "); fileWriter.write(number + " "); } fileWriter.close(); } } <file_sep>package com.javarush.task.task14.task1413; /** * Created by at on 11.10.2017. */ class Monitor implements CompItem { public String getName(){return "Monitor";} } <file_sep>package com.javarush.task.task30.task3001; import java.math.BigInteger; /* Конвертер систем счислений */ public class Solution { public static void main(String[] args) { Number number = new Number(NumerationSystemType._10, "6"); Number result = convertNumberToOtherNumerationSystem(number, NumerationSystemType._2); System.out.println(result); //expected 110 number = new Number(NumerationSystemType._16, "6df"); result = convertNumberToOtherNumerationSystem(number, NumerationSystemType._8); System.out.println(result); //expected 3337 number = new Number(NumerationSystemType._16, "abcdefabcdef"); result = convertNumberToOtherNumerationSystem(number, NumerationSystemType._16); System.out.println(result); //expected abcdefabcdef } public static Number convertNumberToOtherNumerationSystem(Number number, NumerationSystem expectedNumerationSystem) throws NumberFormatException { String sResult = null; int expectedRadix = expectedNumerationSystem.getNumerationSystemIntValue(); int defaultRadix = number.getNumerationSystem().getNumerationSystemIntValue(); // Integer n = Integer.valueOf(number.getDigit(), defaultRadix); // sResult = Integer.toString(n, expectedRadix); BigInteger bi = new BigInteger(number.getDigit(), defaultRadix); sResult = bi.toString(expectedRadix); return new Number(expectedNumerationSystem, sResult); } } <file_sep>package com.javarush.task.task31.task3106; import java.io.*; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /* Разархивируем файл */ public class Solution { public static void main(String[] args) throws Exception { String resultFileName = args[0]; String[] fileNames = new String[args.length-1]; for (int i = 1; i < args.length; i++){ fileNames [i-1] = args[i]; } Arrays.sort(fileNames); Vector<InputStream> vectorFileNames = new Vector<InputStream>(); for (int i = 0; i < fileNames.length; i++){ vectorFileNames.add(new FileInputStream(fileNames[i])); } Enumeration <InputStream> files = vectorFileNames.elements(); ZipInputStream zipInputStream = new ZipInputStream(new SequenceInputStream(files)); ZipEntry zipEntry = zipInputStream.getNextEntry(); FileOutputStream fileOutputStream = new FileOutputStream(resultFileName); copyData(zipInputStream, fileOutputStream); zipInputStream.close(); fileOutputStream.close(); } private static void copyData(InputStream in, OutputStream out) throws Exception { byte[] buffer = new byte[8 * 1024]; int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } } <file_sep>package com.javarush.task.task10.task1013; /* Конструкторы класса Human */ public class Solution { public static void main(String[] args) { } public static class Human { private String name; private int age; private boolean sex; private String address; private boolean education; private int children; public Human (String name){ this.name = name; } public Human (String name, int age){ this.name = name; this.age = age; } public Human (String name, int age, boolean sex){ this.name = name; this.age = age; this.sex = sex; } public Human (String name, int age, boolean sex, String address){ this.name = name; this.age = age; this.sex = sex; this.address = address; } public Human (String name, int age, boolean sex, String address, boolean education){ this.name = name; this.age = age; this.sex = sex; this.address = address; this.education = education; } public Human (String name, int age, boolean sex, String address, boolean education, int children){ this.name = name; this.age = age; this.sex = sex; this.address = address; this.education = education; this.children = children; } public Human (String name, int age, boolean sex, String address, int children){ this.name = name; this.age = age; this.sex = sex; this.address = address; this. children = children; } public Human (String name, int age, boolean sex, int children){ this.name = name; this.age = age; this.sex = sex; this.children = children; } public Human (String name, int age, String address){ this.name = name; this.age = age; this.address = address; } public Human (String name, boolean education){ this.name = name; this.education = education; } } } <file_sep>package com.javarush.task.task26.task2613; import com.javarush.task.task26.task2613.exception.NotEnoughMoneyException; import java.util.*; public class CurrencyManipulator { private String currencyCode; // номинал - количество доступных купюр (англ. denomination - купюра) private Map<Integer, Integer> denominations = new HashMap<>(); public CurrencyManipulator(String currencyCode) { this.currencyCode = currencyCode; } public String getCurrencyCode() { return currencyCode; } public void addAmount(int detonation, int count){ if (denominations.containsKey(detonation)) { count = denominations.get(detonation) + count; } denominations.put(detonation, count); } public int getTotalAmount(){ int totalAmount = 0; for (Map.Entry<Integer, Integer> entry : denominations.entrySet()){ totalAmount += entry.getKey() * entry.getValue(); } return totalAmount; } public boolean hasMoney(){ if (getTotalAmount() == 0) return false; return true; } public boolean isAmountAvailable(int expectedAmount){ if (getTotalAmount() < expectedAmount) return false; return true; } public boolean isDenominationsAvailable(int expectedAmount, Map<Integer, Integer> denominationsCopy){ Map<Integer, Integer> localCopy = new HashMap<>(denominationsCopy); for (Map.Entry<Integer, Integer> entry : localCopy.entrySet()){ if (entry.getKey() <= expectedAmount && entry.getValue() > 0) { expectedAmount -= entry.getKey(); entry.setValue(entry.getValue() - 1); } if (expectedAmount == 0) return true; } return false; } public Map<Integer, Integer> withdrawAmount(int expectedAmount) throws NotEnoughMoneyException { //test start // System.out.println("Перед выдачей в банкомате: " + denominations); // test end Map <Integer, Integer> denominationsCopy = new HashMap<>(denominations); if (!isDenominationsAvailable(expectedAmount, denominationsCopy)) throw new NotEnoughMoneyException(); Map<Integer, Integer> result = new HashMap<>(); TreeSet<Map.Entry<Integer, Integer>> denominationSortedSet = new TreeSet<>((entry1, entry2) -> { if (entry1.getKey() > entry2.getKey()) return -1; else if (entry1.getKey() < entry2.getKey()) return 1; else return 0; }); denominationSortedSet.addAll(denominationsCopy.entrySet()); while (expectedAmount > 0) { try { Map.Entry<Integer, Integer> currentEntry = getCurrentEntry(denominationSortedSet, expectedAmount); int moneyInCurrentEntry = currentEntry.getKey() * currentEntry.getValue(); while (expectedAmount > 0 && moneyInCurrentEntry > 0 && currentEntry.getKey() <= expectedAmount) { if (result.containsKey(currentEntry.getKey())) { Integer v = result.get(currentEntry.getKey()) + 1; result.put(currentEntry.getKey(), v); } else { result.put(currentEntry.getKey(), 1); } moneyInCurrentEntry -= currentEntry.getKey(); expectedAmount -= currentEntry.getKey(); currentEntry.setValue(currentEntry.getValue() - 1); } if (moneyInCurrentEntry > 0) denominationSortedSet.add(currentEntry); } catch (NullPointerException e){ throw new NotEnoughMoneyException(); } } denominationsCopy.clear(); for (Map.Entry<Integer, Integer> currentEntry : denominationSortedSet){ denominationsCopy.put(currentEntry.getKey(), currentEntry.getValue()); } denominations = new HashMap<>(denominationsCopy); //test start // System.out.println("В банкомате осталось: " + denominations); // test end return result; } private Map.Entry<Integer, Integer> getCurrentEntry (TreeSet<Map.Entry<Integer, Integer>> denominationSortedSet, int expectedAmount){ Map.Entry<Integer, Integer> result = null; for (Map.Entry<Integer, Integer> currentEntry : denominationSortedSet){ if (currentEntry.getKey() <= expectedAmount) { result = currentEntry; denominationSortedSet.remove(currentEntry); break; } } return result; } } <file_sep>package com.javarush.task.task37.task3707; import java.io.*; import java.util.*; public class AmigoSet <E> extends AbstractSet implements Serializable, Cloneable, Set { public static void main(String[] args) throws IOException, ClassNotFoundException { AmigoSet <Integer> mySet = new AmigoSet<>(); mySet.add(1); mySet.add(2); ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("D://data.dat")); objectOutputStream.writeObject(mySet); objectOutputStream.close(); ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("D://data.dat")); AmigoSet <Integer> myUnserializedSet = (AmigoSet<Integer>) objectInputStream.readObject(); objectInputStream.close(); System.out.println(mySet.equals(myUnserializedSet)); } private static final Object PRESENT = new Object(); private transient HashMap<E, Object> map; public AmigoSet() { map = new HashMap<>(); } public AmigoSet(Collection<? extends E> collection){ int capacity = Math.max(16,(int)Math.ceil(collection.size()/.75f)); map = new HashMap<>(capacity); for (Object o : collection){ E element = (E) o; map.put(element, PRESENT); } } @Override public Iterator iterator() { return map.keySet().iterator(); } @Override public boolean isEmpty() { return map.isEmpty(); } @Override public boolean contains(Object o) { return map.containsKey(o); } @Override public Object[] toArray() { return super.toArray(); } @Override public Object[] toArray(Object[] a) { return super.toArray(a); } @Override public boolean add(Object o) { return map.put((E) o, PRESENT) == null; } @Override public boolean remove(Object o) { return map.remove(o) == null; } @Override public boolean containsAll(Collection c) { return super.containsAll(c); } @Override public boolean addAll(Collection c) { return super.addAll(c); } @Override public boolean retainAll(Collection c) { return super.retainAll(c); } @Override public void clear() { map.clear(); } @Override public String toString() { return super.toString(); } @Override public int size() { return map.size(); } @Override public Object clone() { try { AmigoSet amigoSet = (AmigoSet) super.clone(); amigoSet.map = (HashMap) map.clone(); return amigoSet; } catch (Exception e){ throw new InternalError(); } } private void writeObject(ObjectOutputStream oos) throws IOException { int capacity = HashMapReflectionHelper.callHiddenMethod(map, "capacity"); float loadFactor = HashMapReflectionHelper.callHiddenMethod(map, "loadFactor"); Set<E> set = new HashSet<>(); for (Map.Entry <E, Object> entry : map.entrySet()) set.add(entry.getKey()); oos.defaultWriteObject(); oos.writeObject(set); oos.writeInt(capacity); oos.writeFloat(loadFactor); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); Set<E> set = (Set<E>) ois.readObject(); int capacity = ois.readInt(); float loadFactor = ois.readFloat(); this.map = new HashMap(capacity, loadFactor); for (E object : set){ map.put(object, PRESENT); } } } <file_sep>package com.javarush.task.task13.task1320; /* Neo */ public class Solution { } <file_sep>package com.javarush.task.task18.task1821; /* Встречаемость символов */ import java.io.*; import java.util.Arrays; public class Solution { public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader reader = new BufferedReader(new FileReader(args[0])); FileInputStream fileInputStream = new FileInputStream(args[0]); char [] symbols = new char[fileInputStream.available()]; reader.read(symbols); Arrays.sort(symbols); int [] freq = new int [symbols.length]; for (int i = 0; i < symbols.length; i++){ for (int j = 0; j < symbols.length; j++){ if (symbols[i] == symbols [j]) freq[i] ++; } } reader.close(); fileInputStream.close(); int printed = 0; for (int i = 0; i < symbols.length; i++){ if (symbols[i] != printed) { System.out.print(symbols[i] + " " + freq[i]); System.out.println(); } printed = symbols[i]; } } } <file_sep>package com.javarush.task.task32.task3201; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.RandomAccess; /* Запись в существующий файл */ //public class Solution { // public static void main(String... args) throws IOException { // RandomAccessFile raf = new RandomAccessFile(args[0], "rw"); // // if (raf.length() < args[2].length()) { // //raf.setLength(args[2].length()); // raf.seek(raf.length()-1); // } // else // raf.seek(Long.parseLong(args[1])); // // byte [] bytes = args[2].getBytes(); // // raf.write(bytes); // // raf.close(); // } //} public class Solution { public static void main(String... args) throws IOException { String fileName = args[0]; long position = Integer.parseInt(args[1]); String text = args[2]; RandomAccessFile file = new RandomAccessFile(fileName, "rw"); position = position > file.length() ? file.length() : position; file.seek(position); file.write(text.getBytes()); file.close(); } } <file_sep>package com.javarush.task.task38.task3802; /* Проверяемые исключения (checked exception) */ import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.nio.file.Path; import java.nio.file.Paths; public class VeryComplexClass { public void veryComplexMethod() throws Exception { File file = new File("asdasdasd"); BufferedReader reader = new BufferedReader(new FileReader(file)); //928 754 564 6146 } public static void main(String[] args) { // VeryComplexClass veryComplexClass = new VeryComplexClass(); // veryComplexClass.veryComplexMethod(); } } <file_sep>package com.javarush.task.task26.task2613.command; import com.javarush.task.task26.task2613.CashMachine; import com.javarush.task.task26.task2613.ConsoleHelper; import com.javarush.task.task26.task2613.exception.InterruptOperationException; import java.io.File; import java.util.Locale; import java.util.ResourceBundle; public class LoginCommand implements Command { private ResourceBundle validCreditCards = ResourceBundle.getBundle(CashMachine.class.getPackage().getName()+".resources.verifiedCards"); private ResourceBundle res = ResourceBundle.getBundle(CashMachine.RESOURCE_PATH + "login_en"); @Override public void execute() throws InterruptOperationException { String enteredCardNumber = "", enteredPin = ""; ConsoleHelper.writeMessage(res.getString("before")); ConsoleHelper.writeMessage(res.getString("specify.data")); while (true){ enteredCardNumber = ConsoleHelper.readString(); enteredPin = ConsoleHelper.readString(); if (enteredCardNumber.length() != 12 && enteredPin.length() != 4){ ConsoleHelper.writeMessage(res.getString("try.again.with.details")); continue; } int c = 0; for (int i = 0; i < enteredCardNumber.length(); i++) if (Character.isDigit(enteredCardNumber.charAt(i))) c++; for (int i = 0; i < enteredPin.length(); i++) if (Character.isDigit(enteredPin.charAt(i))) c++; if (c != 16){ ConsoleHelper.writeMessage(String.format(res.getString("not.verified.format"), enteredCardNumber)); ConsoleHelper.writeMessage(res.getString("try.again.or.exit")); continue; } if (validCreditCards.containsKey(enteredCardNumber) && validCreditCards.getString(enteredCardNumber).equalsIgnoreCase(enteredPin)) { ConsoleHelper.writeMessage(String.format(res.getString("success.format"), enteredCardNumber)); break; } else ConsoleHelper.writeMessage(String.format(res.getString("not.verified.format"), enteredCardNumber)); } } } <file_sep>package com.javarush.task.task15.task1527; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /* <NAME> */ public class Solution { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String url = reader.readLine(); String [] strings = url.split("[\\?\\&]"); String [] par = new String [2]; for (int i = 1; i < strings.length; i++){ if (strings[i].contains("=")) { par = strings[i].split("\\="); System.out.print(par[0] + " "); } else System.out.print(strings[i] + " "); } System.out.println(); for (String str : strings) if (str.contains("obj")) { par = str.split("\\="); try { alert(Double.parseDouble(par[1])); } catch (Exception e){ alert(par[1]); } } } public static void alert(double value) { System.out.println("double " + value); } public static void alert(String value) { System.out.println("String " + value); } } <file_sep>package com.javarush.task.task05.task0532; import java.io.*; /* Задача по алгоритмам */ public class Solution { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int arrlength = Integer.parseInt(reader.readLine()); int [] array = new int [arrlength]; for (int i = 0; i < arrlength; i++) array[i] = Integer.parseInt(reader.readLine()); int maximum = array[0]; for (int i = 0; i < arrlength; i++){ if (array[i] > maximum) maximum = array[i]; } System.out.println(maximum); } } <file_sep>package com.javarush.task.task28.task2810; import com.javarush.task.task28.task2810.model.HHStrategy; import com.javarush.task.task28.task2810.model.Model; import com.javarush.task.task28.task2810.model.MoikrugStrategy; import com.javarush.task.task28.task2810.model.Provider; import com.javarush.task.task28.task2810.view.HtmlView; public class Aggregator { public static void main(String[] args) { // HtmlView htmlView = new HtmlView(); // Provider HHProvider = new Provider(new HHStrategy()); // Provider moikrugProvider = new Provider(new MoikrugStrategy()); //// Model model = new Model(htmlView, moikrugProvider, HHProvider); // Model model = new Model(htmlView, HHProvider); // Controller controller = new Controller(model); // htmlView.setController(controller); // htmlView.userCitySelectEmulationMethod(); // System.out.println(""); int i = 5; int b = 10; String s = "12"; String a = i + b + s; printIBS(i, b, s); System.out.println(a); } private static void printIBS(int i, int b, String s) { System.out.println(i); System.out.println(b); System.out.println(s); } } <file_sep>package com.javarush.task.task08.task0823; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /* <NAME> */ public class Solution { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String s = reader.readLine(); String [] words = s.split("\\b"); String [] words1 = new String[words.length]; for (int i = 0; i < words.length; i++){ char [] word = words[i].toCharArray(); word[0] = Character.toUpperCase(word[0]); words1[i] = ""; for (int j = 0; j < word.length; j++){ words1[i] = words1[i] + word[j]; } } for (int i = 0; i < words.length; i++) { words[i] = words1[i]; System.out.print(words[i] + " "); } } } <file_sep>package com.javarush.task.task33.task3304; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; /* Конвертация из одного класса в другой используя JSON */ public class Solution { public static void main(String[] args) throws IOException { Second s = (Second) convertOneToAnother(new First(), Second.class); First f = (First) convertOneToAnother(new Second(), First.class); // First firts = new First(); // firts.i = 1; // firts.name = "vasya"; // System.out.println(firts.getClass().getSimpleName() + " " + firts.i + " " + firts.name); // // Second s = (Second) convertOneToAnother(firts, Second.class); // System.out.println(s.getClass().getSimpleName() + " " + s.i + " " + s.name); // // Second second = new Second(); // second.i = 2; // second.name = "petya"; // System.out.println(second.getClass().getSimpleName() + " " + second.i + " " + second.name); // // First f = (First) convertOneToAnother(second, First.class); // System.out.println(f.getClass().getSimpleName() + " " + f.i + " " + f.name); } public static Object convertOneToAnother(Object one, Class resultClassObject) throws IOException { ObjectMapper mapper = new ObjectMapper(); StringWriter stringWriter = new StringWriter(); mapper.writeValue(stringWriter, one); System.out.println(stringWriter.toString()); String clazzName = resultClassObject.getSimpleName().toLowerCase(); String jsonStr = stringWriter.toString().replaceFirst("\":\"[a-z]+", "\":\"" + clazzName); System.out.println(jsonStr); StringReader stringReader = new StringReader(jsonStr); Object o = mapper.readValue(jsonStr, resultClassObject); return o; } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property="className") @JsonSubTypes(@JsonSubTypes.Type(value=First.class, name="first")) public static class First { public int i; public String name; } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property="className") @JsonSubTypes(@JsonSubTypes.Type(value=Second.class, name="second")) public static class Second { public int i; public String name; } } <file_sep>package com.javarush.task.task27.task2712.ad; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; public class StatisticAdvertisementManager { static StatisticAdvertisementManager instance = new StatisticAdvertisementManager(); AdvertisementStorage advertisementStorage = AdvertisementStorage.getInstance(); private StatisticAdvertisementManager() {} public static StatisticAdvertisementManager getInstance() { return instance; } public List<Advertisement> getActiveVideos(){ return advertisementStorage.list().stream().filter(advertisement -> advertisement.getHits() > 0).collect(Collectors.toList()); } public List<Advertisement> getArchivedVideos(){ return advertisementStorage.list().stream().filter(advertisement -> advertisement.getHits() == 0).collect(Collectors.toList()); } } <file_sep>package com.javarush.task.task30.task3005; import java.util.ArrayList; import java.util.List; /* Такие хитрые исключения! */ public class Solution { public static void main(String[] args){ boolean a = true; boolean b = false; boolean c = true; boolean d = false; int result = 0; if (a) result += 1; //1 == 20 — нулевой бит if (b) result += 2; //2 == 21 — первый бит if (c) result+= 4; //4 == 22 — второй бит if (d) result+= 8; //8 == 23 — третий бит } }<file_sep>package com.javarush.task.task38.task3804; public class ExceptionFabric { public static Throwable getException(Enum enumm){ if (enumm == null) return new IllegalArgumentException(); String message = enumm.toString().replaceAll("_", " ").toLowerCase() .replaceFirst("[a-z]", String.valueOf(enumm.toString().charAt(0)).toUpperCase()); if (enumm instanceof ExceptionApplicationMessage) { return new Exception(message); } else if (enumm instanceof ExceptionDBMessage) return new RuntimeException(message); else if (enumm instanceof ExceptionUserMessage) return new Error(message); else return new IllegalArgumentException(); } } <file_sep>package com.javarush.task.task19.task1920; /* Самый богатый */ public class Solution { public static void main(String[] args) { String string; } } <file_sep>package com.javarush.task.task18.task1816; /* Английские буквы */ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class Solution { public static void main(String[] args) throws FileNotFoundException, IOException { FileInputStream fileInputStream = new FileInputStream(args[0]); int counter = 0; while (fileInputStream.available() > 0){ int ch = fileInputStream.read(); if (ch > 64 && ch < 91 || ch > 96 && ch < 123) counter++; } fileInputStream.close(); System.out.println(counter); } } <file_sep>package com.javarush.task.task09.task0902; /* И снова StackTrace */ public class Solution { public static void main(String[] args) throws Exception { method1(); } public static String method1() { method2(); StackTraceElement[] stackTraceElement = Thread.currentThread().getStackTrace(); String methodName = ""; int c = 0; for (StackTraceElement element : stackTraceElement){ if (c == 2) methodName = element.getMethodName(); c++; } return methodName; } public static String method2() { method3(); StackTraceElement[] stackTraceElement = Thread.currentThread().getStackTrace(); String methodName = ""; int c = 0; for (StackTraceElement element : stackTraceElement){ if (c == 2) methodName = element.getMethodName(); c++; } return methodName; } public static String method3() { method4(); StackTraceElement[] stackTraceElement = Thread.currentThread().getStackTrace(); String methodName = ""; int c = 0; for (StackTraceElement element : stackTraceElement){ if (c == 2) methodName = element.getMethodName(); c++; } return methodName; } public static String method4() { method5(); StackTraceElement[] stackTraceElement = Thread.currentThread().getStackTrace(); String methodName = ""; int c = 0; for (StackTraceElement element : stackTraceElement){ if (c == 2) methodName = element.getMethodName(); c++; } return methodName; } public static String method5() { StackTraceElement[] stackTraceElement = Thread.currentThread().getStackTrace(); String methodName = ""; int c = 0; for (StackTraceElement element : stackTraceElement){ if (c == 2) methodName = element.getMethodName(); c++; } return methodName; } } <file_sep>package com.javarush.task.task40.task4009; import javax.swing.text.DateFormatter; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.Year; import java.time.format.DateTimeFormatter; import java.time.format.TextStyle; import java.util.Locale; /* Buon Compleanno! */ public class Solution { public static void main(String[] args) { System.out.println(weekDayOfBirthday("1.12.2015", "2016")); } public static String weekDayOfBirthday(String birthday, String year) { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("d.M.yyyy", Locale.ITALIAN); Year yearr = Year.parse("1999"); String sDate = birthday.substring(0, birthday.length()-4) + year; LocalDate localDate = LocalDate.parse(sDate, dateTimeFormatter); return DayOfWeek.of(localDate.getDayOfWeek().getValue()).getDisplayName(TextStyle.FULL, Locale.ITALIAN); } } <file_sep>package com.javarush.task.task08.task0812; import java.io.*; import java.util.ArrayList; /* Cамая длинная последовательность */ public class Solution { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); ArrayList <Integer> numbers = new ArrayList<Integer>(); for (int i = 0; i < 10; i++){ String s = reader.readLine(); numbers.add(Integer.parseInt(s)); } int c = 1; int k; for (int i = 0; i < numbers.size(); i++){ int n = numbers.get(i); k = 1; for (int j = i+1; j < numbers.size(); j++){ if (numbers.get(j) == n) k++; else break; } if (k > c) c = k; } System.out.println(c); } }<file_sep>package com.javarush.task.task32.task3204; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Random; /* <NAME> */ public class Solution { public static void main(String[] args) throws IOException { ByteArrayOutputStream password = getPassword(); System.out.println(password.toString()); } public static ByteArrayOutputStream getPassword() throws IOException { String result = ""; Random random = new Random(); while (true) { boolean hasDigit = false, hasSmallLetter = false, hasBigLetter = false; for (int i = 0; i < 8; i++) { int type = 1 + random.nextInt(3); if (type == 1) { result += String.valueOf(random.nextInt(9)); hasDigit = true; } else if (type == 2) { result += String.valueOf((char) (65 + random.nextInt(25))); hasBigLetter = true; } else { result += String.valueOf((char) (97 + random.nextInt(25))); hasSmallLetter = true; } } if (hasDigit && hasSmallLetter && hasBigLetter){ break; } else result = ""; } ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byteArrayOutputStream.write(result.getBytes()); return byteArrayOutputStream; } }<file_sep>package com.javarush.task.task07.task0724; /* Семейная перепись */ import java.util.ArrayList; public class Solution { public static void main(String[] args) { ArrayList <Human> family = new ArrayList<Human>(); Human grandfather1 = new Human("Michael", true, 75); family.add(grandfather1); Human grandmother1 = new Human ("Sarah", false, 70); family.add(grandmother1); Human grandfather2 = new Human("Sam", true, 76); family.add(grandfather2); Human grandmother2 = new Human ("Miranda", false, 71); family.add(grandmother2); Human father = new Human ("Joe", true, 45, grandmother1, grandfather1); family.add(father); Human mother = new Human ("Helen", false, 35, grandmother2, grandfather2); family.add(mother); Human child1 = new Human ("Vasya", true, 15, mother, father); family.add(child1); Human child2 = new Human ("Veronika", false, 14, mother, father); family.add(child2); Human child3 = new Human ("Hannah", false, 13, mother, father); family.add(child3); for (int i = 0; i < family.size(); i++){ System.out.println(family.get(i).toString()); } } public static class Human { public String name; public boolean sex; public int age; public Human father; public Human mother; public Human (String name, boolean sex, int age){ this.name = name; this.sex = sex; this.age = age; } public Human (String name, boolean sex, int age, Human mothet, Human father){ this.name = name; this.sex = sex; this.age = age; this.mother = mothet; this.father = father; } public String toString() { String text = ""; text += "Имя: " + this.name; text += ", пол: " + (this.sex ? "мужской" : "женский"); text += ", возраст: " + this.age; if (this.father != null) text += ", отец: " + this.father.name; if (this.mother != null) text += ", мать: " + this.mother.name; return text; } } } <file_sep>package com.javarush.task.task39.task3904; import java.util.Arrays; /* Лестница */ public class Solution { private static int n = 70; public static void main(String[] args) { } } <file_sep>package com.javarush.task.task27.task2712.kitchen; import com.javarush.task.task27.task2712.Tablet; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class TestOrder extends Order { public TestOrder(Tablet tablet) throws IOException { super(tablet); } @Override protected void initDishes() throws IOException { super.dishes = new ArrayList<>(); int count = (int ) (Math.random() * 10); for (int i = 0; i < count; i++){ int randomDish = (int) (Math.random() * 4); dishes.add(Dish.values()[randomDish]); } } @Override public List<Dish> getDishes() { return super.getDishes(); } @Override public int getTotalCookingTime() { return super.getTotalCookingTime(); } @Override public boolean isEmpty() { return super.isEmpty(); } @Override public String toString() { return super.toString(); } } <file_sep>package com.javarush.task.task26.task2613.command; import com.javarush.task.task26.task2613.ConsoleHelper; import com.javarush.task.task26.task2613.CurrencyManipulator; import com.javarush.task.task26.task2613.CurrencyManipulatorFactory; import com.javarush.task.task26.task2613.exception.InterruptOperationException; import com.javarush.task.task26.task2613.exception.NotEnoughMoneyException; import java.util.Map; class WithdrawCommand implements Command { @Override public void execute() throws InterruptOperationException { String currencyCode = ConsoleHelper.askCurrencyCode(); CurrencyManipulator manipulator = CurrencyManipulatorFactory.getManipulatorByCurrencyCode(currencyCode); while (true){ ConsoleHelper.writeMessage("Введите желаемую сумму:"); try { int amount = Integer.parseInt(ConsoleHelper.readString()); if (!manipulator.isAmountAvailable(amount)) throw new NotEnoughMoneyException(); else { Map<Integer, Integer> withdraw = manipulator.withdrawAmount(amount); for (Map.Entry entry : withdraw.entrySet()) ConsoleHelper.writeMessage("\t" + entry.getKey() + " - " + entry.getValue()); ConsoleHelper.writeMessage("Транзакция проведена успешно"); break; } } catch (NumberFormatException e){ ConsoleHelper.writeMessage("Введена некорректная сумма."); } catch (NotEnoughMoneyException e){ ConsoleHelper.writeMessage("В банкомате не хватает банкнот"); } } } } <file_sep>package com.javarush.task.task39.task3909; /* Одно изменение */ public class Solution { public static void main(String[] args) { System.out.println(isOneEditAway("Вdася", "Васяj")); } public static boolean isOneEditAway(String first, String second) { if (first.equals(second)) return true; String longWord = ""; String shortWord = ""; if (first.length() >= second.length()) { longWord = first; shortWord = second; } else { longWord = second; shortWord = first; } int differents = 0; int c = 0; for (int i = 0; i < shortWord.length(); i++){ if (shortWord.charAt(i) != longWord.charAt(i)) { differents++; break; } c++; } c = longWord.length()-1 - c; for (int i = 0; i < c; i++){ if (longWord.charAt(longWord.length()-1-i) != shortWord.charAt(shortWord.length()-1-i)) { differents++; break; } } if (differents > 1) return false; return true; } } <file_sep>package com.javarush.task.task15.task1529; /** * Created by at on 18.10.2017. */ public class Plane implements Flyable { public int passengers; public Plane(int passengers){ this.passengers = passengers; } public void fly(){ } } <file_sep>package com.javarush.task.task08.task0820; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /* Множество всех животных */ public class Solution { public static void main(String[] args) { Set<Cat> cats = createCats(); Set<Dog> dogs = createDogs(); Set<Object> pets = join(cats, dogs); printPets(pets); removeCats(pets, cats); printPets(pets); } public static Set<Cat> createCats() { HashSet<Cat> result = new HashSet<Cat>(); Cat murzik = new Cat(); Cat vaska = new Cat(); Cat petr = new Cat(); Cat boris = new Cat(); result.add(murzik); result.add(vaska); result.add(petr); result.add(boris); return result; } public static Set<Dog> createDogs() { HashSet<Dog> result = new HashSet<Dog>(); Dog bobik = new Dog(); Dog patrick = new Dog(); Dog muhtar = new Dog(); result.add(bobik); result.add(patrick); result.add(muhtar); return result; } public static Set<Object> join(Set<Cat> cats, Set<Dog> dogs) { Set<Object> pets = new HashSet(); for (Object pet : cats) pets.add(pet); for (Object pet : dogs) pets.add(pet); return pets; } public static void removeCats(Set<Object> pets, Set<Cat> cats) { Iterator iterator = pets.iterator(); while (iterator.hasNext()){ Object pet = iterator.next(); for (Object cat : cats) if (pet.equals(cat)) iterator.remove(); } /*for (Object pet : pets){ for (Object cat : cats){ if (pet.equals(cat)) pets.remove(pet); } }*/ } public static void printPets(Set<Object> pets) { for (Object pet : pets) System.out.println(pet); } public static class Cat{ } public static class Dog{ } } <file_sep>package com.javarush.task.task17.task1711; import java.util.Date; public class Person { private String name; private Sex sex; private Date birthDay; private Person(String name, Sex sex, Date birthDay) { this.name = name; this.sex = sex; this.birthDay = birthDay; } public static Person createMale(String name, Date birthDay) { return new Person(name, Sex.MALE, birthDay); } public static Person createFemale(String name, Date birthDay) { return new Person(name, Sex.FEMALE, birthDay); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Sex getSex() { return sex; } public void setSex(Sex sex) { this.sex = sex; } public Date getBirthDay() { return birthDay; } public void setBirthDay(Date birthDay) { this.birthDay = birthDay; } public String getSexStr() { return getSex().toString().equals("MALE") ? "м" : "ж" ; } public String getDateStr() { String [] dateArray = getBirthDay().toString().split(" "); return dateArray[2] + "-" + dateArray[1] + "-" + dateArray[5]; } } <file_sep>package com.javarush.task.task18.task1819; /* Объединение файлов */ import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; public class Solution { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String fileName1 = reader.readLine(); String fileName2 = reader.readLine(); FileInputStream fileInputStream1 = new FileInputStream(fileName1); byte [] data = new byte [fileInputStream1.available()]; fileInputStream1.read(data); FileInputStream fileInputStream2 = new FileInputStream(fileName2); FileOutputStream fileOutputStream = new FileOutputStream(fileName1); while (fileInputStream2.available() > 0){ int b = fileInputStream2.read(); fileOutputStream.write(b); } for (int i = 0; i < data.length; i++){ fileOutputStream.write(data[i]); } reader.close(); fileInputStream1.close(); fileInputStream2.close(); fileOutputStream.close(); } } <file_sep>package com.javarush.task.task27.task2712.ad; import com.javarush.task.task27.task2712.ConsoleHelper; import com.javarush.task.task27.task2712.statistic.StatisticManager; import com.javarush.task.task27.task2712.statistic.event.VideoSelectedEventDataRow; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class AdvertisementManager { // общее время приготовления заказа в секундах private int timeSeconds; private AdvertisementStorage storage = AdvertisementStorage.getInstance(); public AdvertisementManager(int timeSeconds) { this.timeSeconds = timeSeconds; } public void processVideos(){ if (storage.list().size() == 0) { throw new NoVideoAvailableException(); } //Сортируем список по стоимости показа, затем по стоимости показа секунды ролика Collections.sort(storage.list(), new Comparator<Advertisement>() { @Override public int compare(Advertisement adv1, Advertisement adv2) { if (adv1.getAmountPerOneDisplaying() > adv2.getAmountPerOneDisplaying()) return -1; else if (adv1.getAmountPerOneDisplaying() < adv2.getAmountPerOneDisplaying()) return 1; else { if (adv1.getAmountPerOneSecond() > adv2.getAmountPerOneSecond()) return 1; else if (adv1.getAmountPerOneSecond() < adv2.getAmountPerOneSecond()) return -1; else return 0; } } }); // Создаем список видео к показу List<Advertisement> videosToShow = new ArrayList<>(); // Общее рекламное время int totalAdvTime = timeSeconds; // Общая стоимость и продолжительность отобранных роликов long totalAmount = 0; int totalDuration = 0; for (Advertisement video : storage.list()){ if (video.getDuration() <= totalAdvTime && video.getHits() > 0) { videosToShow.add(video); totalAdvTime -= video.getDuration(); totalAmount += video.getAmountPerOneDisplaying(); totalDuration += video.getDuration(); } } StatisticManager.getInstance().register(new VideoSelectedEventDataRow(videosToShow, totalAmount, totalDuration)); for (Advertisement video : videosToShow){ ConsoleHelper.writeMessage(video.getName() + " is displaying... " + video.getAmountPerOneDisplaying() + ", " + video.getAmountPerOneSecond()); video.revalidate(); } } } <file_sep>package com.javarush.task.task13.task1326; /* Сортировка четных чисел из файла */ import java.io.*; import java.util.ArrayList; import java.util.Set; import java.util.TreeSet; public class Solution { public static void main(String[] args)throws Exception { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); String name = bufferedReader.readLine(); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(name))); Set<Integer> set = new TreeSet<>(); while (reader.ready()){ int i = Integer.parseInt(reader.readLine()); if (i % 2 == 0){ set.add(i); } } reader.close(); for (Integer i: set){ System.out.println(i); } } }
fad73d6ac1371c37cf77826c9569de3d0eca34d9
[ "Java" ]
52
Java
ArFonzerelli/JavaRushTasks
3d9e89d5481f981459e24a44fc7b0cd92c4f3977
d751f2e32dddfe0c763716926dbd362faf3dfeb1
refs/heads/master
<file_sep>package com.bw.mapper; import java.util.List; import com.bw.bean.Brand; import com.bw.bean.Goods; import com.bw.bean.Type; public interface GoodsMapper { public List<Goods> sel(Goods g); public String addBrand(Brand b); public String kind(Type t); public void addAll(Goods g); } <file_sep>package com.bw.bean; public class Type { private Integer tid; private String type; public Type() { super(); // TODO Auto-generated constructor stub } @Override public String toString() { return "type [tid=" + tid + ", type=" + type + "]"; } public Integer getTid() { return tid; } public void setTid(Integer tid) { this.tid = tid; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Type(Integer tid, String type) { super(); this.tid = tid; this.type = type; } } <file_sep>package com.bw.bean; public class Goods { private Integer gid; private Integer tid; private Integer bid; private Integer num; private String name; private String ename; private String rize; private String bq; private String imgurl; private String price; private String brand; private String type; public Goods() { super(); // TODO Auto-generated constructor stub } @Override public String toString() { return "Goods [gid=" + gid + ", tid=" + tid + ", pid=" + bid + ", num=" + num + ", name=" + name + ", ename=" + ename + ", rize=" + rize + ", bq=" + bq + ", imgurl=" + imgurl + ", price=" + price + ", brand=" + brand + ", type=" + type + "]"; } public Integer getGid() { return gid; } public void setGid(Integer gid) { this.gid = gid; } public Integer getTid() { return tid; } public void setTid(Integer tid) { this.tid = tid; } public Integer getBid() { return bid; } public void setBid( Integer bid) { this.bid = bid; } public Integer getNum() { return num; } public void setNum(Integer num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public String getRize() { return rize; } public void setRize(String rize) { this.rize = rize; } public String getBq() { return bq; } public void setBq(String bq) { this.bq = bq; } public String getImgurl() { return imgurl; } public void setImgurl(String imgurl) { this.imgurl = imgurl; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Goods(Integer gid, Integer tid, Integer bid, Integer num, String name, String ename, String rize, String bq, String imgurl, String price, String brand, String type) { super(); this.gid = gid; this.tid = tid; this.bid = bid; this.num = num; this.name = name; this.ename = ename; this.rize = rize; this.bq = bq; this.imgurl = imgurl; this.price = price; this.brand = brand; this.type = type; } }
f833a36f9f17582e4510fdc46594accb474c5134
[ "Java" ]
3
Java
guojiqiang88/1711b
9fda1264d8d98e5cc6a29430e111ef757d8c8dd1
7f778ed34f7768412c95dc67e27e6d7cbf8ef5dd
refs/heads/master
<file_sep>const path = require('path'); const webpack = require('webpack'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); module.exports = { entry: ['./src/promise-fix.js', './src/entry.js'], output: { path: path.resolve(__dirname, 'dist'), filename: 'entry.bundle.js', }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader' } } ] }, optimization: { minimizer: [ new UglifyJsPlugin({ cache: true, parallel: true, uglifyOptions: { compress: true, ecma: 6, mangle: false // Disable name mangling to avoid this issue: https://github.com/espruino/Espruino/issues/1367 }, sourceMap: true }) ] }, };
627c25b36a6c6b22feba825abd7c54f89b9251a3
[ "JavaScript" ]
1
JavaScript
tripleW1989/espruino-webpack-babel-sample
d3f776aedd2aeaa293813acd2eecd6dc2740d410
9539711e2e9c7aac2e9f7435f9e7bf5af43dc5d7
refs/heads/master
<repo_name>sanwong15/RL<file_sep>/Self-Driving/PPO-deepCarla/sim_v3/action.py """ Summary: Class - Action """ from __future__ import (absolute_import, division, print_function, unicode_literals) from itertools import product from future.builtins import (int, open, round, str) import math import numpy as np import logs log = logs.get_log(__name__) class Action(object): STEERING_INDEX = 0 THROTTLE_INDEX = 1 BRAKE_INDEX = 2 HANDBRAKE_INDEX = 3 HAS_CONTROL_INDEX = 4 STEERING_MIN, STEERING_MAX = -1, 1 THROTTLE_MIN, THROTTLE_MAX = -1, 1 BRAKE_MIN, BRAKE_MAX = 0, 1 HANDBRAKE_MIN, HANDBRAKE_MAX = 0, 1 def __init__(self, steering=0, throttle=0, brake=0, handbrake=0, has_control=True): self.steering = steering self.throttle = throttle self.brake = brake self.handbrake = handbrake self.has_control = has_control def clip(self): self.steering = min(max(self.steering, self.STEERING_MIN), self.STEERING_MAX) self.throttle = min(max(self.throttle, self.THROTTLE_MIN), self.THROTTLE_MAX) self.brake = min(max(self.brake, self.BRAKE_MIN), self.BRAKE_MAX) self.handbrake = min(max(self.handbrake, self.HANDBRAKE_MIN), self.HANDBRAKE_MAX) def as_gym(self): ret = gym_action(steering=self.steering, throttle=self.throttle, brake=self.brake, handbrake=self.handbrake, has_control=self.has_control) return ret def serialize(self): ret = [self.steering, self.throttle, self.brake, self.handbrake, self.has_control] return ret @classmethod def from_gym(cls, action): has_control = True if len(action) > 4: if isinstance(action[4], list): has_control = action[4][0] else: has_control = action[cls.HAS_CONTROL_INDEX] handbrake = action[cls.HANDBRAKE_INDEX][0] if handbrake <= 0 or math.isnan(handbrake): handbrake = 0 else: handbrake = 1 ret = cls(steering=action[cls.STEERING_INDEX][0], throttle=action[cls.THROTTLE_INDEX][0], brake=action[cls.BRAKE_INDEX][0], handbrake=handbrake, has_control=has_control) return ret def gym_action(steering=0, throttle=0, brake=0, handbrake=0, has_control=True): action = [np.array([steering]), np.array([throttle]), np.array([brake]), np.array([handbrake]), has_control] return action class DiscreteActions(object): def __init__(self, steer, throttle, brake): self.steer = steer self.throttle = throttle self.brake = brake self.product = list(product(steer, throttle, brake)) def get_components(self, idx): steer, throttle, brake = self.product[idx]<file_sep>/Self-Driving/PPO-deepCarla/tensorflow_agent/action_jitterer.py from __future__ import (absolute_import, division, print_function, unicode_literals) import glob import os from future.builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str, super, zip) from enum import Enum import config as c import logs log = logs.get_log(__name__) class JitterState(Enum): MAINTAIN = 1 SWITCH_TO_NONRAND = 2 SWITCH_TO_RAND = 3 class ActionJitterer(object): def __init__(self): """ Jitters state between m random then n non-random steps - where m and n are set to different values to increase sample diversity """ self.rand_step = None self.nonrand_step = None self.rand_total = None self.nonrand_total = None self.seq_total = None self.perform_random_actions = None self.reset() def advance(self): if self.perform_random_actions: if self.rand_step < self.rand_total: self.rand_step += 1 ret = JitterState.MAINTAIN else: # Done with random actions, switch to non-random self.perform_random_actions = False ret = JitterState.SWITCH_TO_NONRAND else: if self.nonrand_step < self.nonrand_total: self.nonrand_step += 1 ret = JitterState.MAINTAIN else: # We are done with the sequence self.reset() if self.perform_random_actions: ret = JitterState.SWITCH_TO_RAND else: ret = JitterState.MAINTAIN # Skipping random actions this sequence return ret def reset(self): self.rand_step = 0 self.nonrand_step = 0 rand = c.rng.rand() if rand < 0.50: self.rand_total = 0 self.nonrand_total = 10 elif rand < 0.67: self.rand_total = 4 self.nonrand_total = 5 elif rand < 0.85: self.rand_total = 8 self.nonrand_total = 10 elif rand < 0.95: self.rand_total = 12 self.nonrand_total = 15 else: self.rand_total = 24 self.nonrand_total = 30 log.debug('random action total %r, non-random total %r', self.rand_total, self.nonrand_total) self.seq_total = self.rand_total + self.nonrand_total self.perform_random_actions = self.rand_total != 0 <file_sep>/Self-Driving/baseline-model/preception/vision/traffic-sign/modelTest.py import os import numpy as np from imagePreprocess import pre_processing def test(path_to_signs): labels = {} X_new = list() y_new = np.array([], dtype=np.int) #path_to_signs = './new_images' for imagePath in os.listdir(path_to_signs): print(imagePath) image = cv2.imread(os.path.join(path_to_signs, imagePath), cv2.COLOR_BGRA2RGB) path = imagePath.split('_') image = cv2.resize(image, (32, 32)) X_new.append(image) y_new = np.append(y_new, [np.int(path[0])]) print(len(X_new), ' images of shape: ', X_new[0].shape) def performanceEvaulation(X_new, y_new): X_new_p = pre_processing(X_new) with tf.Session() as sess: saver.restore(sess, './lenet11') test_accuracy = evaluate(X_new_p, y_new) print("Test Accuracy = {:.3f}".format(test_accuracy))<file_sep>/Self-Driving/PPO-deepCarla/sim_v3/__init__.py ''' Summary: File to run when an env / sim is being set - start - start_local_env - add_recorder - monkey_patch_env_api - connect_to_unreal ''' from __future__ import (absolute_import, division, print_function, unicode_literals) from future.builtins import (dict, input, str) from box import Box from gym.envs.registration import register # noinspection PyUnresolvedReferences import gym import logs import config as c # We do not use deepdrive api # from deepdrive_api.client import Client # noinspection PyUnresolvedReferences from sim_v3.action import gym_action as action from sim_v3.driving_style import DrivingStyle from sim_v3 import driving_style from sim_v3.sim_args import SimArgs from sim_v3.view_mode import ViewMode, ViewModeController from sim_v3 import world from recorder_v3.recorder import Recorder log = logs.get_log(__name__) def start(**kwargs): """ Deepdrive gym environment factory. This configures and creates a gym environment from parameters passed through main.py The parameters are either used to start the environment in process, or marshalled and passed to a remote instance of the environment, in which case this method is called again on the remote server with the same args, minus is_remote_client. :param kwargs: Deepdrive gym env configuration :return: environment object that implements the gym API (i.e. step, reset, close, render) """ args = SimArgs(**kwargs) if args.is_remote_client: if isinstance(args.driving_style, DrivingStyle): args.driving_style = args.driving_style.as_string() args.client_main_args = c.MAIN_ARGS env = Client(**(args.to_dict())) else: env = start_local_env(args) return env def start_local_env(args:SimArgs): """ Acts as a constructor / factory for a local gym environment and starts the associated Unreal process :param args: :return: gym environment """ if isinstance(args.driving_style, str): args.driving_style = DrivingStyle.from_str(args.driving_style) env = gym.make(args.env_id) env.seed(c.RNG_SEED) if args.experiment is None: args.experiment = '' _env = env.unwrapped _env.is_discrete = args.is_discrete _env.preprocess_with_tensorflow = args.preprocess_with_tensorflow _env.is_sync = args.is_sync _env.reset_returns_zero = args.reset_returns_zero _env.init_action_space() _env.target_fps = args.fps _env.experiment = args.experiment.replace(' ', '_') _env.sim_step_time = args.sim_step_time _env.period = 1. / args.fps _env.driving_style = args.driving_style _env.should_render = args.render _env.enable_traffic = args.enable_traffic _env.ego_mph = args.ego_mph _env.view_mode_controller = ViewModeController(period=args.view_mode_period) _env.max_steps = args.max_steps _env.max_episodes = args.max_episodes _env.set_use_sim_start_command(args.use_sim_start_command) _env.image_resize_dims = args.image_resize_dims add_recorder(_env, args) _env.should_normalize_image = args.should_normalize_image _env.randomize_sun_speed = args.randomize_sun_speed _env.randomize_shadow_level = args.randomize_shadow_level _env.randomize_month = args.randomize_month _env.is_botleague = args.is_botleague connect_to_unreal(_env, args) _env.set_step_mode() if args.sess: _env.set_tf_session(args.sess) if args.start_dashboard: _env.start_dashboard() log.info('Will save results to %s', c.RESULTS_DIR) _env.init_benchmarking() monkey_patch_env_api(env) env.reset() return env def add_recorder(_env, args:SimArgs): if args.is_remote_client: main_args = args.client_main_args else: main_args = c.MAIN_ARGS _env.recorder = Recorder(args.recording_dir, should_record=args.should_record, eval_only=args.eval_only, should_upload_gist=args.upload_gist, public=args.public, main_args=main_args, is_botleague=args.is_botleague) def monkey_patch_env_api(env): """ Monkey patch methods we want in the env API (c.f. api/client.py) :param env: gym environment to patch """ env.change_cameras = env.unwrapped.change_cameras def connect_to_unreal(_env, args): """ Start or connect to an existing instance of the Deepdrive simulator running in Unreal Engine """ if args.use_sim_start_command: # TODO: Find a better way to do this. Waiting for the hwnd and focusing does not work in windows. input('Press any key when the game has loaded') _env.connect(args.cameras) # Use start() to parameterize environment. # Parameterizing here leads to combinitorial splosion. register( id='Deepdrive-v0', entry_point='sim_v3.gym_env:DeepDriveEnv', kwargs=dict(), )<file_sep>/Self-Driving/baseline-model/preception/vision/traffic-sign/modelTrain.py import tensorflow as tf from LeNetArch import LeNet from sklearn.utils import shuffle from dataAugmentation import augmentation, motion_blue, save_augmented_data from imagePreprocess import pre_processing_single_img, pre_processing from sklearn import metrics import seaborn as sn def setTrainPipeline(X_train, one_hot_y, apply_dropout): # Train Pipeline: (1) Take in Tensorflow placeholder (contain training data), (2) pass it through the model (3) Calculate cross-entropy (4) # Expecting X_train is the Tensorflow placeholder # Expect the y_train already been transformed into one-hot array placeholder to calculate cross-entropy # Expecting apply_dropout is the Tensorflow placeholder # Return: training_operation (i.e: output of optimizer minimization rate = 0.001 mu = 0 sigma = 0.1 beta = 0.001 weights = [ tf.Variable(tf.truncated_normal(shape=(5, 5, 1, 12), mean = mu, stddev = sigma)), tf.Variable(tf.truncated_normal(shape=(5, 5, 12, 24), mean = mu, stddev = sigma)), tf.Variable(tf.truncated_normal(shape=(1188, 320), mean = mu, stddev = sigma)), tf.Variable(tf.truncated_normal(shape=(320, n_classes), mean = mu, stddev = sigma)) ] biases = [ tf.Variable(tf.zeros(12)), tf.Variable(tf.zeros(24)), tf.Variable(tf.zeros(320)), tf.Variable(tf.zeros(n_classes)) ] logits = LeNet(X_train, weights, biases, apply_dropout) cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, one_hot_y) loss_operation = tf.reduce_mean(cross_entropy) regularizer = tf.reduce_sum([tf.nn.l2_loss(w) for w in weights]) loss = tf.reduce_mean(loss_operation + beta * regularizer) optimizer = tf.train.AdamOptimizer(learning_rate = rate) training_operation = optimizer.minimize(loss) return logits, cross_entropy, loss_operation, training_operation def evaluate(X_data, y_data): num_examples = len(X_data) total_accuracy = 0 sess = tf.get_default_session() for offset in range(0, num_examples, BATCH_SIZE): batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE] accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y, apply_dropout: False}) total_accuracy += (accuracy * len(batch_x)) return total_accuracy / num_examples def preprocessDataAugmentation(X_data, y_data): # 1. Augmentation X_data_aug, y_data_aug = augmentation(X_data, y_data) # 2. Save Augmentated and Motion Blur data first path = "./data/traffic-signs-data/train_aug.p" save_augmented_data(X_data_aug, y_data_aug, path) # 3. preprocess (normalization, grayscale) X_data_aug_p = pre_processing(X_data_aug) y_data_aug_p = y_data_aug_mb # 4. Save preprocess augmented motion blur data path = "./data/traffic-signs-data/train_aug_p.p" save_augmented_data(X_data_aug_p, y_data_aug_p, path) return X_data_aug_p, y_data_aug_p def preprocessDataAugmentationMotionBlur(X_data, y_data): # 1. Augmentation X_data_aug, y_data_aug = augmentation(X_data, y_data) # 2. Motion Blur X_data_aug_mb, y_data_aug_mb = motion_blur(X_data_aug, y_data_aug, 4) # 3. Save Augmentated and Motion Blur data first path = "./data/traffic-signs-data/train_aug_mb.p" save_augmented_data(X_data_aug_mb, y_data_aug_mb, path) # 4. preprocess (normalization, grayscale) X_data_aug_mb_p = pre_processing(X_data_aug_mb) y_data_aug_mb_p = y_data_aug_mb # 5. Save preprocess augmented motion blur data path = "./data/traffic-signs-data/train_aug_mb_p.p" save_augmented_data(X_data_aug_mb_p, y_data_aug_mb_p, path) return X_data_aug_mb_p, y_data_aug_mb_p def load_default_data(): # default data path training_file = "./data/traffic-signs-data/train.p" validation_file = "./data/traffic-signs-data/valid.p" testing_file = "./data/traffic-signs-data/test.p" with open(training_file, mode='rb') as f: train = pickle.load(f) with open(validation_file, mode='rb') as f: valid = pickle.load(f) with open(testing_file, mode='rb') as f: test = pickle.load(f) X_train, y_train = train['features'], train['labels'] X_valid, y_valid = valid['features'], valid['labels'] X_test, y_test = test['features'], test['labels'] return X_train, y_train, X_valid, y_valid, X_test, y_test def train(): # Init global best_validation_accuracy best_validation_accuracy = 0.0 # Load the Data X_train, y_train, X_valid, y_valid, X_test, y_test = load_default_data() # preprocess original TRAIN DATA X_train_p = pre_processing(X_train) y_train_p = y_train # Augmentation + Preprocess on TRAIN DATA X_train_aug_p, y_train_aug_p = preprocessDataAugmentation(X_train, y_train) # Augmentation + Motion_blur + Preprocess on TRAIN DATA X_train_aug_mb_p, y_train_aug_mb_p = preprocessDataAugmentationMotionBlur(X_train, y_train) # Concate Augmentation + Motion_blur with original processed TRAIN DATA X_train_p = np.concatenate((X_train_p, X_train_aug_p, X_train_aug_mb_p), axis=0) y_train_p = np.concatenate((y_train_p, y_train_aug_p, y_train_aug_mb_p), axis=0) # TrainPipeline (input placeholder: x, one_hot_y, apple_dropout) # (1) Create placeholders x = tf.placeholder(tf.float32, (None, 32, 32, 1)) y = tf.placeholder(tf.int32, (None)) one_hot_y = tf.one_hot(y, n_classes) apply_dropout = tf.placeholder(tf.bool) # (2) Pipeline logits, cross_entropy, loss_operation, training_operation = setTrainPipeline(x, one_hot_y, apply_dropout) # training_operation will be used in the training sess correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1)) accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) saver = tf.train.Saver() # TRAIN # (1) TRAINING Parameters EPOCHS = 10 BATCH_SIZE = 128 # (2) Start session for training with tf.Session() as sess: print("Training Session Starting...") print("Initializing Global Variables ... ") sess.run(tf.global_variables_initializer()) print("Global Variables Initialization done") # saver.restore(sess, tf.train.latest_checkpoint('.')) # saver.restore(sess, './lenet11') num_examples = len(X_train_p) print("Training...") print() for i in range(EPOCHS): X_train_p, y_train_p = shuffle(X_train_p, y_train_p) for offset in range(0, num_examples, BATCH_SIZE): end = offset + BATCH_SIZE batch_x, batch_y = X_train_p[offset:end], y_train_p[offset:end] sess.run(training_operation, feed_dict={x: batch_x, y: batch_y, apply_dropout: True}) validation_accuracy = evaluate(X_valid_p, y_valid_p) training_accuracy = evaluate(X_train_p, y_train_p) print("EPOCH {} ...".format(i + 1)) print("Training Accuracy = {:.3f}".format(training_accuracy)) print("Validation Accuracy = {:.3f}".format(validation_accuracy)) print() if (validation_accuracy > best_validation_accuracy): best_validation_accuracy = validation_accuracy saver.save(sess, './lenet11') print("Model saved") # Compute Accuracy with tf.Session() as sess: # saver.restore(sess, tf.train.latest_checkpoint('.')) saver.restore(sess, './lenet11') training_accuracy = evaluate(X_train_p, y_train_p) print("Training Accuracy = {:.3f}".format(training_accuracy)) validation_accuracy = evaluate(X_valid_p, y_valid_p) print("Validation Accuracy = {:.3f}".format(validation_accuracy)) test_accuracy = evaluate(X_test_p, y_test_p) print("Test Accuracy = {:.3f}".format(test_accuracy)) # metrics y_p = tf.argmax(logits, 1) y_pred = sess.run(y_p, feed_dict={x: X_test_p, y: y_test_p, apply_dropout: False}) print ("test accuracy:", test_accuracy) y_true = y_test_p print ("Precision", metrics.precision_score(y_true, y_pred, average='macro')) print ("Recall", metrics.recall_score(y_true, y_pred, average='micro')) print ("f1_score", metrics.f1_score(y_true, y_pred, average='weighted')) print ("Confusion_matrix") cm = metrics.confusion_matrix(y_true, y_pred) print (cm) # Save the confusion matrix in a csv file: np.savetxt("cm.csv", cm, delimiter=",")<file_sep>/Self-Driving/PPO-deepCarla/sim_v3/driving_style.py ''' Summary: driving_style.py define the the followings Class - RewardWeighting : {progress_weight, gforce_weight, lane_deviation_weight, time_weight, speed_weight} - combine: define the logic of how those weight comes together Class - DrivingStyle: Mode of driving ''' from __future__ import (absolute_import, division, print_function, unicode_literals) from future.builtins import (int, open, round, str) from enum import Enum import logs log = logs.get_log(__name__) class RewardWeighting(object): def __init__(self, progress, gforce, lane_deviation, total_time, speed): # Progress and time were used in DeepDrive-v0 (2.0) - # keeping for now in case we want to use again self.progress_weight = progress self.gforce_weight = gforce self.lane_deviation_weight = lane_deviation self.time_weight = total_time self.speed_weight = speed @staticmethod def combine(progress_reward, gforce_penalty, lane_deviation_penalty, time_penalty, speed): return progress_reward \ - gforce_penalty \ - lane_deviation_penalty \ - time_penalty \ + speed class DrivingStyle(Enum): """Idea: Adjust these weights dynamically to produce a sort of curriculum where speed is learned first, then lane, then gforce. Also, need to record unweighted score components in physical units (m, m/s^2, etc...) so that scores can be compared across different weightings and environments. To adjust dynamically, the reward weighting should be changed per episode, or a horizon based on discount factor, in order to achieve a desired reward component balance. So say we wanted speed to be the majority of the reward received, i.e. 50%. We would look at the share made up by speed in the return for an episode (i.e. trip or lap for driving). If it's 25% of the absolute reward (summing positive and abs(negative) rewards), then we double a "curriculum coefficient" or CC for speed. These curriculum coefficients then get normalized so the final aggregate reward maintains the same scale as before. Then, as speed gets closer to 50% of the reward, the smaller components of the reward will begin to get weighted more heavily. If speed becomes more than 50% of the reward, then its CC will shrink and allow learning how to achieve other objectives. Why do this? Optimization should find the best way to squeeze out all the juice from the reward, right? Well, maybe, but I'm finding the scale and *order* to be very important in practice. In particular, lane deviation grows like crazy once you are out of the lane, regardless of the weight. So if speed is not learned first, our agent just decides to not move. Also, g-force penalties counter initial acceleration required to get speed, so we end up needing to weight g-force too small or too large with respect to speed over the long term. The above curriculum approach aims to fix these things by targeting a certain balance of objectives over the long-term, rather than the short-term, while adjusting short-term curriculum weights in order to get there. Yes, it does feel like the model should take care of this, but it's only optimized for the expected aggregate reward across all the objectives. Perhaps inputting the different components running averages or real-time values to a recurrent part of the model would allow it to balance the objectives through SGD rather than the above simple linear tweaking. (looks like EPG is a nicer formulation of this https://blog.openai.com/evolved-policy-gradients/) (Now looks like RUDDER is another principled step in this direction https://arxiv.org/abs/1806.07857) - After some experimentation, seems like we may not need this yet. Observation normalization was causing the motivating problem by learning too slow. Optimization does find a way. I think distributional RL may be helpful here especially if we can get dimensions for all the components of the reward. Also a novelty bonus on (observation,action) or (game-state,action) would be helpful most likely to avoid local minima. """ __order__ = 'CRUISING NORMAL RL_1 LATE EMERGENCY CHASE STEER_ONLY' # TODO: Possibly assign function rather than just weights CRUISING = RewardWeighting(speed=0.5, progress=0.0, gforce=2.00, lane_deviation=1.50, total_time=0.0) NORMAL = RewardWeighting(speed=1.0, progress=0.0, gforce=1.00, lane_deviation=0.10, total_time=0.0) RL_1 = RewardWeighting(speed=1.0, progress=0.0, gforce=0.00, lane_deviation=0.10, total_time=0.0) # TODO: Use this to bootstrap PPO, otherwise will not gain speed. LATE = RewardWeighting(speed=2.0, progress=0.0, gforce=0.50, lane_deviation=0.50, total_time=0.0) EMERGENCY = RewardWeighting(speed=2.0, progress=0.0, gforce=0.75, lane_deviation=0.75, total_time=0.0) CHASE = RewardWeighting(speed=2.0, progress=0.0, gforce=0.00, lane_deviation=0.00, total_time=0.0) STEER_ONLY = RewardWeighting(speed=1.0, progress=0.0, gforce=0.00, lane_deviation=0.00, total_time=0.0) def as_string(self): return self.name.lower() @classmethod def from_str(cls, name): return cls[name.upper()]<file_sep>/Self-Driving/PPO-deepCarla/tensorflow_agent/net.py import tensorflow as tf # Layer is the same for Dagger from tensorflow_agent.layers import conv2d, max_pool_2x2, linear, lrn # Integrate with Dagger-Net (deepDrivev3) import config as c from config import ALEXNET_NAME, ALEXNET_FC7, ALEXNET_IMAGE_SHAPE, MOBILENET_V2_SLIM_NAME, MOBILENET_V2_IMAGE_SHAPE from util.download import download, has_stuff from vendor.tensorflow.models.research.slim.nets import nets_factory from vendor.tensorflow.models.research.slim.preprocessing import preprocessing_factory log = logs.get_log(__name__) # A module is understood as instrumented for quantization with TF-Lite # if it contains any of these ops. FAKE_QUANT_OPS = ('FakeQuantWithMinMaxVars','FakeQuantWithMinMaxVarsPerChannel') class Net(object): """AlexNet architecture with modified final fully-connected layers regressed on driving control outputs (steering, throttle, etc...)""" def __init__(self, x, num_targets=6, is_training=True): self.x = x # phase = tf.placeholder(tf.bool, name='phase') # Used for batch norm conv1 = tf.nn.relu(conv2d(x, "conv1", 96, 11, 4, 1)) lrn1 = lrn(conv1) maxpool1 = max_pool_2x2(lrn1) conv2 = tf.nn.relu(conv2d(maxpool1, "conv2", 256, 5, 1, 2)) lrn2 = lrn(conv2) maxpool2 = max_pool_2x2(lrn2) conv3 = tf.nn.relu(conv2d(maxpool2, "conv3", 384, 3, 1, 1)) # Not sure why this isn't 2 groups, but pretrained net was trained like this so we're going with it. # Avoid diverging from pretrained weights with things like batch norm for now. # Perhaps try a modern small net like Inception V1, ResNet 18, or Resnet 50 # conv3 = tf.contrib.layers.batch_norm(conv3, scope='batchnorm3', is_training=phase, # # fused=True, # # data_format='NCHW', # # renorm=True # ) conv4 = tf.nn.relu(conv2d(conv3, "conv4", 384, 3, 1, 2)) conv5 = tf.nn.relu(conv2d(conv4, "conv5", 256, 3, 1, 2)) maxpool5 = max_pool_2x2(conv5) fc6 = tf.nn.relu(linear(maxpool5, "fc6", 4096)) if is_training: fc6 = tf.nn.dropout(fc6, 0.5) else: fc6 = tf.nn.dropout(fc6, 1.0) fc7 = tf.nn.relu(linear(fc6, "fc7", 4096)) # fc7 = tf.contrib.layers.batch_norm(fc7, scope='batchnorm7', is_training=phase) if is_training: fc7 = tf.nn.dropout(fc7, 0.95) else: fc7 = tf.nn.dropout(fc7, 1.0) fc8 = linear(fc7, "fc8", num_targets) self.p = fc8 self.global_step = tf.get_variable("global_step", [], tf.int32, initializer=tf.zeros_initializer, trainable=False) class DaggerNet(object): def __int__(self, global_step=None, num_targets=c.NUM_TARGETS, is_training=True, freeze_pretrained=False, overfit=False): self.num_targets = num_targets self.is_training = is_training self.global_step = global_step self.freeze_pretrained = freeze_pretrained self.overfit = overfit self.batch_size = None self.learning_rate = None self.starter_learning_rate = None self.weight_decay = None self.input, self.last_hidden, self.out, self.eval_out = self._init_net() self.num_last_hidden = self.last_hidden.shape[-1] def get_tf_init_fn(self, init_op): raise NotImplementedError('get_tf_init_fn not implemented') def preprocess(self, image): return image def _init_net(self): raise NotImplementedError('init_net not implemented') class MobileNetV2(DaggerNet): def __init__(self, *args, **kwargs): self.input_image_shape = MOBILENET_V2_IMAGE_SHAPE self.image_preprocessing_fn = preprocessing_factory.get_preprocessing(MOBILENET_V2_SLIM_NAME, is_training=False) super(MobileNetV2, self).__init__(*args, **kwargs) if self.is_training: if self.freeze_pretrained: self.batch_size = 48 self.starter_learning_rate = 1e-3 else: self.batch_size = 32 self.starter_learning_rate = 1e-3 self.learning_rate = tf.train.exponential_decay(self.starter_learning_rate, global_step=self.global_step, decay_steps=55000, decay_rate=0.5, staircase=True) if self.overfit: self.weight_decay = 0. else: self.weight_decay = 0.00004 #https://arxiv.org/pdf/1801.04381.pdf self.mute_spurious_targets = True def get_tf_init_fn(self, init_op): def ret(sess): log.info('Initializing parameters.') sess.run(init_op) return ret def preprocess(self, image): image = self.image_preprocessing_fn(image, self.input_image_shape[0], self.input_image_shape[1]) image = tf.expand_dims(image, 0) return image def _init_net(self): input_tensor = tf.placeholder(tf.unit8, [None]+list(MOBILENET_V2_IMAGE_SHAPE)) network_fn = nets_factory.get_network_fn(MOBILENET_V2_SLIM_NAME, num_classes=None, num_targets=6, is_training=False, ) log.info('Loading mobilenet v2') image = self.preprocess(input_tensor) out, endpoints = nets_factory(image) last_hidden = endpoints['global_pool'] eval_out = out return input_tensor, last_hidden, out, eval_out class AlexNet(DaggerNet): def __init__(self, *args, **kwargs): self.input_image_shape = ALEXNET_IMAGE_SHAPE self.num_last_hidden = ALEXNET_FC7 self.net_name = ALEXNET_NAME self.starter_learning_rate = 2e-6 super(AlexNet, self).__init__(*args, **kwargs) if self.is_training: # The following should fit with GPU self.batch_size = 32 # TODO: Add Polyak Averaging self.learning_rate = tf.train.exponential_decay(self.starter_learning_rate, global_step = self.global_step, decay_steps = 73000, decay_rate=0.5, staircase=True) if self.overfit: self.weight_decay = 0. else: self.weight_decay = 0.0005 self.mute_spurious_targets = False def _init_net(self): input_tensor = tf.placeholder(tf.float32, (None,) + self.input_image_shape) with tf.variable_scope("model") as variable_scope: last_hidden, out = self._init_alexnet(input_tensor, self.is_training, self.num_targets, self.num_last_hidden) if self.is_training: variable_scope.reuse_variables() _, eval_out = self._init_alexnet(input_tensor, False, self.num_targets, self.num_last_hidden) else: eval_out = None return input_tensor, last_hidden, out, eval_out def get_tf_init_fn(self, init_op): return self._load_alexnet_pretrained(init_op) @staticmethod def _load_alexnet_pretrained(init_op): pretrained_var_map = {} for v in tf.trainable_variables(): found = False for bad_layer in ["fc6", "fc7", "fc8"]: if bad_layer in v.name: found = True if found: continue pretrained_var_map[v.op.name[6:]] = v alexnet_saver = tf.train.Saver(pretrained_var_map) def init_fn(ses): log.info('Initializing parameters.') if not has_stuff(c.ALEXNET_PRETRAINED_PATH): print('\n--------- ImageNet checkpoint not found, downloading ----------') download(c.ALEXNET_PRETRAINED_URL, c.WEIGHTS_DIR, warn_existing=False, overwrite=True) ses.run(init_op) alexnet_saver.restore(ses, c.ALEXNET_PRETRAINED_PATH) return init_fn @staticmethod def _init_alexnet(input_tensor, is_training, num_targets, num_last_hidden): # AlexNet (modified final fully-connected layers regressed on driving control outputs (steering, throttle, etc) # For Batch Norm # phase = tf.placeholder(tf.bool, name='phase') conv1 = tf.nn.relu(conv2d(input_tensor, "conv1", 96, 11, 4, 1)) lrn1 = lrn(conv1) maxpool1 = max_pool_2x2(lrn1) conv2 = tf.nn.relu(conv2d(maxpool1, "conv2", 256, 5, 1, 2)) lrn2 = lrn(conv2) maxpool2 = max_pool_2x2(lrn2) conv3 = tf.nn.relu(conv2d(maxpool2, "conv3", 384, 3, 1, 1)) conv4 = tf.nn.relu(conv2d(conv3, "conv4", 384, 3, 1, 2)) conv5 = tf.nn.relu(conv2d(conv4, "conv5", 256, 3, 1, 2)) maxpool5 = max_pool_2x2(conv5) fc6 = tf.nn.relu(linear(maxpool5, "fc6", 4096)) if is_training: fc6 = tf.nn.dropout(fc6, 0.5) else: fc6 = tf.nn.dropout(fc6, 1.0) fc7 = tf.nn.relu(linear(fc6, "fc7", num_last_hidden)) if is_training: fc7 = tf.nn.dropout(fc7, 0.95) else: fc7 = tf.nn.dropout(fc7, 1.0) fc8 = linear(fc7, "fc8", num_targets) return fc7, fc8 def variable_summaries(var): """Attach a lot of summaries to a Tensor (for TensorBoard visualization).""" with tf.name_scope('summaries'): mean = tf.reduce_mean(var) tf.summary.scalar('mean', mean) with tf.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean))) tf.summary.scalar('stddev', stddev) tf.summary.scalar('max', tf.reduce_max(var)) tf.summary.scalar('min', tf.reduce_min(var)) tf.summary.histogram('histogram', var)<file_sep>/Self-Driving/baseline-model/behavioural-cloning/modelTrain.py # Behavioural Cloning : # User drive on their own, while the system start recording the behaviour and sensor data # The car will then start to learn from the recorded data import os import csv import cv2 import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg from sklearn.model_selection import train_test_split from sklearn.utils import shuffle from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten, SpatialDropout2D, ELU from keras.layers import Convolution2D, MaxPooling2D, Cropping2D from keras.layers.core import Lambda from keras.optimizers import SGD, Adam, RMSprop from keras.utils import np_utils from keras.callbacks import ModelCheckpoint from keras.models import model_from_json import tensorflow as tf def run(csv_filepath): # Step 1: Sample Gathering (define empty sample array) samples = [] # Step 2: Add sample from data #samples = add_to_samples('data-udacity/driving_log.csv', samples) #samples = add_to_samples('data-recovery-annie/driving_log.csv', samples) samples = add_to_samples(csv_filepath, samples) samples = samples[1:] print("Length of samples: ", len(samples)) # Step 3: Split the samples into training and validation train_samples, validation_samples = train_test_split(samples, test_size = 0.1) # Step 4: Get the X and Y from samples with Generator train_generator = generator(train_samples, batch_size=32) validation_generator = generator(validation_samples, batch_size=32) # Step 5: Create the model model = behaviouralCloneModel() # Step 6: Start the training trainModel(model, train_generator, validation_generator) def add_to_samples(csv_filepath, samples): # Take in csv log data with open(csv_filepath) as csvfile: reader = csv.reader(csvfile) for line in reader: samples.append(line) return samples def generator(samples, batch_size = 32): num_samples = len(samples) while 1: # Loop forever, Generator never end shuffle(samples) for offset in range(0, num_samples, batch_size): # Getting batch sample of batch size batch_samples = samples[offset: offset + batch_size] images = [] angles = [] for batch_sample in batch_samples: # TODO: name has to be updated name = './data-udacity/' + batch_sample[0] center_image = mpimg.imread(name) center_angle = float(batch_sample[3]) images.append(center_image) angles.append(center_angle) X_train = np.array(images) y_train = np.array(angles) yield shuffle(X_train, y_train) #yield return a generator # Data preprocessing functions def resize_comma(image): return tf.image.resize_images(image, 40, 160) def behaviouralCloneModel(): # Construct a model, Return model model = Sequential() # INPUT LAYER 0 # (0.1) Crop 70 pixels from the top of the image and 25 from the bottom model.add(Cropping2D(cropping = ((70, 25), (0, 0)), dim_ordering='tf', input_shaoe=(160, 320, 3))) # (0.2) Resize the data model.add(Lambda(resize_comma)) # (0.3) Normalise the data model.add(Lambda(lambda x: (x/255.0) - 0.5)) # CONV LAYER 1 model.add(Convolution2D(16, 8, 8, subsample=(4, 4), border_mode="same")) model.add(ELU()) # CONV LAYER 2 model.add(Convolution2D(32, 5, 5, subsample=(2, 2), border_mode="same")) model.add(ELU()) # CONV LAYER 3 model.add(Convolution2D(64, 5, 5, subsample=(2, 2), border_mode="same")) model.add(Flatten()) model.add(Dropout(.2)) model.add(ELU()) # FULLY CONNECTED LAYER 1 model.add(Dense(512)) model.add(Dropout(.5)) model.add(ELU()) # FULLY CONNECTED LAYER 2 model.add(Dense(50)) model.add(ELU()) model.add(Dense(1)) adam = Adam(lr=0.0001) model.compile(optimizer=adam, loss="mse", metrics=['accuracy']) print("Model summary:\n", model.summary()) return model def trainModel(model, train_generator, validation_generator): nb_epoch = 20 # Create checkpoint to save model weights after each epoch checkpointer = ModelCheckpoint(filepath="./tmp/v2-weights.{epoch:02d}-{val_loss:.2f}.hdf5", verbose=1, save_best_only=False) # Train Model using Generator model.fit_generator(train_generator, samples_per_epoch=len(train_samples), validation_data=validation_generator, nb_val_samples=len(validation_samples), nb_epoch=nb_epoch, callbacks=[checkpointer]) # Save model model_json = model.to_json() with open("model.json", "w") as json_file: json_file.write(model_json) model.save_weights("model.h5") print("Saved model to disk")<file_sep>/carla_env.py from __future__ import print_function # import gym import gym from gym import error, spaces, utils from gym.utils import seeding # import other lib import asyncore from threading import Thread import time import glob import os import sys # Get time for get_reward import time try: sys.path.append(glob.glob('**/carla-*%d.%d-%s.egg' % ( sys.version_info.major, sys.version_info.minor, 'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0]) except IndexError: pass import carla from carla import ColorConverter as cc import argparse import collections import datetime import logging import math import random import re import weakref try: import pygame from pygame.locals import KMOD_CTRL from pygame.locals import KMOD_SHIFT from pygame.locals import K_0 from pygame.locals import K_9 from pygame.locals import K_BACKQUOTE from pygame.locals import K_BACKSPACE from pygame.locals import K_COMMA from pygame.locals import K_DOWN from pygame.locals import K_ESCAPE from pygame.locals import K_F1 from pygame.locals import K_LEFT from pygame.locals import K_PERIOD from pygame.locals import K_RIGHT from pygame.locals import K_SLASH from pygame.locals import K_SPACE from pygame.locals import K_TAB from pygame.locals import K_UP from pygame.locals import K_a from pygame.locals import K_c from pygame.locals import K_d from pygame.locals import K_h from pygame.locals import K_m from pygame.locals import K_p from pygame.locals import K_q from pygame.locals import K_r from pygame.locals import K_s from pygame.locals import K_w from pygame.locals import K_MINUS from pygame.locals import K_EQUALS except ImportError: raise RuntimeError('cannot import pygame, make sure pygame package is installed') try: import numpy as np except ImportError: raise RuntimeError('cannot import numpy, make sure numpy package is installed') # ============================================================================== # -- Global functions ---------------------------------------------------------- # ============================================================================== def find_weather_presets(): rgx = re.compile('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)') name = lambda x: ' '.join(m.group(0) for m in rgx.finditer(x)) presets = [x for x in dir(carla.WeatherParameters) if re.match('[A-Z].+', x)] return [(getattr(carla.WeatherParameters, x), name(x)) for x in presets] def get_actor_display_name(actor, truncate=250): name = ' '.join(actor.type_id.replace('_', '.').title().split('.')[1:]) return (name[:truncate-1] + u'\u2026') if len(name) > truncate else name # ============================================================================== # -- World --------------------------------------------------------------------- # ============================================================================== class World(object): def __init__(self, carla_world, hud, actor_filter): self.world = carla_world self.map = self.world.get_map() self.hud = hud self.player = None self.collision_sensor = None self.lane_invasion_sensor = None self.gnss_sensor = None self.camera_manager = None self._weather_presets = find_weather_presets() self._weather_index = 0 self._actor_filter = actor_filter self.restart() self.world.on_tick(hud.on_world_tick) self.recording_enabled = False self.recording_start = 0 self.velocity = 0 self.distanceFromLane = 0 self.angleFromLane = 0 self.isCrossingLane = False self.lastCrossingFrame = 0 def restartAtNewPos(self): spawn_points = self.map.get_spawn_points() spawn_point = random.choice(spawn_points) if spawn_points else carla.Transform() self.player.set_transform(spawn_point) self.player.set_velocity(carla.Vector3D()) self.player.set_angular_velocity(carla.Vector3D()) self.collision_sensor.sensor.destroy() self.lane_invasion_sensor.sensor.destroy() self.gnss_sensor.sensor.destroy() time.sleep(2.0) self.collision_sensor = CollisionSensor(self.player, self.hud) self.lane_invasion_sensor = LaneInvasionSensor(self.player, self) self.gnss_sensor = GnssSensor(self.player) return # Keep same camera config if the camera manager exists. cam_index = self.camera_manager._index if self.camera_manager is not None else 0 cam_pos_index = self.camera_manager._transform_index if self.camera_manager is not None else 0 # Get a random blueprint. blueprint = random.choice(self.world.get_blueprint_library().filter(self._actor_filter)) blueprint.set_attribute('role_name', 'hero') if blueprint.has_attribute('color'): color = random.choice(blueprint.get_attribute('color').recommended_values) blueprint.set_attribute('color', color) # Spawn the player. if self.player is not None: spawn_points = self.map.get_spawn_points() spawn_point = random.choice(spawn_points) if spawn_points else carla.Transform() self.destroy() self.player = self.world.try_spawn_actor(blueprint, spawn_point) while self.player is None: spawn_points = self.map.get_spawn_points() spawn_point = random.choice(spawn_points) if spawn_points else carla.Transform() self.player = self.world.try_spawn_actor(blueprint, spawn_point) # Set up the sensors. self.collision_sensor = CollisionSensor(self.player, self.hud) self.lane_invasion_sensor = LaneInvasionSensor(self.player, self) self.gnss_sensor = GnssSensor(self.player) self.camera_manager = CameraManager(self.player, self.hud) self.camera_manager._transform_index = cam_pos_index self.camera_manager.set_sensor(cam_index, notify=False) actor_type = get_actor_display_name(self.player) def restart(self): # Keep same camera config if the camera manager exists. cam_index = self.camera_manager._index if self.camera_manager is not None else 0 cam_pos_index = self.camera_manager._transform_index if self.camera_manager is not None else 0 # Get a random blueprint. blueprint = random.choice(self.world.get_blueprint_library().filter(self._actor_filter)) blueprint.set_attribute('role_name', 'hero') if blueprint.has_attribute('color'): color = random.choice(blueprint.get_attribute('color').recommended_values) blueprint.set_attribute('color', color) # Spawn the player. if self.player is not None: spawn_point = self.player.get_transform() spawn_point.location.z += 2.0 spawn_point.rotation.roll = 0.0 spawn_point.rotation.pitch = 0.0 self.destroy() self.player = self.world.try_spawn_actor(blueprint, spawn_point) while self.player is None: spawn_points = self.map.get_spawn_points() spawn_point = random.choice(spawn_points) if spawn_points else carla.Transform() self.player = self.world.try_spawn_actor(blueprint, spawn_point) # Set up the sensors. self.collision_sensor = CollisionSensor(self.player, self.hud) self.lane_invasion_sensor = LaneInvasionSensor(self.player, self) self.gnss_sensor = GnssSensor(self.player) self.camera_manager = CameraManager(self.player, self.hud) self.camera_manager._transform_index = cam_pos_index self.camera_manager.set_sensor(cam_index, notify=False) actor_type = get_actor_display_name(self.player) self.hud.notification(actor_type) def next_weather(self, reverse=False): self._weather_index += -1 if reverse else 1 self._weather_index %= len(self._weather_presets) preset = self._weather_presets[self._weather_index] self.hud.notification('Weather: %s' % preset[1]) self.player.get_world().set_weather(preset[0]) def tick(self, clock): self.hud.tick(self, clock) # calculate velocity if self.player is not None: v = self.player.get_velocity() self.velocity = math.sqrt(v.x**2 + v.y**2 + v.z**2) # in m/s # calculate distance from lane selfLoc = self.player.get_transform().location waypoint = self.map.get_waypoint(self.player.get_transform().location) if waypoint is not None: waypointLoc = waypoint.transform.location self.distanceFromLane = math.sqrt((selfLoc.x - waypointLoc.x)**2 + (selfLoc.y - waypointLoc.y)**2 + (selfLoc.z - waypointLoc.z)**2) next_waypoints = waypoint.next(1.0) if next_waypoints is not None and len(next_waypoints)>0: nextLoc = next_waypoints[len(next_waypoints)-1].transform.location waypointDiff = nextLoc - waypointLoc forward_vector = self.player.get_transform().get_forward_vector() self.angleFromLane = math.degrees(math.atan2(waypointDiff.y,waypointDiff.x) - math.atan2(forward_vector.y,forward_vector.x)) # print(self.angleFromLane) if self.isCrossingLane == True and self.lastCrossingFrame<= 0: self.isCrossingLane = False else: self.lastCrossingFrame = self.lastCrossingFrame - 1 def render(self, display): self.camera_manager.render(display) self.hud.render(display) def destroySensors(self): self.camera_manager.sensor.destroy() self.camera_manager.sensor = None self.camera_manager._index = None def destroy(self): actors = [ self.camera_manager.sensor, self.collision_sensor.sensor, self.lane_invasion_sensor.sensor, self.gnss_sensor.sensor, self.player] for actor in actors: if actor is not None: actor.destroy() # ============================================================================== # -- KeyboardControl ----------------------------------------------------------- # ============================================================================== class KeyboardControl(object): def __init__(self, world, start_in_autopilot): self._autopilot_enabled = start_in_autopilot if isinstance(world.player, carla.Vehicle): self._control = carla.VehicleControl() world.player.set_autopilot(self._autopilot_enabled) elif isinstance(world.player, carla.Walker): self._control = carla.WalkerControl() self._autopilot_enabled = False self._rotation = world.player.get_transform().rotation else: raise NotImplementedError("Actor type not supported") self._steer_cache = 0.0 world.hud.notification("Press 'H' or '?' for help.", seconds=4.0) def parse_events(self, client, world, clock): for event in pygame.event.get(): if event.type == pygame.QUIT: return True elif event.type == pygame.KEYUP: if self._is_quit_shortcut(event.key): return True elif event.key == K_BACKSPACE: world.restart() elif event.key == K_F1: world.hud.toggle_info() elif event.key == K_h or (event.key == K_SLASH and pygame.key.get_mods() & KMOD_SHIFT): world.hud.help.toggle() elif event.key == K_TAB: world.camera_manager.toggle_camera() elif event.key == K_c and pygame.key.get_mods() & KMOD_SHIFT: world.next_weather(reverse=True) elif event.key == K_c: world.next_weather() elif event.key == K_BACKQUOTE: world.camera_manager.next_sensor() elif event.key > K_0 and event.key <= K_9: world.camera_manager.set_sensor(event.key - 1 - K_0) elif event.key == K_r and not (pygame.key.get_mods() & KMOD_CTRL): world.camera_manager.toggle_recording() elif event.key == K_r and (pygame.key.get_mods() & KMOD_CTRL): if (world.recording_enabled): client.stop_recorder() world.recording_enabled = False world.hud.notification("Recorder is OFF") else: client.start_recorder("manual_recording.rec") world.recording_enabled = True world.hud.notification("Recorder is ON") elif event.key == K_p and (pygame.key.get_mods() & KMOD_CTRL): # stop recorder client.stop_recorder() world.recording_enabled = False # work around to fix camera at start of replaying currentIndex = world.camera_manager._index world.destroySensors() # disable autopilot self._autopilot_enabled = False world.player.set_autopilot(self._autopilot_enabled) world.hud.notification("Replaying file 'manual_recording.rec'") # replayer client.replay_file("manual_recording.rec", world.recording_start, 0, 0) world.camera_manager.set_sensor(currentIndex) elif event.key == K_MINUS and (pygame.key.get_mods() & KMOD_CTRL): if pygame.key.get_mods() & KMOD_SHIFT: world.recording_start -= 10 else: world.recording_start -= 1 world.hud.notification("Recording start time is %d" % (world.recording_start)) elif event.key == K_EQUALS and (pygame.key.get_mods() & KMOD_CTRL): if pygame.key.get_mods() & KMOD_SHIFT: world.recording_start += 10 else: world.recording_start += 1 world.hud.notification("Recording start time is %d" % (world.recording_start)) if isinstance(self._control, carla.VehicleControl): if event.key == K_q: self._control.gear = 1 if self._control.reverse else -1 elif event.key == K_m: self._control.manual_gear_shift = not self._control.manual_gear_shift self._control.gear = world.player.get_control().gear world.hud.notification('%s Transmission' % ('Manual' if self._control.manual_gear_shift else 'Automatic')) elif self._control.manual_gear_shift and event.key == K_COMMA: self._control.gear = max(-1, self._control.gear - 1) elif self._control.manual_gear_shift and event.key == K_PERIOD: self._control.gear = self._control.gear + 1 elif event.key == K_p and not (pygame.key.get_mods() & KMOD_CTRL): self._autopilot_enabled = not self._autopilot_enabled world.player.set_autopilot(self._autopilot_enabled) world.hud.notification('Autopilot %s' % ('On' if self._autopilot_enabled else 'Off')) if not self._autopilot_enabled: if isinstance(self._control, carla.VehicleControl): self._parse_vehicle_keys(pygame.key.get_pressed(), clock.get_time()) self._control.reverse = self._control.gear < 0 elif isinstance(self._control, carla.WalkerControl): self._parse_walker_keys(pygame.key.get_pressed(), clock.get_time()) world.player.apply_control(self._control) def _parse_vehicle_keys(self, keys, milliseconds): self._control.throttle = 1.0 if keys[K_UP] or keys[K_w] else 0.0 steer_increment = 5e-4 * milliseconds if keys[K_LEFT] or keys[K_a]: self._steer_cache -= steer_increment elif keys[K_RIGHT] or keys[K_d]: self._steer_cache += steer_increment else: self._steer_cache = 0.0 self._steer_cache = min(0.7, max(-0.7, self._steer_cache)) self._control.steer = round(self._steer_cache, 1) self._control.brake = 1.0 if keys[K_DOWN] or keys[K_s] else 0.0 self._control.hand_brake = keys[K_SPACE] def _parse_walker_keys(self, keys, milliseconds): self._control.speed = 0.0 if keys[K_DOWN] or keys[K_s]: self._control.speed = 0.0 if keys[K_LEFT] or keys[K_a]: self._control.speed = .01 self._rotation.yaw -= 0.08 * milliseconds if keys[K_RIGHT] or keys[K_d]: self._control.speed = .01 self._rotation.yaw += 0.08 * milliseconds if keys[K_UP] or keys[K_w]: self._control.speed = 5.556 if pygame.key.get_mods() & KMOD_SHIFT else 2.778 self._control.jump = keys[K_SPACE] self._rotation.yaw = round(self._rotation.yaw, 1) self._control.direction = self._rotation.get_forward_vector() @staticmethod def _is_quit_shortcut(key): return (key == K_ESCAPE) or (key == K_q and pygame.key.get_mods() & KMOD_CTRL) # ============================================================================== # -- HUD ----------------------------------------------------------------------- # ============================================================================== class HUD(object): def __init__(self, width, height): self.dim = (width, height) font = pygame.font.Font(pygame.font.get_default_font(), 20) if os.name == "posix": fonts = [x for x in pygame.font.get_fonts() if 'mono' in x] else: fonts = [x for x in pygame.font.get_fonts() if 'arial' in x] default_font = 'ubuntumono' mono = default_font if default_font in fonts else fonts[0] mono = pygame.font.match_font(mono) self._font_mono = pygame.font.Font(mono, 14) self._notifications = FadingText(font, (width, 40), (0, height - 40)) self.help = HelpText(pygame.font.Font(mono, 24), width, height) self.server_fps = 0 self.frame_number = 0 self.simulation_time = 0 self._show_info = True self._info_text = [] self._server_clock = pygame.time.Clock() def on_world_tick(self, timestamp): self._server_clock.tick() self.server_fps = self._server_clock.get_fps() self.frame_number = timestamp.frame_count self.simulation_time = timestamp.elapsed_seconds def tick(self, world, clock): return self._notifications.tick(world, clock) if not self._show_info: return t = world.player.get_transform() v = world.player.get_velocity() c = world.player.get_control() heading = 'N' if abs(t.rotation.yaw) < 89.5 else '' heading += 'S' if abs(t.rotation.yaw) > 90.5 else '' heading += 'E' if 179.5 > t.rotation.yaw > 0.5 else '' heading += 'W' if -0.5 > t.rotation.yaw > -179.5 else '' colhist = world.collision_sensor.get_collision_history() collision = [colhist[x + self.frame_number - 200] for x in range(0, 200)] max_col = max(1.0, max(collision)) collision = [x / max_col for x in collision] vehicles = world.world.get_actors().filter('vehicle.*') self._info_text = [ 'Server: % 16.0f FPS' % self.server_fps, 'Client: % 16.0f FPS' % clock.get_fps(), '', 'Vehicle: % 20s' % get_actor_display_name(world.player, truncate=20), 'Map: % 20s' % world.map.name, 'Simulation time: % 12s' % datetime.timedelta(seconds=int(self.simulation_time)), '', 'Speed: % 15.0f km/h' % (3.6 * math.sqrt(v.x**2 + v.y**2 + v.z**2)), u'Heading:% 16.0f\N{DEGREE SIGN} % 2s' % (t.rotation.yaw, heading), 'Location:% 20s' % ('(% 5.1f, % 5.1f)' % (t.location.x, t.location.y)), 'GNSS:% 24s' % ('(% 2.6f, % 3.6f)' % (world.gnss_sensor.lat, world.gnss_sensor.lon)), 'Height: % 18.0f m' % t.location.z, ''] if isinstance(c, carla.VehicleControl): self._info_text += [ ('Throttle:', c.throttle, 0.0, 1.0), ('Steer:', c.steer, -1.0, 1.0), ('Brake:', c.brake, 0.0, 1.0), ('Reverse:', c.reverse), ('Hand brake:', c.hand_brake), ('Manual:', c.manual_gear_shift), 'Gear: %s' % {-1: 'R', 0: 'N'}.get(c.gear, c.gear)] elif isinstance(c, carla.WalkerControl): self._info_text += [ ('Speed:', c.speed, 0.0, 5.556), ('Jump:', c.jump)] self._info_text += [ '', 'Collision:', collision, '', 'Number of vehicles: % 8d' % len(vehicles)] if len(vehicles) > 1: self._info_text += ['Nearby vehicles:'] distance = lambda l: math.sqrt((l.x - t.location.x)**2 + (l.y - t.location.y)**2 + (l.z - t.location.z)**2) vehicles = [(distance(x.get_location()), x) for x in vehicles if x.id != world.player.id] for d, vehicle in sorted(vehicles): if d > 200.0: break vehicle_type = get_actor_display_name(vehicle, truncate=22) self._info_text.append('% 4dm %s' % (d, vehicle_type)) def toggle_info(self): self._show_info = not self._show_info def notification(self, text, seconds=2.0): self._notifications.set_text(text, seconds=seconds) def error(self, text): self._notifications.set_text('Error: %s' % text, (255, 0, 0)) def render(self, display): return if self._show_info: info_surface = pygame.Surface((220, self.dim[1])) info_surface.set_alpha(100) display.blit(info_surface, (0, 0)) v_offset = 4 bar_h_offset = 100 bar_width = 106 for item in self._info_text: if v_offset + 18 > self.dim[1]: break if isinstance(item, list): if len(item) > 1: points = [(x + 8, v_offset + 8 + (1.0 - y) * 30) for x, y in enumerate(item)] pygame.draw.lines(display, (255, 136, 0), False, points, 2) item = None v_offset += 18 elif isinstance(item, tuple): if isinstance(item[1], bool): rect = pygame.Rect((bar_h_offset, v_offset + 8), (6, 6)) pygame.draw.rect(display, (255, 255, 255), rect, 0 if item[1] else 1) else: rect_border = pygame.Rect((bar_h_offset, v_offset + 8), (bar_width, 6)) pygame.draw.rect(display, (255, 255, 255), rect_border, 1) f = (item[1] - item[2]) / (item[3] - item[2]) if item[2] < 0.0: rect = pygame.Rect((bar_h_offset + f * (bar_width - 6), v_offset + 8), (6, 6)) else: rect = pygame.Rect((bar_h_offset, v_offset + 8), (f * bar_width, 6)) pygame.draw.rect(display, (255, 255, 255), rect) item = item[0] if item: # At this point has to be a str. surface = self._font_mono.render(item, True, (255, 255, 255)) display.blit(surface, (8, v_offset)) v_offset += 18 self._notifications.render(display) self.help.render(display) # ============================================================================== # -- FadingText ---------------------------------------------------------------- # ============================================================================== class FadingText(object): def __init__(self, font, dim, pos): self.font = font self.dim = dim self.pos = pos self.seconds_left = 0 self.surface = pygame.Surface(self.dim) def set_text(self, text, color=(255, 255, 255), seconds=2.0): text_texture = self.font.render(text, True, color) self.surface = pygame.Surface(self.dim) self.seconds_left = seconds self.surface.fill((0, 0, 0, 0)) self.surface.blit(text_texture, (10, 11)) def tick(self, _, clock): delta_seconds = 1e-3 * clock.get_time() self.seconds_left = max(0.0, self.seconds_left - delta_seconds) self.surface.set_alpha(500.0 * self.seconds_left) def render(self, display): display.blit(self.surface, self.pos) # ============================================================================== # -- HelpText ------------------------------------------------------------------ # ============================================================================== class HelpText(object): def __init__(self, font, width, height): # lines = __doc__.split('\n') lines = ['',''] self.font = font self.dim = (680, len(lines) * 22 + 12) self.pos = (0.5 * width - 0.5 * self.dim[0], 0.5 * height - 0.5 * self.dim[1]) self.seconds_left = 0 self.surface = pygame.Surface(self.dim) self.surface.fill((0, 0, 0, 0)) for n, line in enumerate(lines): text_texture = self.font.render(line, True, (255, 255, 255)) self.surface.blit(text_texture, (22, n * 22)) self._render = False self.surface.set_alpha(220) def toggle(self): self._render = not self._render def render(self, display): if self._render: display.blit(self.surface, self.pos) # ============================================================================== # -- CollisionSensor ----------------------------------------------------------- # ============================================================================== class CollisionSensor(object): def __init__(self, parent_actor, hud): self.sensor = None self._history = [] self._parent = parent_actor self._hud = hud world = self._parent.get_world() bp = world.get_blueprint_library().find('sensor.other.collision') self.sensor = world.spawn_actor(bp, carla.Transform(), attach_to=self._parent) # We need to pass the lambda a weak reference to self to avoid circular # reference. weak_self = weakref.ref(self) self.sensor.listen(lambda event: CollisionSensor._on_collision(weak_self, event)) def get_collision_history(self): history = collections.defaultdict(int) for frame, intensity in self._history: history[frame] += intensity return history @staticmethod def _on_collision(weak_self, event): self = weak_self() if not self: return actor_type = get_actor_display_name(event.other_actor) self._hud.notification('Collision with %r' % actor_type) impulse = event.normal_impulse intensity = math.sqrt(impulse.x**2 + impulse.y**2 + impulse.z**2) self._history.append((event.frame_number, intensity)) if len(self._history) > 4000: self._history.pop(0) # ============================================================================== # -- LaneInvasionSensor -------------------------------------------------------- # ============================================================================== # class LaneInvasionSensor(object): # def __init__(self, parent_actor, hud): # self.sensor = None # self._parent = parent_actor # self._hud = hud # world = self._parent.get_world() # bp = world.get_blueprint_library().find('sensor.other.lane_detector') # self.sensor = world.spawn_actor(bp, carla.Transform(), attach_to=self._parent) # # We need to pass the lambda a weak reference to self to avoid circular # # reference. # weak_self = weakref.ref(self) # self.sensor.listen(lambda event: LaneInvasionSensor._on_invasion(weak_self, event)) # @staticmethod # def _on_invasion(weak_self, event): # self = weak_self() # if not self: # return # text = ['%r' % str(x).split()[-1] for x in set(event.crossed_lane_markings)] # self._hud.notification('Crossed line %s' % ' and '.join(text)) # new lane invasion sensor for world class LaneInvasionSensor(object): def __init__(self, parent_actor, world): self.sensor = None self._parent = parent_actor self._world = world world = self._parent.get_world() bp = world.get_blueprint_library().find('sensor.other.lane_detector') self.sensor = world.spawn_actor(bp, carla.Transform(), attach_to=self._parent) # We need to pass the lambda a weak reference to self to avoid circular # reference. weak_self = weakref.ref(self) self.sensor.listen(lambda event: LaneInvasionSensor._on_invasion(weak_self, event)) @staticmethod def _on_invasion(weak_self, event): self = weak_self() if not self: return text = ['%r' % str(x).split()[-1] for x in set(event.crossed_lane_markings)] self._world.isCrossingLane = True self._world.lastCrossingFrame = 20 print("i m KG") # ============================================================================== # -- GnssSensor -------------------------------------------------------- # ============================================================================== class GnssSensor(object): def __init__(self, parent_actor): self.sensor = None self._parent = parent_actor self.lat = 0.0 self.lon = 0.0 world = self._parent.get_world() bp = world.get_blueprint_library().find('sensor.other.gnss') self.sensor = world.spawn_actor(bp, carla.Transform(carla.Location(x=1.0, z=2.8)), attach_to=self._parent) # We need to pass the lambda a weak reference to self to avoid circular # reference. weak_self = weakref.ref(self) self.sensor.listen(lambda event: GnssSensor._on_gnss_event(weak_self, event)) @staticmethod def _on_gnss_event(weak_self, event): self = weak_self() if not self: return self.lat = event.latitude self.lon = event.longitude # ============================================================================== # -- CameraManager ------------------------------------------------------------- # ============================================================================== class CameraManager(object): def __init__(self, parent_actor, hud): self.sensor = None self._surface = None self._parent = parent_actor self._hud = hud self._recording = False self._camera_transforms = [ carla.Transform(carla.Location(x=-5.5, z=2.8), carla.Rotation(pitch=-15)), carla.Transform(carla.Location(x=1.6, z=1.7))] self._transform_index = 1 self._sensors = [ ['sensor.camera.rgb', cc.Raw, 'Camera RGB'], ['sensor.camera.depth', cc.Raw, 'Camera Depth (Raw)'], ['sensor.camera.depth', cc.Depth, 'Camera Depth (Gray Scale)'], ['sensor.camera.depth', cc.LogarithmicDepth, 'Camera Depth (Logarithmic Gray Scale)'], ['sensor.camera.semantic_segmentation', cc.Raw, 'Camera Semantic Segmentation (Raw)'], ['sensor.camera.semantic_segmentation', cc.CityScapesPalette, 'Camera Semantic Segmentation (CityScapes Palette)'], ['sensor.lidar.ray_cast', None, 'Lidar (Ray-Cast)']] world = self._parent.get_world() bp_library = world.get_blueprint_library() for item in self._sensors: bp = bp_library.find(item[0]) if item[0].startswith('sensor.camera'): bp.set_attribute('image_size_x', str(hud.dim[0])) bp.set_attribute('image_size_y', str(hud.dim[1])) elif item[0].startswith('sensor.lidar'): bp.set_attribute('range', '5000') item.append(bp) self._index = None self.image_array = np.zeros((hud.dim[0],hud.dim[1],0)) def toggle_camera(self): self._transform_index = (self._transform_index + 1) % len(self._camera_transforms) self.sensor.set_transform(self._camera_transforms[self._transform_index]) def set_sensor(self, index, notify=True): index = index % len(self._sensors) needs_respawn = True if self._index is None \ else self._sensors[index][0] != self._sensors[self._index][0] if needs_respawn: if self.sensor is not None: self.sensor.destroy() self._surface = None self.sensor = self._parent.get_world().spawn_actor( self._sensors[index][-1], self._camera_transforms[self._transform_index], attach_to=self._parent) # We need to pass the lambda a weak reference to self to avoid # circular reference. weak_self = weakref.ref(self) self.sensor.listen(lambda image: CameraManager._parse_image(weak_self, image)) if notify: self._hud.notification(self._sensors[index][2]) self._index = index def next_sensor(self): self.set_sensor(self._index + 1) def toggle_recording(self): self._recording = not self._recording self._hud.notification('Recording %s' % ('On' if self._recording else 'Off')) def render(self, display): if self._surface is not None: display.blit(self._surface, (0, 0)) @staticmethod def _parse_image(weak_self, image): self = weak_self() if not self: return if self._sensors[self._index][0].startswith('sensor.lidar'): points = np.frombuffer(image.raw_data, dtype=np.dtype('f4')) points = np.reshape(points, (int(points.shape[0]/3), 3)) lidar_data = np.array(points[:, :2]) lidar_data *= min(self._hud.dim) / 100.0 lidar_data += (0.5 * self._hud.dim[0], 0.5 * self._hud.dim[1]) lidar_data = np.fabs(lidar_data) lidar_data = lidar_data.astype(np.int32) lidar_data = np.reshape(lidar_data, (-1, 2)) lidar_img_size = (self._hud.dim[0], self._hud.dim[1], 3) lidar_img = np.zeros(lidar_img_size) lidar_img[tuple(lidar_data.T)] = (255, 255, 255) self._surface = pygame.surfarray.make_surface(lidar_img) else: image.convert(self._sensors[self._index][1]) array = np.frombuffer(image.raw_data, dtype=np.dtype("uint8")) array = np.reshape(array, (image.height, image.width, 4)) array = array[:, :, :3] array = array[:, :, ::-1] self.image_array = array self._surface = pygame.surfarray.make_surface(array.swapaxes(0, 1)) if self._recording: image.save_to_disk('_out/%08d' % image.frame_number) class CarlaEnv(gym.Env): metadata = {'render.modes': ['human']} ACTION_NAMES = ["steer", "throttle", "brake", "reverse"] STEER_LIMIT_LEFT = -1.0 STEER_LIMIT_RIGHT = 1.0 THROTTLE_MIN = 0.0 THROTTLE_MAX = 1.0 BRAKE_MIN = 0.0 BRAKE_MAX = 1.0 REVERSE_MIN = 0.0 REVERSE_MAX = 1.0 VAL_PER_PIXEL = 255 # IP: 172.16.68.187 # SELF-HOST: 127.0.0.1 #172.16.68.140: LAPTOP HOST def __init__(self, host = '172.16.68.187', port = 2000, width = 640, height = 480, frame_to_store=3): print("init") self.host = host self.port = port self.width = width self.height = height self.reward = 0 self.action_space = spaces.Box(low=np.array([self.STEER_LIMIT_LEFT, self.THROTTLE_MIN, self.BRAKE_MIN, self.REVERSE_MIN]), high=np.array([self.STEER_LIMIT_RIGHT, self.THROTTLE_MAX, self.BRAKE_MAX, self.REVERSE_MAX]), dtype=np.float32 ) self.threshold = 2 high = np.array([ self.threshold * 2, np.finfo(np.float32).max, self.threshold * 2, np.finfo(np.float32).max]) self.observation_space = spaces.Box(0, self.VAL_PER_PIXEL, (height, width, 3), dtype=np.uint8) # simulation related variables. self.seed() # Frame to store self.frame_to_store = frame_to_store # Assign state self.state = [] for i in range(0,frame_to_store): #self.state.append(np.zeros((self.width,self.height,0))) self.state.append(np.zeros((self.height,self.width,0))) print(self.state) self.world = None # carla world as viewer # self.game_loop() self.thread = Thread(target=self.game_loop) # self.thread.daemon = True self.thread.start() self.action = [0,0,0,0] self.velocity = 0 self.distanceFromLane = 0 self.previous_step_time = None def __del__(self): self.close() def close(self): self.state = [] # print("close") pass def seed(self, seed=None): self.np_random, seed = seeding.np_random(seed) return [seed] def step(self, action): # print(action) # self.state = (1,2,1,2) # self.action = action # print("step") assert self.action_space.contains(action), "%r (%s) invalid"%(action, type(action)) while True: try: reward = self.get_reward() done = self.is_done() self.action = action obs = self.get_observation() except Exception as e: print(e) continue break return obs, reward, done, {} def reset(self): print("reset") while True: try: obs = self.get_observation() if self.world is not None: self.world.restartAtNewPos() time.sleep(3) except Exception as e: print(e) continue break return obs def render(self, mode='human', close=False): # print("render") # self.camera_manager.image_array while True: try: obs = self.get_observation() except Exception as e: print(e) continue break return obs # return self.world.camera_manager.image_array def get_observation(self): if self.world is not None: # print("self.world is not None") return self.world.camera_manager.image_array else: # print("zero") # return np.zeros((self.width,self.height,0)) return np.zeros((self.height,self.width,0)) def get_observation_array(self): return self.state def update_observation(self): if(len(self.state) >0): self.state.pop(0) self.state.append(self.get_observation()) def update_other_observation(self): if self.world is not None: self.velocity = self.world.velocity self.distanceFromLane = self.world.distanceFromLane self.angleFromLane = self.world.angleFromLane # sample for vehicles nearby # vehicles = self.world.world.get_actors().filter('vehicle.*') # if len(vehicles) > 1: # t = self.world.player.get_transform() # distance = lambda l: math.sqrt((l.x - t.location.x)**2 + (l.y - t.location.y)**2 + (l.z - t.location.z)**2) # vehicles = [(distance(x.get_location()), x) for x in vehicles if x.id != self.world.player.id] # for d, vehicle in sorted(vehicles): # if d > 200.0: # break # vehicle_type = get_actor_display_name(vehicle, truncate=22) # print('% 4dm %s' % (d, vehicle_type)) # print(self.distanceFromLane) def cal_acceleration_mag(self): accelerate_3dVector = self.world.player.get_acceleration() my_forward_vector = self.world.player.get_transform().get_forward_vector() # acceleration_mag cal by DOT PRODUCT acceleration_mag = accelerate_3dVector.x * my_forward_vector.x + accelerate_3dVector.y * my_forward_vector.y + accelerate_3dVector.z * my_forward_vector.z return acceleration_mag def cal_velocity_mag(self): velocity_3dVector = self.world.player.get_velocity() velocity_mag = math.sqrt(velocity_3dVector.x**2 + velocity_3dVector.y**2 + velocity_3dVector.z**2) return velocity_mag def get_lane_deviation_penalty(self, time_passed): lane_deviation_penalty = 0 lane_deviation_penalty = self.l( self.world.distanceFromLane, time_passed) return lane_deviation_penalty def l(self, lane_deviation, time_passed): #time_passed = update freq (step_time) lane_deviation_penalty = 0 if lane_deviation < 0: raise ValueError('Lane deviation should be positive') if time_passed is not None and lane_deviation > 200: # Tuned for Canyons spline - change for future maps lane_deviation_coeff = 0.1 lane_deviation_penalty = lane_deviation_coeff * time_passed * lane_deviation ** 2 / 100. lane_deviation_penalty =min(max(lane_deviation_penalty, -1e2), 1e2) return lane_deviation_penalty def get_reward(self): reward = 0 now = time.time() if self.previous_step_time != None: step_time = now - self.previous_step_time else: step_time=0 if self.is_collide == True: return -100 if self.world.isCrossingLane == True: return -1 reward += -self.get_lane_deviation_penalty(step_time) + 0.1*self.cal_velocity_mag() self.previous_step_time = now return reward def get_reward_v0(self): # init variables v_brake = 10 # Speed that the car should start braking v_max = 20 # Speed Limit theta_thresohold = 5 # Thresohold from the center of the lane reward = 0 # Rule 1: if v_t > v_brake AND action = brake: reward = reward + 1 if self.cal_velocity_mag() > v_brake and self.action[2] >= 0.5: reward = reward + 1 # Rule 2: if v_t > v_brake AND action != brake: reward = reward - 1 if self.cal_velocity_mag() > v_brake and self.action[2] < 0.5: reward = reward - 1 # Rule 3: if v_t < v_max AND action = accelerate: reward = reward + 1 (self.cal_acceleration_mag > 0 : Accelerate) if self.cal_velocity_mag() < v_max and self.cal_acceleration_mag() > 0: reward = reward + 1 # Rule 3: if v_t < v_max AND action = accelerate: reward = reward - 1 (self.cal_acceleration_mag <= 0 : Decelerate/maintain same speed) if self.cal_velocity_mag() < v_max and self.cal_acceleration_mag() <= 0: reward = reward - 1 # Rule 4: if Theta_t > theta_thresohold AND action = steer(positive value: Turn Right): reward = reward + 1 (Assume: Theta > Theta_Thresohold means drifting to the left) if self.world.angleFromLane > theta_thresohold and self.action[0] >= 0: reward = reward + 1 if self.world.angleFromLane > theta_thresohold and self.action[0] < 0: reward = reward - 1 if self.world.angleFromLane < -1*theta_thresohold and self.action[0] <= 0: reward = reward + 1 if self.world.angleFromLane < -1*theta_thresohold and self.action[0] > 0: reward = reward - 1 if self.is_collide == True: reward = - 100 #self.world.angleFromLane #self.world.distanceFromLane #self.reward = reward return reward def get_reward_v1(self): # init variables v_brake = 10 # Speed that the car should start braking v_max = 20 # Speed Limit theta_thresohold = 5 # Thresohold from the center of the lane if self.is_collide == True: return -100 if self.cal_velocity_mag() > v_brake and self.action[2] < 0.5: return -1 if self.cal_velocity_mag() < v_max and self.cal_acceleration_mag() <= 0: return -1 if self.world.angleFromLane > theta_thresohold and self.action[0] < 0: return -1 if self.world.angleFromLane < -1*theta_thresohold and self.action[0] > 0: return - 1 return abs(math.sin(math.radians(self.world.angleFromLane)))*self.cal_velocity_mag() def is_collide(self): if self.world is not None: if self.world.collision_sensor is not None: colhist = self.world.collision_sensor.get_collision_history() collision = [colhist[x + self.world.hud.frame_number - 200] for x in range(0, 200)] max_col = max(1.0, max(collision)) if max_col > 1.0: return True return False def is_done(self): if self.world is not None: if self.world is not None: colhist = self.world.collision_sensor.get_collision_history() collision = [colhist[x + self.world.hud.frame_number - 200] for x in range(0, 200)] max_col = max(1.0, max(collision)) if max_col > 1.0: return True return False def game_loop(self): # args args = type('', (), {})() args.host = self.host args.port = self.port args.width = self.width args.height = self.height args.filter = 'vehicle.audi.*' args.autopilot = False pygame.init() pygame.font.init() world = None try: client = carla.Client(args.host, args.port) client.set_timeout(2.0) client.load_world('/Game/Carla/Maps/Town01') display = pygame.display.set_mode( (args.width, args.height), pygame.HWSURFACE | pygame.DOUBLEBUF) hud = HUD(args.width, args.height) world = World(client.get_world(), hud, args.filter) # controller = KeyboardControl(world, args.autopilot) self.world = world self.hud = hud clock = pygame.time.Clock() while True: clock.tick_busy_loop(60) # if controller.parse_events(client, world, clock): # return for event in pygame.event.get(): if event.type == pygame.QUIT: return #print(self.action) self._control = carla.VehicleControl() self._control.steer = float(self.action[0]) self._control.throttle = float(self.action[1]) self._control.brake = float(self.action[2]) > 0.5 self._control.hand_brake = False self._control.reverse = float(self.action[3]) > 0.5 world.player.apply_control(self._control) world.tick(clock) world.render(display) pygame.display.flip() self.update_observation() self.update_other_observation() finally: if (world and world.recording_enabled): client.stop_recorder() if world is not None: world.destroy() pygame.quit() <file_sep>/Self-Driving/PPO-deepCarla/tensorflow_agent/common.py from __future__ import (absolute_import, division, print_function, unicode_literals) import glob import os from future.builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str, super, zip) import sys import logs import config as c log = logs.get_log(__name__) def get_throttle(actual_speed, target_speed): # TODO: Use a PID here desired_throttle = abs(target_speed / max(actual_speed, 1e-3)) desired_throttle = min(max(desired_throttle, 0.), 1.)<file_sep>/Self-Driving/baseline-model/preception/vision/traffic-sign/LeNetArch.py from tensorflow.contrib.layers import flatten def LeNet(x, weights, biases, apply_dropout): if apply_dropout is not None: print ("Training phase -> perform Dropout") else: print ("Evalutation phase -> not performing Dropout") layer = 0 # Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x12. conv1 = tf.nn.conv2d(x, weights[layer], strides=[1, 1, 1, 1], padding='VALID') + biases[layer] layer += 1 # Activation. conv1 = tf.nn.relu(conv1, name='act1') # Pooling. Input = 28x28x12. Output = 14x14x12. conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID') # Dropout conv1 = tf.cond(apply_dropout, lambda: tf.nn.dropout(conv1, keep_prob=0.8), lambda: conv1) # Layer 2: Convolutional. Output = 10x10x24. conv2 = tf.nn.conv2d(conv1, weights[layer], strides=[1, 1, 1, 1], padding='VALID') + biases[layer] layer += 1 # Activation. conv2 = tf.nn.relu(conv2, name='act2') # Pooling. Input = 10x10x24. Output = 5x5x24. conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID') # Dropout conv2 = tf.cond(apply_dropout, lambda: tf.nn.dropout(conv2, keep_prob=0.7), lambda: conv2) # Input = 14x14x12. Output = 7x7x12 = 588 conv1_1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID') shape = conv1_1.get_shape().as_list() conv1_1 = tf.reshape(conv1_1, [-1, shape[1] * shape[2] * shape[3]]) # Flatten conv2 Input = 5x5x24. Output = 600 shape = conv2.get_shape().as_list() conv2 = tf.reshape(conv2, [-1, shape[1] * shape[2] * shape[3]]) fc0 = tf.concat(1, [conv1_1, conv2]) # Layer 3: Fully Connected. Input = 588+600 = 1188. Output = 320. fc1 = tf.matmul(fc0, weights[layer]) + biases[layer] layer += 1 # Activation fc1 = tf.nn.relu(fc1) # Dropout fc1 = tf.cond(apply_dropout, lambda: tf.nn.dropout(fc1, keep_prob=0.6), lambda: fc1) logits = tf.matmul(fc1, weights[layer]) + biases[layer] return logits <file_sep>/freeCodeCamp-learning-note/Doom_DQN.py import tensorflow as tf import numpy as np from vizdoom import* import random import time from skimage import transform from collections import deque import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') # Create Env # Doom Env takes (1) configuration file => to handle all the options (size of frames, possible actions ... ) # (2) scenario file => Generates the correct scenario # 3 Possible actions [[0,0,1],[1,0,0],[0,1,0]] # Monster is spawned randomly somewhere along the opposite wall # 1 hit to kill a monster # Episode ends when monster is killed OR on timeout (300) # Reward: # +101 for killing the monster # -5 for missing # Episode ends after killing the monster or on timeout # Living reward = -1 def create_environment(): game = DoomGame() # Load configuration game.load_config("basic.cfg") # Load scenario game.set_doom_scenario_path("basic.wad") game.init() # Possible actions left = [1,0,0] right = [0,1,0] shoot = [0,0,1] possible_actions = [left,right, shoot] return game, possible_actions # Perform random action to test the environment def test_environment(): game = DoomGame() game.load_config("basic.cfg") game.set_doom_scenario_path("basic.wad") game.init() shoot = [0,0,1] left = [1,0,0] right = [0,1,0] actions = [shoot, left, right] episodes = 10 for i in range(episodes): game.new_episode() # while game is not finished while not game.is_episode_finished(): state = game.get_state() img = state.game_variables misc = state.game_variables action = random.choice(actions) print(action) reward = game.make_action(action) print("\treward:", reward) time.sleep(0.02) print("Result:", game.get_total_reward()) time.sleep(2) game.close() # Create the DoomGame env game, possible_actions = create_environment() # Define the Preprocessing Functions # Preprocess => so that we can reduce the complexity of our states -> reduce the computation time needed for training ''' Step 1 : Grayscale each frames Step 2 : Crop the screen Step 3 : Normalize pixel values Step 4 : Resize preprocessed frame ''' def preprocess_frame(frame): # Step 1: Grayscale (handled by the environment) # Step 2: Crop the screen cropped_frame = frame[30:-10,30:-30] # Step 3: Normalized frame normalized_frame = cropped_frame/255.0 # Step 4: Resize preprocess_frame = transform.resize(normalized_frame, [84,84]) return preprocess_frame # Define number of frame to be stacked stack_size = 4 # Initialize deque with ZERO-IMAGES # collections.deque() is a double-ended queue. Can be used to add or remove elements from both ends stacked_frames = deque([np.zeros((84,84),dtype=np.int) for i in range(stack_size)], maxlen=4) def stack_frames(stacked_frames, state, is_new_episode): frame = preprocess_frame(state) if is_new_episode: # Clear the stacked_frames stacked_frames = deque([np.zeros((84,84), dtype=np.int) for i in range(stack_size)], maxlen=4) # Put the frame into the stacked frame stacked_frames.append(frame) stacked_frames.append(frame) stacked_frames.append(frame) stacked_frames.append(frame) stacked_state = np.stack(stacked_frames, axis=2) else: stacked_frames.append(frame) stacked_state = np.stack(stacked_frames, axis=2) return stacked_state, stacked_frames ''' Hyperparameters set up ''' state_size = [84,84,4] action_size = game.get_available_buttons_size() # left, right, shoot learning_rate = 0.0002 total_episodes = 500 max_steps = 100 batch_size = 64 explore_start = 1.0 explore_stop = 0.01 decay_rate = 0.0001 # Q-Learning hyperparameters gamma = 0.95 # Memory Hyperparameters pretrain_length = batch_size #num of experiences stored in the memory when initialized for the first time memory_size = 1000000 #num of experience that memory can keep training = True episode_render = False ''' Create Deep Q-Learning Neural Network Model ''' class DQNetwork: def __init__(self, state_size, action_size, learning_rate, name = 'DQNetwork'): self.state_size = state_size self.action_size = action_size self.learning_rate = learning_rate with tf.variable_scope(name): # Define placeholders # state_size: we take each elements of state_size in tuple and like [None, 84,84,4] self.inputs = tf.placeholder(tf.float32, [None, *state_size], name="inputs") self.actions = tf.placeholder(tf.float32, [None, 3], name="action") self.target_Q = tf.placeholder(tf.float32, [None], name="target") # Conv_layer1 self.conv1 = tf.layers.conv2d(intput = self.inputs, filters=32, kernel_size=[8,8], strides=[4,4], padding="VALID",kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(), name = 'conv1') self.conv1_batchnorm = tf.layers.batch_normalization(self.conv1, training = True, epsilon = 1e-5, name="batch_norm1") self.conv1_out = tf.nn.elu(self.conv1_batchnorm, name="conv1_out") # output: [20,20,32] # Conv_layer2 self.conv2 = tf.layers.conv2d(intput = self.inputs, filters=64, kernel_size=[4,4], strides=[2,2], padding="VALID",kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(), name = 'conv2') self.conv2_batchnorm = tf.layers.batch_normalization(self.conv2, training = True, epsilon = 1e-5, name="batch_norm2") self.conv2_out = tf.nn.elu(self.conv2_batchnorm, name="conv2_out") # output: [9,9,64] # Conv_layer3 self.conv3 = tf.layers.conv2d(intput = self.inputs, filters=128, kernel_size=[4,4], strides=[2,2], padding="VALID",kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(), name = 'conv3') self.conv3_batchnorm = tf.layers.batch_normalization(self.conv3, training = True, epsilon = 1e-5, name="batch_norm3") self.conv3_out = tf.nn.elu(self.conv2_batchnorm, name="conv3_out") # output: [3,3,128] # Flatten self.flatten = tf.layers.flatten(self.conv3_out) # Fully Connected self.fc = tf.layers.dense(inputs = self.flatten, units = 512, activation=tf.nn.elu, kernel_initializer=tf.contrib.layers.xavier_initializer(), name='fc1') # Output layer (output: 3. One Q-value for each actions) self.output = tf.layers.dense(input = self.fc, kernel_initializer=tf.contrib.layers.xavier_initializer(), unit=3, activation=None) # Q-Value self.Q = tf.reduce_sum(tf.multiply(self.output, self.actions), axis=1) # Loss : Sum(Qtarget - Q)^2 self.loss = tf.reduce_mean(tf.square(self.target_Q - self.Q)) # Optimizer self.optimizer = tf.train.RMSPropOptimizer(self.learning_rate).minimize(self.loss) # Reset Graph tf.reset_default_graph() DQNetwork = DQNetwork(state_size, action_size, learning_rate) class Memory(): def __init__(self, max_size): self.buffer = deque(maxlen= max_size) def add(self, experience): self.buffer.append(experience) def sample(self, batch_size): buffer_size = len(self.buffer) index = np.random.choice(np.arrange(buffer_size), size=batch_size, replace=False) return [self.buffer[i] for i in index] memory = Memory(max_size= memory_size) # Render new Env game.new_episode() for i in range(pretrain_length): if i == 0: # For the first step # Need a state state = game.get_state().screen_buffer state, stacked_frames = stack_frames(stacked_frames, state, True) # Random Action action = random.choice(possible_actions) # Get Rewards reward = game.make_action(action) # Check if episode is finished done = game.is_episode_finished if done: # Episode finished next_state = np.zeros(state.shape) # Add experience to memory memory.add((state, action, reward, next_state, done)) # Start a new episode game.new_episode() # get state state = game.get_state().screen_buffer state, stacked_frames = stack_frames(stacked_frames, state, True) else: # Episode not finished next_state = game.get_state().screen_buffer next_state, stacked_frames = stack_frames(stacked_frames, next_state, False) # Add experience to memory memory.add((state, action, reward, next_state, done)) # Update state state = next_state # Set up Tensorboard # set up Tensorboard writer writer = tf.summary.FileWriter("/tensorboard/dqn/1") # Losses tf.summary.scalar("Loss", DQNetwork.loss) # write output write_op = tf.summary.merge_all() # Train Agent ''' (1) Init weight (2) Init Env (3) Init Decay rate FOR-LOOP (Episode) for each episode Make new episode Set step to ZERO Observe the first state s_0 While-Loop (while below max_steps): Increase decay_rate With prob epsilon: select a random action a_t, with prob (1-epsilon) select a_t = argmax_a Q(s_t, a) Execute action a_t, observe reward r_t+1 and get new state s_t+1 Store Transition (to Experience Buffer) Sample random mini-batch Set Predicted_next_state_Q_value = r (terminate state: episode ends) OR Predicted_next_state_Q_value = r + Decay_rate(max_a: Q(next_state, next_state_all_possible_action) Make Gradient Descent Step with Loss: (Predict_next_state_Q_value - Current_state_Q_value) power to 2 END-WHILE END-FOR ''' def predict_action(explore_start, explore_stop, decay_rate, decay_step, state, actions): # Epsilon Greedy # Random Number exp_exp_tradeoff = np.random.rand() explore_prob = explore_stop + (explore_start - explore_stop)*np.exp(-decay_rate*decay_step) if (explore_prob > exp_exp_tradeoff): # Make random action (exploration) action = random.choice(possible_actions) else: # Get action from Q-network (exploitation) # Estimate the Qs value state Qs = sess.run(DQNetwork.output, feed_dict={DQNetwork.inputs: state.reshape((1, *state.shape))}) # Take Biggest Q value -> Best action choice = np.argmax(Qs) action = possible_actions[int(choice)] return action, explore_prob # Training and Saving # Saver will help us to save our model saver = tf.train.Saver() if training == True: with tf.Session() as sess: # Init the variables sess.run(tf.global_variables_initializer()) # Init decay rate decay_step = 0 game.init() for episode in range(total_episodes): # set step to 0 step = 0 episode_rewards = [] # Init rewards of the episode # New episode game.new_episode() # Get state state = game.get_state().screen_buffer # Stack Frame state, stacked_frames = stack_frames(stacked_frames, state, True) while step < max_steps: # Update step step += 1 # Increase decay_step decay_step += 1 # Predict action to take and exe action action, explore_prob = predict_action(explore_start, explore_stop, decay_rate, decay_step, state, possible_actions) # Exe the action reward = game.make_action(action) # Check if episode is finished done = game.is_episode_finished() # Append rewards episode_rewards.append(reward) # If game finished if done: next_state = np.zeros((84,84), dtype=np.int) next_state, stacked_frames = stack_frames(stacked_frames, next_state, False) # set step to max_steps to end episode step = max_steps # Get total_reward total_reward = np.sum(episode_rewards) print('Episode: {}'.format(episode), 'Total reward: {}'.format(total_reward), 'Training loss: {:.4f}'.format(loss), 'Explore P: {:.4f}'.format(explore_prob)) memory.add((state, action, reward, next_state, done)) else: <file_sep>/Self-Driving/baseline-model/preception/vision/traffic-sign/imagePreprocess.py from skimage import exposure import cv2 import numpy as np def pre_processing_single_img(img): img_y = cv2.cvtColor(img, (cv2.COLOR_BGR2YUV))[:,:,0] img_y = (img_y / 255.).astype(np.float32) #img_y = exposure.adjust_log(img_y) img_y = (exposure.equalize_adapthist(img_y,) - 0.5) img_y = img_y.reshape(img_y.shape + (1,)) return img_y def pre_processing(X): print(X.shape) X_out = np.empty((X.shape[0],X.shape[1],X.shape[2],1)).astype(np.float32) print(X_out.shape) for idx, img in enumerate(X): X_out[idx] = pre_processing_single_img(img) return X_out def save_preprocessed_data(X,y,path): d = {"features": X.astype('uint8'), "labels": y} with open(path, 'wb') as handle: pickle.dump(d, handle, protocol=pickle.HIGHEST_PROTOCOL)<file_sep>/Self-Driving/baseline-model/preception/vision/traffic-sign/dataAugmentation.py from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img import matplotlib.pyplot as plt import random import cv2 # For reference: This is a great tool https://github.com/albu/albumentations datagen = ImageDataGenerator( rotation_range=17, width_shift_range=0.1, height_shift_range=0.1, shear_range=0.3, zoom_range=0.15, horizontal_flip=False, dim_ordering='tf', fill_mode='nearest') # Usage: datagen.fit(X_test_,augment=True,seed=0) def augmentation(X, y): for X_batch, y_batch in datagen.flow(X, y, batch_size = X.shape[0], shuffle=False): print("X_batch shape: ", X_batch.shape) X_aug = X_batch.astype('uint8') y_aug = y_batch # Not sure how this works (but I don't think it will work) #img_out_rgb = cv2.cvtColor(X_batch[0].astype('float32'), cv2.COLOR_BGR2RGB) #cv2.imwrite("out.jpg", img_out_rgb) return X_aug, y_aug def motion_blur(X, y, kernel_size): print("input X shape: ", X.shape) X_out = np.empty((X.shape)).astype('uint8') print("X_out shape: ", X_out.shape) kernel_motion_blur = np.zeros((kernel_size, kernel_size)) kernel_motion_blur[int((size - 1) / 2), :] = np.ones(kernel_size) kernel_motion_blur = kernel_motion_blur / kernel_size for idx, img in enumerate(X): X_out[idx] = cv2.filter2D(img, -1, kernel_motion_blur) return X_out, y def save_augmented_data(X,y,path): d = {"features": X.astype('uint8'), "labels": y} with open(path, 'wb') as handle: pickle.dump(d, handle, protocol=pickle.HIGHEST_PROTOCOL)<file_sep>/Self-Driving/baseline-model/env/carla_env2.py from __future__ import print_function import carla from carla import ColorConverter as cc import os import glob import sys import time import numpy as np import weakref import random try: sys.path.append(glob.glob('**/carla-*%d.%d-%s.egg' % ( sys.version_info.major, sys.version_info.minor, 'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0]) except IndexError: pass import gym from gym import error, spaces, utils from gym.utils import seeding import cv2 class CarlaEnv(object): ACTION_NAMES = ["steer", "throttle", "brake", "reverse"] STEER_LIMIT_LEFT = -1.0 STEER_LIMIT_RIGHT = 1.0 THROTTLE_MIN = 0.0 THROTTLE_MAX = 1.0 BRAKE_MIN = 0.0 BRAKE_MAX = 1.0 REVERSE_MIN = 0.0 REVERSE_MAX = 1.0 VAL_PER_PIXEL = 255 def __init__(self, host='127.0.0.1', port=2000, isSave=False, headless=False): print("__init__") self.isSave = isSave self.host, self.port = host, port self.width = 1920 self.height = 1080 self.steps = 0 self.num_episodes = 0 self.action_space = spaces.Box(low=np.array([self.STEER_LIMIT_LEFT, self.THROTTLE_MIN, self.BRAKE_MIN, self.REVERSE_MIN]), high=np.array([self.STEER_LIMIT_RIGHT, self.THROTTLE_MAX, self.BRAKE_MAX, self.REVERSE_MAX]), dtype=np.float32 ) self.player = None self.image_array = np.zeros((self.height,self.width,0)) self.lidar_array = np.zeros((self.height,self.width,0)) self._make_carla_client(self.host, self.port) self._get_world() self._make_vehicle() def step(self, action): self._control = carla.VehicleControl() self._control.steer = float(action[0]) self._control.throttle = float(action[1]) self._control.brake = float(action[2]) > 0.5 self._control.hand_brake = False self._control.reverse = float(action[3]) > 0.5 self.player.apply_control(self._control) obs = self.get_observation() return obs, 0.1, False, {} def render(self): obs = self.get_observation() return obs def reset(self): pass def disconnect(self): pass def get_observation(self): return self.image_array def get_camera_image(self): return self.image_array def get_lidar_image(self): return self.lidar_array def close(self): self.player.destroy() self.camera.destroy() self.lidar.destroy() def _make_carla_client(self, host, port): print("_make_carla_client") self._client = carla.Client(host, port) self._client.set_timeout(2.0) # while True: # try: # self._client = carla.Client(host, port) # self._client.set_timeout(2.0) # except: # print("Connection error") # time.sleep(1) def _get_world(self): print("_get_world") self.world = self._client.get_world() self.map = self.world.get_map() def _make_vehicle(self): print("_make_vehicle") print(self.world.get_blueprint_library().filter("vehicle.audi.*")) blueprint = random.choice(self.world.get_blueprint_library().filter("vehicle.audi.*")) blueprint.set_attribute('role_name', 'hero') if blueprint.has_attribute('color'): color = random.choice(blueprint.get_attribute('color').recommended_values) blueprint.set_attribute('color', color) if self.player is None: spawn_points = self.map.get_spawn_points() spawn_point = spawn_points[0] # spawn_point = random.choice(spawn_points) if spawn_points else carla.Transform() self.player = self.world.try_spawn_actor(blueprint, spawn_point) #create camera attach on vehicle self._sensors = [ ['sensor.camera.rgb', cc.Raw, 'Camera RGB'], ['sensor.camera.depth', cc.Raw, 'Camera Depth (Raw)'], ['sensor.camera.depth', cc.Depth, 'Camera Depth (Gray Scale)'], ['sensor.camera.depth', cc.LogarithmicDepth, 'Camera Depth (Logarithmic Gray Scale)'], ['sensor.camera.semantic_segmentation', cc.Raw, 'Camera Semantic Segmentation (Raw)'], ['sensor.camera.semantic_segmentation', cc.CityScapesPalette, 'Camera Semantic Segmentation (CityScapes Palette)'], ['sensor.lidar.ray_cast', None, 'Lidar (Ray-Cast)']] bp_library = self.world.get_blueprint_library() for item in self._sensors: bp = bp_library.find(item[0]) if item[0].startswith('sensor.camera'): bp.set_attribute('image_size_x', str(self.width)) bp.set_attribute('image_size_y', str(self.height)) elif item[0].startswith('sensor.lidar'): bp.set_attribute('range', '5000') #camera bp = self.world.get_blueprint_library().find(self._sensors[0][0]) self.camera = self.world.spawn_actor(bp, carla.Transform(carla.Location(x=1.6, z=1.7)), attach_to=self.player) weak_self = weakref.ref(self) self.camera.listen(lambda image: self._parse_rgb_image(weak_self, image)) #lidar bp = self.world.get_blueprint_library().find(self._sensors[6][0]) self.lidar = self.world.spawn_actor(bp, carla.Transform(carla.Location(x=1.6, z=1.7)), attach_to=self.player) weak_self = weakref.ref(self) self.lidar.listen(lambda image: self._parse_lidar_image(weak_self, image)) @staticmethod def _parse_rgb_image(weak_self, image): self = weak_self() if not self: return image.convert(self._sensors[0][1]) array = np.frombuffer(image.raw_data, dtype=np.dtype("uint8")) array = np.reshape(array, (image.height, image.width, 4)) array = array[:, :, :3] array = array[:, :, ::-1] self.image_array = array if self.isSave: image.save_to_disk('_out/%08d' % image.frame_number) print("_parse_rgb_image") @staticmethod def _parse_lidar_image(weak_self, image): self = weak_self() if not self: return points = np.frombuffer(image.raw_data, dtype=np.dtype('f4')) points = np.reshape(points, (int(points.shape[0]/3), 3)) lidar_data = np.array(points[:, :2]) lidar_data *= min(self.width, self.height) / 100.0 lidar_data += (0.5 * self.width, 0.5 * self.height) lidar_data = np.fabs(lidar_data) lidar_data = lidar_data.astype(np.int32) lidar_data = np.reshape(lidar_data, (-1, 2)) lidar_img_size = (self.width, self.height, 3) lidar_img = np.zeros(lidar_img_size) lidar_img[tuple(lidar_data.T)] = (255, 255, 255) self.lidar_array = lidar_img lidar_img = lidar_img.swapaxes(0, 1) if self.isSave: cv2.imwrite('_out/lidar%08d.png' % image.frame_number, lidar_img) # image.save_to_disk('_out/lidar%08d' % image.frame_number)
404667d70009a4a4867c46857acb8742783a2720
[ "Python" ]
15
Python
sanwong15/RL
9ad4740efd46fa50150482f1e837eed54c45ae68
9a39da1cd01abf0cb4c9185cff6e149c377d2963
refs/heads/master
<repo_name>Sha1989/TestTwoBranch<file_sep>/test-output/old/Suite/Sanity Suite Two.properties [SuiteResult context=Sanity Suite Two]<file_sep>/src/main/java/com/property/data/OR.properties searchField=//input[contains(@class, 'gLFyf gsfi')]<file_sep>/target/classes/META-INF/maven/TestMavenProject/TestMavenProject/pom.xml <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>TestMavenProject</groupId> <artifactId>TestMavenProject</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>TestMavenProject</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.aventstack/extentreports --> <dependency> <groupId>com.aventstack</groupId> <artifactId>extentreports</artifactId> <version>3.0.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java --> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>3.14.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.testng/testng --> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.14.3</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.8</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>com.relevantcodes</groupId> <artifactId>extentreports</artifactId> <version>2.41.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- https://mvnrepository.com/artifact/io.appium/java-client --> <dependency> <groupId>io.appium</groupId> <artifactId>java-client</artifactId> <version>5.0.4</version> </dependency> <!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured --> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>3.3.0</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/io.rest-assured/json-schema-validator --> <dependency> <groupId>io.rest-assured</groupId> <artifactId>json-schema-validator</artifactId> <version>4.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.json/json --> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20190722</version> </dependency> <!-- https://mvnrepository.com/artifact/com.aventstack/extentreports --> <dependency> <groupId>com.aventstack</groupId> <artifactId>extentreports</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>io.rest-assured</groupId> <artifactId>json-path</artifactId> <version>4.3.0</version> <scope>test</scope> </dependency> <dependency> <groupId>io.rest-assured</groupId> <artifactId>spring-mock-mvc</artifactId> <version>4.3.0</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/io.github.bonigarcia/webdrivermanager --> <dependency> <groupId>io.github.bonigarcia</groupId> <artifactId>webdrivermanager</artifactId> <version>3.8.1</version> </dependency> <!-- https://mvnrepository.com/artifact/net.rcarz/jira-client --> <dependency> <groupId>net.rcarz</groupId> <artifactId>jira-client</artifactId> <version>0.5</version> </dependency> </dependencies> </project> <file_sep>/src/test/java/com/common/pkg/Element.java package com.common.pkg; import java.util.ArrayList; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import com.main.utilty.Logz; public class Element { private By by; private WebDriver driver; private WebElement element; private WebDriverWait wait; public Element(WebDriver driver, WebElement e) { this.driver = driver; wait = new WebDriverWait(driver, 10); this.element = e; } public WebElement element() { return element; } public Element sendKeys(String val) { this.element().sendKeys(val); return this; } public Element click() { this.element().click(); return this; } public Element getText() { this.element.getText(); return this; } public Element(WebDriver driver, ExpectedCondition<?> exp, int... delay) throws Exception { this.driver = driver; try { wait = new WebDriverWait(driver, 10); this.element = (WebElement) wait.until(exp); } catch (Exception e) { this.element = null; Logz.debug("element not located: " + by.toString()); Logz.debug(e.getMessage()); } } public Element(WebDriver driver, By by) throws Exception { this.driver = driver; this.by = by; try { wait = new WebDriverWait(driver, 10); this.element = wait.until(ExpectedConditions.presenceOfElementLocated(by)); Logz.debug("Element is found."); } catch (Exception e) { Logz.debug("Element is not found."); Logz.message(e.getMessage()); } } } <file_sep>/src/test/java/com/test/page/TestOnePage.java package com.test.page; import static com.common.pkg.Locator.getLocator; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import com.common.pkg.Element; import com.common.pkg.Locator.Loc; import com.common.pkg.PageObject; import com.main.utilty.Logz; public class TestOnePage extends PageObject { public TestOnePage(WebDriver driver) { super(driver); } public String searchFieldLocator = prop.getProperty("searchField"); public void enterDataSearchField() throws Exception { Logz.message("searchFieldLocator:- " + searchFieldLocator); $(Loc.XPATH, searchFieldLocator).click(); $findElements(ExpectedConditions.presenceOfAllElementsLocatedBy($By(Loc.XPATH, searchFieldLocator)), 5).get(0).sendKeys("Text "); $getText(ExpectedConditions.presenceOfElementLocated($By(Loc.XPATH, searchFieldLocator)), 5); $findElements(ExpectedConditions.presenceOfAllElementsLocatedBy($By(Loc.XPATH, searchFieldLocator)), 5).get(0).getText(); $(ExpectedConditions.presenceOfElementLocated($By(Loc.XPATH, searchFieldLocator)), 5).sendKeys("Test"); $getText($findElements(ExpectedConditions.presenceOfAllElementsLocatedBy($By(Loc.XPATH, searchFieldLocator)), 5).get(0)); $(Loc.XPATH, searchFieldLocator).sendKeys("Test"); } public void message() throws Exception { Logz.message("Success"); } }
7dbea91e8421851ac876aebe8677efd75523e15d
[ "Java", "Maven POM", "INI" ]
5
INI
Sha1989/TestTwoBranch
22c4da529a086263564c397833e16894209b2516
c0950a428e46587adac8e6f081754aec7b5e83f8
refs/heads/master
<repo_name>mremondi/Radial<file_sep>/Radial/Storage/EventRepository.swift // // EventRepository.swift // Radial // // Created by <NAME> on 5/31/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import CoreData import UIKit class EventRepository{ func createEvent(eventData: [String]){ guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } let managedContext = appDelegate.persistentContainer.viewContext let entity = NSEntityDescription.entity(forEntityName: "Event", in: managedContext)! let eventCache = NSManagedObject(entity: entity, insertInto: managedContext) eventCache.setValue(eventData[0], forKeyPath: "title") eventCache.setValue(eventData[1], forKeyPath: "notes") eventCache.setValue(eventData[2], forKeyPath: "startTime") eventCache.setValue(eventData[3], forKeyPath: "endTime") eventCache.setValue(eventData[4], forKey: "type") do { try managedContext.save() } catch let error as NSError { print("Could not save. \(error), \(error.userInfo)") } } func getEvents(for date: Date) -> [EventModel] { let allEvents = getAllEvents() var selectedDateEvents: [EventModel] = [] let selectedDate = date let selectedDateCalendar = Calendar.current let selectedDateComponents = selectedDateCalendar.dateComponents([.year, .month, .day], from: selectedDate) let selectedDateYear = selectedDateComponents.year let selectedDateMonth = selectedDateComponents.month let selectedDateDay = selectedDateComponents.day for event in allEvents{ let date = event.startTime let calendar = Calendar.current let components = calendar.dateComponents([.year, .month, .day], from: date) let year = components.year let month = components.month let day = components.day if (selectedDateYear == year && selectedDateMonth == month && selectedDateDay == day){ selectedDateEvents.append(event) } } return selectedDateEvents } func getAllEvents() -> [EventModel] { let appDelegate = UIApplication.shared.delegate as! AppDelegate let managedContext = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Event") do { let managedEvents = try managedContext.fetch(fetchRequest) let events = self.mapManagedEvents(managedEvents: managedEvents) return events } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } return [] } private func mapManagedEvents(managedEvents: [NSManagedObject]) -> [EventModel]{ var events: [EventModel] = [] managedEvents.forEach { let managedEvent = $0 let startTime = dateFromString(dateString: managedEvent.value(forKey: "startTime") as! String) let endTime = dateFromString(dateString: managedEvent.value(forKey: "endTime") as! String) if let type = managedEvent.value(forKey: "type") as? String{ let event = EventModel(title: managedEvent.value(forKey: "title") as! String, notes: managedEvent.value(forKey: "notes") as! String, startTime: startTime, endTime: endTime, type: type) events.append(event) } else { let event = EventModel(title: managedEvent.value(forKey: "title") as! String, notes: managedEvent.value(forKey: "notes") as! String, startTime: startTime, endTime: endTime, type: "") events.append(event) } } return events } private func dateFromString(dateString: String) -> Date{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy HH:mm" if let date = dateFormatter.date(from: dateString){ return date } return Date() } } <file_sep>/Radial/Models/Event.swift // // Event.swift // Radial // // Created by <NAME> on 5/31/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation struct EventModel{ let title: String let notes: String let startTime: Date let endTime: Date let type: String } <file_sep>/Radial/Utils/StyleKit.swift // // StyleKit.swift // Radial // // Created by <NAME> on 5/31/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import UIKit /// This struct contains style information and tools for the app. struct StyleKit { struct Font{ static let thin = "AppleSDGothicNeo-Thin" static let regular = "AppleSDGothicNeo-Regular" static let semiBold = "AppleSDGothicNeo-SemiBold" static let bold = "AppleSDGothicNeo-Bold" } // Main theme colors for the app struct Colors { static let clockBackground = UIColor(red: 52/255.0, green: 52/255.0, blue: 52/255.0, alpha: 1.0) static let activeBlue = UIColor(red: 118/255.0,green: 190/255.0, blue: 255/255.0, alpha: 1.0) static let inActiveBlue = UIColor(red: 173/255.0, green: 214/255.0, blue: 255/255.0, alpha: 1.0) } } <file_sep>/Radial/UI/AddEvent/AddEventInteractor.swift // // AddEventInteractor.swift // Radial // // Created by <NAME> on 5/31/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation class AddEventInteractor{ func createEvent(eventData: [String]){ let repository = EventRepository() repository.createEvent(eventData: eventData) } } <file_sep>/Radial/UI/Home/HomeInteractor.swift // // HomeInteractor.swift // Radial // // Created by <NAME> on 5/31/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation class HomeInteractor{ func getEvents(for date: Date) -> [EventModel]{ let repository = EventRepository() return repository.getEvents(for: date) } func getAllEvents() -> [EventModel]{ let repository = EventRepository() return repository.getAllEvents() } } <file_sep>/Radial/UI/Home/HomeView.swift // // HomeView.swift // Radial // // Created by <NAME> on 5/31/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import UIKit protocol HomeViewDelegate{ func newDateSelected(date: Date) } class HomeView: UIView{ var delegate: HomeViewDelegate? var selectedDate: Date? var dateTextField: UITextField! var clockView: ClockView! init() { super.init(frame: .zero) self.backgroundColor = StyleKit.Colors.clockBackground initViews() initConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initViews(){ let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(HomeView.dismissKeyboard)) tap.cancelsTouchesInView = false self.addGestureRecognizer(tap) dateTextField = UITextField() dateTextField.delegate = self clockView = ClockView() [dateTextField, clockView].forEach{ addSubview($0) } } func initConstraints(){ dateTextField.anchor(top: safeAreaLayoutGuide.topAnchor, leading: leadingAnchor, bottom: nil, trailing: trailingAnchor, padding: .init(top: 0, left: 0, bottom: 0, right: 0), size: .init(width: 0, height: 60)) dateTextField.backgroundColor = .white dateTextField.textAlignment = .center dateTextField.text = "TODAY" clockView.anchorCenter(to: self) clockView.anchor(top: nil, leading: nil, bottom: nil, trailing: nil, size: .init(width: 400, height: 400)) } func configureView(events: [EventModel]){ clockView.redraw(events: events) UIView.animate(withDuration: 0.5, delay:0, options: [.repeat, .autoreverse], animations: { UIView.setAnimationRepeatCount(2) self.clockView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) }, completion: {completion in self.clockView.transform = CGAffineTransform(scaleX: 1, y: 1) }) } @objc func dismissKeyboard() { self.endEditing(true) // todo: move this to another method when we have a submit button if let date = self.selectedDate { delegate?.newDateSelected(date: date) } } } extension HomeView: UITextFieldDelegate{ func textFieldDidBeginEditing(_ textField: UITextField) { let datePickerView: UIDatePicker = UIDatePicker() datePickerView.datePickerMode = UIDatePickerMode.date dateTextField.inputView = datePickerView datePickerView.addTarget(self, action: #selector(HomeView.datePicked), for: UIControlEvents.valueChanged) } @objc func datePicked(sender: UIDatePicker) { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMM dd yyyy" dateTextField.text = dateFormatter.string(from: sender.date) self.selectedDate = sender.date } } <file_sep>/Radial/UI/Home/ClockView.swift // // ClockView.swift // Radial // // Created by <NAME> on 5/31/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import UIKit class ClockView: UIView { var events: [EventModel] = [] init() { super.init(frame: .zero) backgroundColor = .clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func redraw(events: [EventModel]){ self.events = events self.setNeedsDisplay() } override func draw(_ rect: CGRect) { drawCircle() if (events.count > 0){ drawEvents() } } private func drawCircle(){ let width = bounds.width let height = bounds.height let centerPoint = CGPoint(x: width/2, y: height/2) let radius = CGFloat(150) let circleBox = CGRect(x: centerPoint.x - radius, y: centerPoint.y - radius, width: radius*2, height: radius*2) let path = UIBezierPath(ovalIn: circleBox) UIColor.white.setFill() path.fill() path.stroke() } private func drawEvents(){ let width = bounds.width let height = bounds.height let centerPoint = CGPoint(x: width/2, y: height/2) let radius = CGFloat(150) for event in events{ let startAngle = convertTimeToAngle(time: event.startTime) let endAngle = convertTimeToAngle(time: event.endTime) let arc = UIBezierPath() arc.move(to: centerPoint) arc.addArc(withCenter: centerPoint, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) UIColor.red.setFill() arc.fill() } } private func convertTimeToAngle(time: Date) -> CGFloat{ // number of minutes in a 24 hour clock print(time) let totalClockMinutes = 1440.0 let totalDegrees = 360.0 let hour = getHour(time: time) let minute = getMinute(time: time) // map hours and minutes let hoursPlusMinutes = Double(hour) * 60.0 + Double(minute) let angle = hoursPlusMinutes / totalClockMinutes * totalDegrees return degreesToRadians(degrees: angle) } private func degreesToRadians(degrees: Double) -> CGFloat{ return CGFloat(((.pi * degrees) / 180.0)) } private func getHour(time: Date) -> Int{ let calendar = Calendar.current let components = calendar.dateComponents([.hour], from: time) return components.hour! } private func getMinute(time: Date) -> Int{ let calendar = Calendar.current let components = calendar.dateComponents([.minute], from: time) return components.minute! } } <file_sep>/Radial/Factories/DependencyContainer.swift // // DependencyContainer.swift // Radial // // Created by <NAME> on 5/31/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation class DependencyContainer { } extension DependencyContainer: ViewControllerFactory{ func makeHomeViewController(navigator: Navigator) -> HomeViewController { return HomeViewController(navigator: navigator as! HomeViewController.HomeNavigation, view: HomeView(), interactor: HomeInteractor()) } func makeAddEventViewController(navigator: Navigator) -> AddEventViewController { return AddEventViewController(navigator: navigator as! AddEventViewController.AddEventNavigation, view: AddEventView(), interactor: AddEventInteractor()) } } <file_sep>/Radial/UI/AddEvent/AddEventViewController.swift // // AddEventViewController.swift // Radial // // Created by <NAME> on 5/31/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import UIKit class AddEventViewController: UIViewController{ typealias AddEventNavigation = HomeNavigator let navigator: AddEventNavigation! let addEventView: AddEventView! let interactor: AddEventInteractor! init(navigator: AddEventNavigation, view: AddEventView, interactor: AddEventInteractor) { self.navigator = navigator self.addEventView = view self.interactor = interactor super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(addEventView) self.addEventView.fillSuperview() navigationItem.title = "Add Event" navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelTapped)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneTapped)) } @objc func cancelTapped(){ navigator.back() } @objc func doneTapped(){ if self.addEventView.getEventData().count == 4{ interactor.createEvent(eventData: self.addEventView.getEventData()) navigator.toHomeViewController() } } } <file_sep>/Radial/Factories/ViewControllerFactory.swift // // ViewControllerFactory.swift // Radial // // Created by <NAME> on 5/31/18. // Copyright © 2018 <NAME>. All rights reserved. // protocol ViewControllerFactory{ func makeHomeViewController(navigator: Navigator) -> HomeViewController func makeAddEventViewController(navigator: Navigator) -> AddEventViewController } <file_sep>/Radial/UI/AddEvent/AddEventView.swift // // AddEventView.swift // Radial // // Created by <NAME> on 5/31/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import UIKit class AddEventView: UIView{ var titleTextField: UITextField! var notesTextView: UITextView! var selectTimeView: UIView! var startTimeTextField: UITextField! var endTimeTextField: UITextField! init() { super.init(frame: .zero) self.backgroundColor = StyleKit.Colors.clockBackground initViews() initConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func initViews(){ titleTextField = UITextField() notesTextView = UITextView() notesTextView.delegate = self startTimeTextField = UITextField() startTimeTextField.delegate = self endTimeTextField = UITextField() endTimeTextField.delegate = self [titleTextField, notesTextView, startTimeTextField, endTimeTextField].forEach{ addSubview($0) } } private func initConstraints(){ titleTextField.anchor(top: topAnchor, leading: leadingAnchor, bottom: nil, trailing: trailingAnchor, padding: .init(top: 90, left: 0, bottom: 0, right: 0), size: .init(width: 0, height: 60)) titleTextField.placeholder = "Event Name" titleTextField.backgroundColor = .white titleTextField.addPadding(.both(16)) notesTextView.anchor(top: titleTextField.bottomAnchor, leading: leadingAnchor, bottom: nil, trailing: trailingAnchor, padding: .init(top: 16, left: 0, bottom: 0, right: 0), size: .init(width: 0, height: 180)) notesTextView.text = "Notes" notesTextView.backgroundColor = .white startTimeTextField.anchor(top: notesTextView.bottomAnchor, leading: leadingAnchor, bottom: nil, trailing: trailingAnchor, padding: .init(top: 16, left: 0, bottom: 0, right: 0), size: .init(width: 0, height: 60)) startTimeTextField.placeholder = "Start Time" startTimeTextField.backgroundColor = .white startTimeTextField.addPadding(.both(16)) endTimeTextField.anchor(top: startTimeTextField.bottomAnchor, leading: leadingAnchor, bottom: nil, trailing: trailingAnchor, padding: .init(top: 16, left: 0, bottom: 0, right: 0), size: .init(width: 0, height: 60)) endTimeTextField.placeholder = "Ending Time" endTimeTextField.backgroundColor = .white endTimeTextField.addPadding(.both(16)) } public func getEventData() -> [String] { if titleTextField.text!.count > 0 && titleTextField.text != "Event Name"{ if notesTextView.text!.count > 0 && notesTextView.text != "Notes"{ if startTimeTextField.text!.count > 0 && startTimeTextField.text != "Start Time"{ if endTimeTextField.text!.count > 0 && endTimeTextField.text != "Ending Time"{ return [titleTextField.text!, notesTextView.text!, startTimeTextField.text!, endTimeTextField.text!] } else{ endTimeTextField.borderWidth = 2 endTimeTextField.borderColor = .red } } else { startTimeTextField.borderWidth = 2 startTimeTextField.borderColor = .red } } else { notesTextView.borderWidth = 2 notesTextView.borderColor = .red } } else { titleTextField.borderWidth = 2 titleTextField.borderColor = .red } return [] } } extension AddEventView: UITextViewDelegate{ func textViewDidBeginEditing(_ textView: UITextView) { textView.text = "" } } extension AddEventView: UITextFieldDelegate{ func textFieldDidBeginEditing(_ textField: UITextField) { let datePickerView: UIDatePicker = UIDatePicker() datePickerView.datePickerMode = UIDatePickerMode.dateAndTime if textField == startTimeTextField{ startTimeTextField.inputView = datePickerView datePickerView.addTarget(self, action: #selector(AddEventView.startTimeChanged), for: UIControlEvents.valueChanged) } else if textField == endTimeTextField{ endTimeTextField.inputView = datePickerView datePickerView.addTarget(self, action: #selector(AddEventView.endTimeChanged), for: UIControlEvents.valueChanged) } } @objc func startTimeChanged(sender: UIDatePicker) { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy HH:mm" startTimeTextField.text = dateFormatter.string(from: sender.date) } @objc func endTimeChanged(sender: UIDatePicker) { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy HH:mm" endTimeTextField.text = dateFormatter.string(from: sender.date) } } <file_sep>/Radial/Navigation/Navigator.swift // // Navigator.swift // Radial // // Created by <NAME> on 5/31/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import UIKit protocol Navigator{ func back() } protocol HomeNavigator: Navigator { func toHomeViewController() } protocol AddEventNavigator: Navigator { func toAddEventViewController() } <file_sep>/Radial/UI/Home/HomeViewController.swift // // HomeViewController.swift // Radial // // Created by <NAME> on 5/31/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import UIKit class HomeViewController: UIViewController{ typealias HomeNavigation = AddEventNavigator let navigator: HomeNavigation! let homeView: HomeView! let interactor: HomeInteractor! var events: [EventModel] = [] init(navigator: HomeNavigation, view: HomeView, interactor: HomeInteractor) { self.navigator = navigator self.homeView = view self.interactor = interactor super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(homeView) self.homeView.fillSuperview() homeView.delegate = self navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add Event", style: .plain, target: self, action: #selector(addTapped)) // get today's events homeView.configureView(events: interactor.getEvents(for: Date())) } @objc func addTapped(){ navigator.toAddEventViewController() } } extension HomeViewController: HomeViewDelegate{ func newDateSelected(date: Date) { homeView.configureView(events: interactor.getEvents(for: date)) } }
0c5ce89be6c58dda6bdc5a3311b24ce77ab3db9a
[ "Swift" ]
13
Swift
mremondi/Radial
cf613af28354f52ded9f7fb2c1bd837cc7286d6b
572be322114249ec805d2a902999ce66a7650ff9
refs/heads/master
<file_sep>var lit_object = (function(){ var _p = { 'init': function(){ return self; }, 'litobject_length': function (){ var count = 0; for (var prop in this) { if (typeof (this[prop]) != 'function') { count++; } } return count; }, 'litobject_get': function (index) { var count = 0; for (var prop in this) { if (typeof (this[prop]) != 'function') { if (count == index) return this[prop]; count++; } } return ''; } }; var self = { 'length': _p.litobject_length, 'get': _p.litobject_get }; return _p.init; })(); //USAGE lit_object["x"] = {name: "y"}; lit_object["w"] = {name: "a"}; lit_object["z"] = {name: "b"}; console.log(lit_object.length()); //RETURNS 3 console.log(lit_object.get(1)); //RETURNS {name:"a"} <file_sep>var EventEmitter = (function () { var self = { 'callbacks': {}, 'emit': function (event_name, data) { if (!self.callbacks[event_name]) return; for (var i = 0; i < self.callbacks[event_name].length; i++) { self.callbacks[event_name][i](data) } }, 'on': function (event_name, callback) { if ('function' != typeof (callback)) return; if (!self.callbacks[event_name]) self.callbacks[event_name] = []; self.callbacks[event_name].push(callback) }, 'removeListener': function (event_name, callback) { if (self.callbacks && self.callbacks[event_name]) { for (var i = 0; i < self.callbacks[event_name].length; i++) { if (self.callbacks[event_name][i] == callback) self.callbacks[event_name].splice(i, 1) } } } }; return self; })(); //USAGE function callback1(message){ console.log(message + "1"); } function callback2(message){ console.log(message + "2"); } EventEmitter.on("message", callback1); EventEmitter.on("message", callback2); EventEmitter.emit("message", "test"); // returns "test1" // returns "test2" EventEmitter.removeListener("message", callback1); EventEmitter.emit("message", "second test"); // returns "second test2"
304f4cba23735db1eecf0e6fd4b344e67c3e2449
[ "JavaScript" ]
2
JavaScript
duartemadueno/javascript
2a2fbde522755dcdf3e043d668df68e0ea0df834
749a6151d79548aeb971e389b9755078fe82f42d
refs/heads/master
<file_sep>package MiscellaneousItems; public class ValidateNumber { public static boolean validateNumber(String contact) { boolean statusContact = false; for (char c : contact.toCharArray()) { if (!Character.isDigit(c)) statusContact = false; else{ statusContact = true; } } return statusContact; } } <file_sep>package ui; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.util.*; public class AllParticipantsTable extends JFrame{ private JTable allParticipantsTable; private String[] columnNames = {"Participant ID","Name","Surname","Affiliation","Position","Email","Address","Contact number", "Attending status","Type of participant","Nationality"}; private Object[][] allParticipantsData = new Object[][]{}; public AllParticipantsTable() { this.allParticipantsTable = new JTable(); allParticipantsTable.setModel( new DefaultTableModel(allParticipantsData, columnNames)); JScrollPane scrollPane = new JScrollPane(allParticipantsTable); allParticipantsTable.setFillsViewportHeight(true); allParticipantsTable.setEnabled(false); allParticipantsTable.setDragEnabled(false); this.add(scrollPane); //set width and height this.setBounds( 75,75,1300, 400); //set visible this.setVisible(true); //cannot be resize this.setResizable(false); } public void populateAllParticipantsTable(ArrayList<String> AllParticipantsDataArraylist) { for(String line: AllParticipantsDataArraylist) { StringTokenizer tokenizer = new StringTokenizer(line, ","); String data1 = tokenizer.nextToken(); String data2 = tokenizer.nextToken(); String data3 = tokenizer.nextToken(); String data4 = tokenizer.nextToken(); String data5 = tokenizer.nextToken(); String data6 = tokenizer.nextToken(); String data7 = tokenizer.nextToken(); String data8 = tokenizer.nextToken(); String data9 = tokenizer.nextToken(); String data10 = tokenizer.nextToken(); String data11 = tokenizer.nextToken(); Object[] row = { data1, data2, data3,data4, data5, data6,data7, data8, data9,data10, data11}; DefaultTableModel model = (DefaultTableModel) this.allParticipantsTable.getModel(); model.addRow(row); } } } <file_sep>package main; import javax.swing.JButton; import data.*; import listener.*; import ui.*; public class Application { public static void main(String[] args) { // TODO Auto-generated method stub //call a gui RegistrationForm rf = new RegistrationForm(); ParticipantsReport pr = new ParticipantsReport(); //create a listener object FormsActionListener listener = new FormsActionListener(rf,pr); //buttons that will be sources of event JButton submit = rf.getSubmit(); JButton search = rf.getSearchButton(); JButton showData = rf.getShowData(); JButton delete = rf.getDelete(); JButton clear = rf.getClear(); JButton addButton = rf.getAddButton(); //add a listener to each button submit.addActionListener(listener); search.addActionListener(listener); showData.addActionListener(listener); delete.addActionListener(listener); clear.addActionListener(listener); addButton.addActionListener(listener); } }
d9309ba5bba17cf34a09f1e4fdcf879df77205c0
[ "Java" ]
3
Java
rickyton/Unitec_Conference_Registration_System
7983dddf1037af7f12302cee53fba2ebdb0eaccc
7fa90e7ed16198888d3d7d73c0c76593abd44726
refs/heads/master
<file_sep><?xml version="1.0" encoding="UTF-8"?> <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>com.example</groupId> <artifactId>flight</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>flight</name> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</version> <relativePath/> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--能够使配置文件有提示 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <!--引入插件lombok 自动的set/get/构造方法插件 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!--支持热部署 --> <dependency> <groupId>org.springframework</groupId> <artifactId>springloaded</artifactId> <version>1.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <!--引入数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>compile</scope> </dependency> <!--引入druid数据源 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <!--spring整合mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.6</version> </dependency> <!-- 阿里沙箱支付 --> <dependency> <groupId>com.alipay.sdk</groupId> <artifactId>alipay-sdk-java</artifactId> <version>4.6.0.ALL</version> </dependency> <!--spring websocket依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <!-- spring整合redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- spring整合rocketmq --> <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-spring-boot-starter</artifactId> <version>2.0.3</version> </dependency> <!-- 使用AspectJ方式自动代理 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <!-- 使用腾讯云发送短信 --> <dependency> <groupId>com.github.qcloudsms</groupId> <artifactId>qcloudsms</artifactId> <version>1.0.6</version> </dependency> <!--<dependency> <groupId>io.shardingsphere</groupId> <artifactId>sharding-jdbc-spring-boot-starter</artifactId> <version>3.1.0</version> </dependency>--> <!-- spring整合elasticsearch --> <!--<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>--> <!-- 引入httpclient --> <!-- <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.0.1</version> </dependency>--> <!--spring 整合netty依赖--> <!--<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.10.Final</version> <scope>compile</scope> </dependency>--> </dependencies> <build> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle --> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> <configuration> <skipTests>true</skipTests> </configuration> </plugin> <plugin> <artifactId>maven-jar-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle --> <plugin> <artifactId>maven-site-plugin</artifactId> <version>3.7.1</version> </plugin> <plugin> <artifactId>maven-project-info-reports-plugin</artifactId> <version>3.0.0</version> </plugin> <!--将项目打包成可执行的jar包--> <!--<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> <configuration> <includeSystemScope>true</includeSystemScope> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <mainClass>com.example.flight.FlightApplication</mainClass> </archive> </configuration> </plugin>--> </plugins> </pluginManagement> </build> </project> <file_sep># flightServer 飞机票销售服务端 <file_sep>package com.example.flight.aop; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.After; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; @Aspect @Component public class WebLogAspect { private final Logger logger = LoggerFactory.getLogger(WebLogAspect.class); //@Pointcut("@annotation(org.springframework.web.bind.annotation.*)") @Pointcut("execution(public * com.example.flight.controller..*.*(..)) ") public void controllerLog() { } @Before("controllerLog()") public void logBeforeController(JoinPoint joinPoint) { //RequestContextHolder是Springmvc提供来获得请求的东西 RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); // 记录下请求内容 logger.info("请求URL : " + request.getRequestURL().toString()); logger.info("请求方式HTTP_METHOD : " + request.getMethod()); logger.info("请求IP : " + request.getRemoteAddr()); logger.info("请求方法CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); logger.info("请求参数ARGS : " + Arrays.toString(joinPoint.getArgs())); } @After("controllerLog()") public void after(JoinPoint joinPoint){ logger.info("请求结束FINISH : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); } /* @AfterReturning(returning = "ret", pointcut = "controllerLog()") public void doAfterReturning(Object ret) throws Throwable { // 处理完请求,返回内容 logger.info("RESPONSE : " + ret); }*/ }<file_sep>package com.example.flight.dao; import org.apache.ibatis.annotations.Mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.flight.model.user.UserInfo; @Mapper public interface UserDao extends BaseMapper<UserInfo>{ } <file_sep>package com.example.flight.service.impl; import javax.servlet.http.HttpServletRequest; import com.alibaba.fastjson.JSON; import com.example.flight.model.user.PhoneInfo; import com.example.flight.rocketmq.SpringProducer; import com.example.flight.service.UserService; import com.example.flight.util.PhoneUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.example.flight.dao.UserDao; import com.example.flight.model.user.UserInfo; import java.util.List; @Service public class UserServiceImpl implements UserService { private final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); @Autowired private UserDao dao; @Autowired private SpringProducer producer; @Override //@Cacheable(cacheNames="user_cache") public UserInfo login(UserInfo user) { QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("user_phone", user.getPhone()).eq("user_password", user.getPassword()) .and(wrapper ->wrapper.eq("user_status",0).or().eq("user_status",1)); /*queryWrapper.eq("user_phone", user.getPhone()).eq("user_password", user.getPassword()) .apply("( user_status = 0 or user_status = 1 )");*/ user=dao.selectOne(queryWrapper); return user; } @Override public UserInfo manageLogin(UserInfo user) { QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("user_name", user.getUserName()).eq("user_password", user.getPassword()) .eq("user_status",2); user=dao.selectOne(queryWrapper); return user; } @Override //@CachePut(cacheNames="user_cache") public void register(UserInfo user) { dao.insert(user); } @Override public boolean sendPhoneCode(HttpServletRequest request){ String phone = request.getParameter("phone"); System.out.println(phone); QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("user_phone", phone); UserInfo user = dao.selectOne(queryWrapper); if(user !=null) return false; String phoneCode = PhoneUtil.smsCode(); System.out.println(phoneCode); request.getSession().setAttribute("phoneCode",phoneCode); PhoneInfo phoneInfo = new PhoneInfo(phone,phoneCode); producer.async("register-topic", JSON.toJSONString(phoneInfo)); return true; } @Override public boolean checkCode(HttpServletRequest request) { String code = request.getParameter("code"); String phoneCode = (String)request.getSession().getAttribute("phoneCode"); if(code.equals(phoneCode)) { return true; } return false; } @Override //@Cacheable(cacheNames="user_cache") public List<UserInfo> getUserAllList() { QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("user_status",0).or().eq("user_status",1) .or().eq("user_status",3); return dao.selectList(queryWrapper); } @Override public void modifyStatus(int userId, int status) { UserInfo userInfo = dao.selectById(userId); userInfo.setStatus(status); dao.updateById(userInfo); } @Override public void modifyUser(UserInfo user) { dao.updateById(user); } @Override public UserInfo getUserById(int userId) { return dao.selectById(userId); } @Override public void deleteUser(Integer userId) { dao.deleteById(userId); } @Override public List<UserInfo> getUserDeleteList() { QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("user_status",4); return dao.selectList(queryWrapper); } } <file_sep>package com.example.flight.exception; import com.example.flight.model.error.ErrorInfo;; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; @ControllerAdvice public class GlobalExceptionHandler { private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(value = MyException.class) @ResponseBody public ErrorInfo jsonErrorHandler(HttpServletRequest req, MyException e) throws Exception { log.info("执行jsonErrorHandler"); ErrorInfo r = new ErrorInfo(); r.setMessage(e.getMessage()); r.setCode(ErrorInfo.ERROR); r.setData("自定义MyException异常"); r.setUrl(req.getRequestURL().toString()); log.error(e.getMessage()); return r; } @ExceptionHandler(value = Exception.class) @ResponseBody public ErrorInfo exceptionHandler(HttpServletRequest req, Exception e){ log.info("执行exceptionHandler"); ErrorInfo r = new ErrorInfo(); r.setMessage(e.getMessage()); r.setCode(ErrorInfo.ERROR); r.setData("Exception异常"); r.setUrl(req.getRequestURL().toString()); e.printStackTrace(); log.error(e.getMessage()); return r; } } <file_sep>package com.example.flight.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; @Component public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (request.getSession().getAttribute("user") == null) { if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) { //如果是ajax请求响应头会有x-requested-with response.setStatus(403); return false; } return false; } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } } <file_sep>package com.example.flight.config; import com.example.flight.listener.RequestListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.example.flight.converter.DateConverter; import com.example.flight.interceptor.LoginInterceptor; @Configuration public class WebConfigurer implements WebMvcConfigurer { @Autowired private LoginInterceptor loginInterceptor; @Autowired private DateConverter dateConverter; @Autowired private RequestListener requestListener; @Override public void addCorsMappings(CorsRegistry registry) { WebMvcConfigurer.super.addCorsMappings(registry); } //这个方法是用来配置静态资源的 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { } // 这个方法用来注册拦截器,我们自己写好的拦截器需要通过这里添加注册才能生效 @Override public void addInterceptors(InterceptorRegistry registry) { // addPathPatterns("/**") 表示拦截所有的请求, // excludePathPatterns("/login", "/register") 表示除了登陆与注册之外 registry.addInterceptor(loginInterceptor).addPathPatterns("/**"). excludePathPatterns("/serachByWeek.action/*","/getFlighInfo.action","/getDateWeek.action", "/serachList.action","/login.action","/sendPhoneCode.action","/checkCode.action","/register.action", "/manageLogin.form"); } //用来注册日期转换器 @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(dateConverter); } //注册监听器 //也可以@WebListener注解来实现,启动类添加@ServletComponentScan注解 @Bean public ServletListenerRegistrationBean<RequestListener> servletListenerRegistrationBean() { ServletListenerRegistrationBean<RequestListener> servletListenerRegistrationBean = new ServletListenerRegistrationBean<>(); servletListenerRegistrationBean.setListener(requestListener); return servletListenerRegistrationBean; } } <file_sep>package com.example.flight.service; import javax.servlet.http.HttpServletRequest; import com.example.flight.model.user.UserInfo; import java.util.List; public interface UserService { UserInfo login(UserInfo user); UserInfo manageLogin(UserInfo user); void register(UserInfo user); boolean sendPhoneCode(HttpServletRequest request) throws Exception; boolean checkCode(HttpServletRequest request); List<UserInfo> getUserAllList(); void modifyStatus(int userId,int status); void modifyUser(UserInfo user); UserInfo getUserById(int userId); void deleteUser(Integer userId); List<UserInfo> getUserDeleteList(); } <file_sep>package com.example.flight.rocketmq; import org.apache.rocketmq.client.producer.SendCallback; import org.apache.rocketmq.client.producer.SendResult; import org.apache.rocketmq.spring.core.RocketMQTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @Component public class SpringProducer { @Autowired private RocketMQTemplate rocketMQTemplate;//在RocketMQAutoConfiguration实例化 public void sendMsg(String topic, Object msg) { System.out.println(msg); this.rocketMQTemplate.convertAndSend(topic, msg); } public void sync(String topic, String msg) { rocketMQTemplate.syncSend(topic,msg); } public void async(String topic, String msg) { System.out.println("producer:"+msg); rocketMQTemplate.asyncSend(topic,msg, new SendCallback() { @Override public void onSuccess(SendResult sendResult) { System.out.println("mq成功发送"); } @Override public void onException(Throwable throwable) { } }); } //用于日志信息发送 //跟异步发送的区别就是它没有回调函数来告知 public void oneWay(String topic, String msg) { rocketMQTemplate.sendOneWay(topic,msg); } } <file_sep>package com.example.flight.controller.backstage; import com.example.flight.model.user.UserInfo; import com.example.flight.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.List; @RestController public class UserManageController { @Autowired private UserService userService; @PostMapping("manageLogin.form") public String userLogin(UserInfo user, HttpServletRequest request){ user = userService.manageLogin(user); if(user!=null) { request.getSession().setAttribute("user", user); return "success"; }else { return "fail"; } } @GetMapping("getUserName.form") public String getUserName(HttpServletRequest request){ UserInfo userInfo = (UserInfo) request.getSession().getAttribute("user"); return userInfo.getUserName(); } @GetMapping("getUserById.form/userId/{userId}") public UserInfo getUserById(@PathVariable int userId){ return userService.getUserById(userId); } @GetMapping("getUserAllList.form") public List<UserInfo> getUserAllList(){ return userService.getUserAllList(); } @PostMapping("addUser.form") public void addUser(UserInfo userInfo){ userService.register(userInfo); } @PutMapping("modifyStatus.form/userId/{userId}/{status}") public void modifyStatus(@PathVariable("userId")Integer userId,@PathVariable("status")int status){ userService.modifyStatus(userId,status); } @PutMapping("memberPwd.form/userId/{userId}") public void memberPwd(@PathVariable("userId")Integer userId){ UserInfo user = new UserInfo().setId(userId).setPassword("<PASSWORD>"); userService.modifyUser(user); } @RequestMapping("modifyUser.form") public void modifyUser(UserInfo userInfo){ userService.modifyUser(userInfo); } @GetMapping("getUserDeleteList.form") public List<UserInfo> getUserDeleteList(){ return userService.getUserDeleteList(); } @DeleteMapping("deleteUser.form/userId/{userId}") public void deleteUser(@PathVariable("userId")Integer userId){ userService.deleteUser(userId); } } <file_sep>package com.example.flight.util; import java.util.Calendar; import java.util.Date; public class DateUtil { //在原来基础上增加一个月 public static Date subMonth(Date date) { Calendar rightNow = Calendar.getInstance(); rightNow.setTime(date); rightNow.add(Calendar.MONTH, 1); return rightNow.getTime(); } // 在原来日期上增减一天(减为-1) public static Date subDay(Date date,int day){ Calendar rightNow = Calendar.getInstance(); rightNow.setTime(date); rightNow.add(Calendar.DAY_OF_MONTH, day); System.out.println(rightNow.getTime()); return rightNow.getTime(); } } <file_sep>package com.example.flight.model.order; import java.io.Serializable; import java.util.Date; import java.util.List; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.example.flight.model.flight.FlightPeople; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import lombok.experimental.Accessors; import org.springframework.format.annotation.DateTimeFormat; @Data @Accessors(chain=true) @TableName(value="flight_ticket") public class FlightTicket implements Serializable{ private static final long serialVersionUID = 1L; @TableId(value="id",type=IdType.AUTO) private Integer id; @TableField(value="order_number") private String orderNumber; @TableField(value="person_name") private String personName; @TableField(value="person_phone") private String personPhone; @TableField(value="person_number") private int personNumber; @TableField(value="shipping_space") private String shippingSpace; @TableField(value="airline") private String airline; @TableField(value="departure") private String departure; @TableField(value="destination") private String destination; @TableField(value="start_time") @DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date startTime; @TableField(value="end_time") @DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date endTime; @TableField(value="price") private String price; @TableField(value="order_time") @DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date orderTime; @TableField(value="order_status") private String orderStatus; @TableField(value="flight_number") private String flightNumber; @TableField(value="user_id") private Integer userId; @TableField(exist = false) private List<FlightPeople> flightPeoples; }
b17b3300039cd345a0c30cbc29e45c9dfc53c637
[ "Markdown", "Java", "Maven POM" ]
13
Maven POM
1145087558/flightServer
b03e1e15070b8d9bbdfa9ff68c51f4cc405ad153
c667d0cd95a265d09132b070d317f9afb441814d
refs/heads/master
<file_sep>using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media.Animation; namespace DB_Store { class Animation { public void MoveLoginWindow(LoginWindow window) { DoubleAnimation da = new DoubleAnimation(SystemParameters.PrimaryScreenWidth, (SystemParameters.PrimaryScreenWidth - window.Width) / 2, TimeSpan.FromMilliseconds(300)); window.BeginAnimation(Canvas.LeftProperty, da); } public void MoveMainWindow(MainWindow window) { DoubleAnimation da = new DoubleAnimation(SystemParameters.PrimaryScreenWidth, (SystemParameters.PrimaryScreenWidth - window.Width) / 2, TimeSpan.FromMilliseconds(300)); window.BeginAnimation(Canvas.LeftProperty, da); } public void MoveNewClientWindow(NewClientWindow window) { DoubleAnimation da = new DoubleAnimation(SystemParameters.PrimaryScreenWidth, (SystemParameters.PrimaryScreenWidth - window.Width) / 2, TimeSpan.FromMilliseconds(300)); window.BeginAnimation(Canvas.LeftProperty, da); } } }<file_sep>using System; using System.Data; using System.Text.RegularExpressions; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace DB_Store { class Checks { static SolidColorBrush colorError = new SolidColorBrush(Color.FromRgb(255, 197, 197)); public static bool TextInput(TextBox tb, TextCompositionEventArgs e) { bool result = false; int code = Convert.ToChar(e.Text); if (tb.Name == "textBoxBrand") { if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) result = true; else result = false; } else if (tb.Name == "textBoxType" || tb.Name == "textBoxSurnameClients" || tb.Name == "textBoxNameClients" || tb.Name == "textBoxPatronymicClients" || tb.Name == "textBoxSurnameStaff" || tb.Name == "textBoxNameStaff" || tb.Name == "textBoxPatronymicStaff") { if (code >= 1040 && code <= 1103) result = true; else result = false; } else if (tb.Name == "textBoxModel") { if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122) || (code >= 48 && code <= 57)) result = true; else result = false; } else if (tb.Name == "textBoxPrice" || tb.Name == "textBoxCount" || tb.Name == "textBoxCountOrder" || tb.Name == "textBoxCountRecords") { if (code >= 48 && code <= 57) result = true; else result = false; } else if (tb.Name == "textBoxPhoneClients" || tb.Name == "textBoxPhoneStaff" || tb.Name == "textBoxPhoneSupplier") { if ((code >= 48 && code <= 57) || code == 45 || code == 40 || code == 41) result = true; else result = false; } else if (tb.Name == "textBoxAddresClients" || tb.Name == "textBoxAddresStaff" || tb.Name == "textBoxAddresSupplier") { if ((code >= 1040 && code <= 1103) || (code >= 48 && code <= 57) || code == 45 || code == 44) result = true; else result = false; } else if (tb.Name == "textBoxSupplier") { if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122) || (code >= 1040 && code <= 1103) || code == 34) result = true; else result = false; } else if (tb.Name == "textBoxDate" || tb.Name == "textBoxDateOrder" || tb.Name == "textBoxDateSale") { if ((code >= 48 && code <= 57) || code == 46 || code == 58) result = true; else result = false; } return result; } public static void TextChanged(TextBox tb, int countDevices) { if (tb.Name == "textBoxBrand") { if (!Regex.IsMatch(tb.Text, @"^([A-Za-z][\s]?)+[A-Za-z]$")) tb.Background = colorError; else tb.Background = Brushes.White; } else if (tb.Name == "textBoxType") { if (!Regex.IsMatch(tb.Text, @"^[А-Я]([а-я][\s]?)+[а-я]$")) tb.Background = colorError; else tb.Background = Brushes.White; } else if (tb.Name == "textBoxModel") { if (!Regex.IsMatch(tb.Text, @"^([A-Za-z\d][\s]?)+[A-Za-z\d]$")) tb.Background = colorError; else tb.Background = Brushes.White; } else if (tb.Name == "textBoxPrice") { if (!Regex.IsMatch(tb.Text, @"^[\d]+$")) tb.Background = colorError; else tb.Background = Brushes.White; } else if (tb.Name == "textBoxSurnameClients" || tb.Name == "textBoxNameClients" || tb.Name == "textBoxPatronymicClients" || tb.Name == "textBoxSurnameStaff" || tb.Name == "textBoxNameStaff" || tb.Name == "textBoxPatronymicStaff") { if (!Regex.IsMatch(tb.Text, @"^[А-Я]{1}[а-я]+$")) tb.Background = colorError; else tb.Background = Brushes.White; } else if (tb.Name == "textBoxPhoneClients" || tb.Name == "textBoxPhoneStaff" || tb.Name == "textBoxPhoneSupplier") { if (!Regex.IsMatch(tb.Text, @"^[(]{1}[\d]{2}[)]{1}[\s]{1}[\d]{3}[-]{1}[\d]{2}[-]{1}[\d]{2}$")) tb.Background = colorError; else tb.Background = Brushes.White; } else if (tb.Name == "textBoxAddresClients" || tb.Name == "textBoxAddresStaff" || tb.Name == "textBoxAddresSupplier") { if (!Regex.IsMatch(tb.Text, @"^([А-Я]{1}[а-я]+[,]{1}[\s]{1}){2}[\d]{1,2}([-]{1}[\d]{1,3})?$")) tb.Background = colorError; else tb.Background = Brushes.White; } else if (tb.Name == "textBoxSupplier") { if (!Regex.IsMatch(tb.Text, @"^[А-ЯA-Za-z]{1}[а-яa-z]+$")) tb.Background = colorError; else tb.Background = Brushes.White; } else if (tb.Name == "textBoxDate" || tb.Name == "textBoxDateOrder" || tb.Name == "textBoxDateSale") { if (!Regex.IsMatch(tb.Text, @"^([\d]{2}[.]{1}){2}[\d]{4}[\s]{1}[\d]{1,2}[:]{1}[\d]{2}[:]{1}[\d]{2}$")) tb.Background = colorError; else tb.Background = Brushes.White; } else if (tb.Name == "textBoxCount" || tb.Name == "textBoxCountRecords") { int count; if (tb.Text == "") count = 0; else count = Convert.ToInt32(tb.Text); if (count == 0 || count > countDevices) tb.Background = colorError; else tb.Background = Brushes.White; } else if (tb.Name == "textBoxCountOrder") { int count; if (tb.Text == "") count = 0; else count = Convert.ToInt32(tb.Text); if (count == 0) tb.Background = colorError; else tb.Background = Brushes.White; } } public static void SelectionChanged(ComboBox cb, SelectionChangedEventArgs e) { string id = ""; if (cb.Name == "comboBoxModelsTypes") id = "ID_type"; else if (cb.Name == "comboBoxModelsBrands") id = "ID_brand"; else if (cb.Name == "comboBoxDevicesModels") id = "ID_model"; else if (cb.Name == "comboBoxAppClients") id = "ID_client"; else if (cb.Name == "comboBoxAppStaff") id = "ID_Staff"; else if (cb.Name == "comboBoxOrdersStaff") id = "ID_Staff"; else if (cb.Name == "comboBoxOrdersDevices") id = "ID_device"; else if (cb.Name == "comboBoxDeliverySupplier") id = "ID_supplier"; else if (cb.Name == "comboBoxDeliveryOrder") id = "ID_order"; else if (cb.Name == "comboBoxRecordsApplications") id = "ID_application"; else if (cb.Name == "comboBoxRecordsDevices") id = "ID_device"; else if (cb.Name == "comboBoxSaleApp") id = "ID_application"; else if (cb.Name == "comboBoxRecordsOfSalesSale") id = "ID_sale"; else if (cb.Name == "comboBoxRecordsOfSalesRecords") id = "ID_record"; try { (e.AddedItems[0] as DataRowView).Row[id].ToString(); cb.Background = Brushes.White; } catch (Exception) { cb.Background = colorError; } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace DB_Store { public partial class NewClientWindow : Window { DB db; bool added; public NewClientWindow(DB _db) { InitializeComponent(); db = _db; } private void Window_Loaded(object sender, RoutedEventArgs e) { Animation animation = new Animation(); animation.MoveNewClientWindow(this); } private void buttonClose_Click(object sender, RoutedEventArgs e) { added = false; this.Close(); } private void titleBar_MouseDown(object sender, MouseButtonEventArgs e) { this.DragMove(); } private void buttonAdd_Click(object sender, RoutedEventArgs e) { db.InsertTableClientsStaff("Clients", textBoxSurnameClients.Text, textBoxNameClients.Text, textBoxPatronymicClients.Text, textBoxPhoneClients.Text, textBoxAddresClients.Text, false); added = true; this.Close(); } private void buttonCancel_Click(object sender, RoutedEventArgs e) { added = false; this.Close(); } public bool GetStatus() { return added; } private void PreviewKeyDownCheck(object sender, KeyEventArgs e) { if (e.Key == Key.Space) e.Handled = true; } private void PreviewTextInputCheck(object sender, TextCompositionEventArgs e) { if (!Checks.TextInput(sender as TextBox, e)) e.Handled = true; } private void TextChangedCheck(object sender, TextChangedEventArgs e) { Checks.TextChanged(sender as TextBox, 0); } } }<file_sep>using System; using System.Data; using System.Data.SqlClient; using System.Windows.Controls; namespace DB_Store { public class DB { SqlConnection connection; SqlCommand cmd; SqlDataAdapter da; DataTable dt; DataGrid dataGrid; int rowsCount; public DB(DataGrid _dataGrid) { dataGrid = _dataGrid; } public void SetConnection(SqlConnection _connection) { connection = _connection; } public void CloseConnection() { connection.Close(); } public DataTable FillTable(string table, string fillForCB) { if (fillForCB == "View_Orders") cmd = new SqlCommand("SELECT * FROM View_Orders WHERE Статус='Открыт' AND Is_deleted='0'", connection); else if (fillForCB == "View_Applications") cmd = new SqlCommand("SELECT * FROM View_Applications WHERE Статус='Оформляется' AND Is_deleted='0'", connection); else cmd = new SqlCommand("SELECT * FROM " + table + " WHERE Is_deleted='0'", connection); da = new SqlDataAdapter(cmd); dt = new DataTable(); da.Fill(dt); rowsCount = dt.Rows.Count; return dt; } public void SelectTable(string table) { dt = FillTable(table, null); dataGrid.ItemsSource = dt.DefaultView; } public void FillComboBox(ComboBox cb, string table, string id, string field) { if (table == "View_Orders") dt = FillTable(table, "View_Orders"); else if (table == "View_Applications") dt = FillTable(table, "View_Applications"); else dt = FillTable(table, null); cb.ItemsSource = dt.DefaultView; cb.SelectedValuePath = dt.Columns[id].ToString(); cb.DisplayMemberPath = dt.Columns[field].ToString(); } public void FillComboBoxWithCondition(ComboBox cb, string fk) { SqlCommand cmd = new SqlCommand("SELECT * FROM View_RecordsOfApplication WHERE FK_application='" + fk + "' AND Is_deleted='0' AND [-Inactive]='0'", connection); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); cb.ItemsSource = dt.DefaultView; cb.SelectedValuePath = dt.Columns["ID_record"].ToString(); cb.DisplayMemberPath = dt.Columns["-Устройство (Количество)"].ToString(); } public void SelectValueForComboBox(ComboBox cb, string columnFK) { try { DataRowView row = dataGrid.SelectedItem as DataRowView; cb.SelectedValue = row[columnFK].ToString(); } catch (NullReferenceException) { } } public string GetID(string table, string columnID) { dt = FillTable(table, null); return dt.Rows[rowsCount - 1][columnID].ToString(); } public int GetRowsCount(string table) { dt = FillTable(table, null); return dt.Rows.Count; } public DataTable GetDataTable(string table) { SqlCommand cmd = new SqlCommand("SELECT * FROM " + table + " WHERE Is_deleted='0'", connection); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); return dt; } public int CheckNames(string table, string name) { cmd = connection.CreateCommand(); cmd.CommandText = "Check_" + table; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Name", name); var returnParameter = cmd.Parameters.Add("@Code", SqlDbType.Int); returnParameter.Direction = ParameterDirection.ReturnValue; cmd.ExecuteNonQuery(); return Convert.ToInt32(returnParameter.Value); } public int CheckModel(string name, string FKbrand, string FKtype) { cmd = connection.CreateCommand(); cmd.CommandText = "Check_Model"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Name", name); cmd.Parameters.AddWithValue("@FK_brand", Convert.ToInt32(FKbrand)); cmd.Parameters.AddWithValue("@FK_type", Convert.ToInt32(FKtype)); var returnParameter = cmd.Parameters.Add("@Code", SqlDbType.Int); returnParameter.Direction = ParameterDirection.ReturnValue; cmd.ExecuteNonQuery(); return Convert.ToInt32(returnParameter.Value); } public void UpdateTableBrandsTypes(string table, string textFromTB, string id) { string columnID; if (table == "Brands") columnID = "brand"; else columnID = "type"; cmd = new SqlCommand("UPDATE " + table + " SET Name='" + textFromTB + "' WHERE ID_" + columnID + "='" + id + "'", connection); cmd.ExecuteNonQuery(); SelectTable("View_" + table); } public void UpdateTableModels(string idFromCB1, string idFromCB2, string textFromTB, string id) { cmd = new SqlCommand("UPDATE Models SET FK_brand='" + idFromCB1 + "', FK_type='" + idFromCB2 + "', Name='" + textFromTB + "' WHERE ID_model='" + id + "'", connection); cmd.ExecuteNonQuery(); SelectTable("View_Models"); } public void UpdateTableDevices(string idFromCB, string textFromTB, string id) { cmd = new SqlCommand("UPDATE Devices SET FK_model='" + idFromCB + "', Price='" + textFromTB + "' WHERE ID_device='" + id + "'", connection); cmd.ExecuteNonQuery(); SelectTable("View_Devices"); } public void UpdateTableClientsStaff(string table, string textFromTB1, string textFromTB2, string textFromTB3, string textFromTB4, string textFromTB5, string id) { string columnID; if (table == "Clients") columnID = "client"; else columnID = "staff"; cmd = new SqlCommand("UPDATE " + table + " SET Surname='" + textFromTB1 + "', Name='" + textFromTB2 + "', Patronymic='" + textFromTB3 + "', Phone='" + textFromTB4 + "', Addres='" + textFromTB5 + "' WHERE ID_" + columnID + "='" + id + "'", connection); cmd.ExecuteNonQuery(); SelectTable("View_" + table); } public void UpdateTableSuppliers(string textFromTB1, string textFromTB2, string textFromTB3, string id) { cmd = new SqlCommand("UPDATE Suppliers SET Name='" + textFromTB1 + "', Phone='" + textFromTB2 + "', Addres='" + textFromTB3 + "' WHERE ID_supplier='" + id + "'", connection); cmd.ExecuteNonQuery(); SelectTable("View_Suppliers"); } public void UpdateTableApplications(string idFromCB1, string idFromCB2, string d, string id) { cmd = new SqlCommand("UPDATE Applications SET FK_client='" + idFromCB1 + "', FK_staff='" + idFromCB2 + "', Date_application='" + d + "' WHERE ID_application='" + id + "'", connection); cmd.ExecuteNonQuery(); SelectTable("View_Applications"); } public void UpdateRecordsOfApplication(string idFromCB1, string idFromCB2, string textFromTB, string id) { cmd = connection.CreateCommand(); cmd.CommandText = "Update_RecordOfApplication"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@FK_application", Convert.ToInt32(idFromCB1)); cmd.Parameters.AddWithValue("@FK_device", Convert.ToInt32(idFromCB2)); cmd.Parameters.AddWithValue("@Count_devices", Convert.ToInt32(textFromTB)); cmd.Parameters.AddWithValue("@ID", Convert.ToInt32(id)); cmd.ExecuteNonQuery(); SelectTable("View_RecordsOfApplication"); } public int GetCountDevicesInStorage(string FK_device) { cmd = connection.CreateCommand(); cmd.CommandText = "Get_CountDevicesInStorage"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@FK_device", Convert.ToInt32(FK_device)); var returnParameter = cmd.Parameters.Add("@Count", SqlDbType.Int); returnParameter.Direction = ParameterDirection.ReturnValue; cmd.ExecuteNonQuery(); return Convert.ToInt32(returnParameter.Value); } public void UpdateOrders(string idFromCB1, string idFromCB2, string textFromTB1, string textFromTB2, string id) { cmd = new SqlCommand("UPDATE Orders SET FK_staff='" + idFromCB1 + "', FK_device='" + idFromCB2 + "', Count_devices='" + textFromTB1 + "', Date_order='" + textFromTB2 + "' WHERE ID_order='" + id + "'", connection); cmd.ExecuteNonQuery(); SelectTable("View_Orders"); } public void UpdateSales(string idFromCB, string textFromTB, string id) { cmd = new SqlCommand("UPDATE Sales SET FK_application='" + idFromCB + "', Date_sale='" + textFromTB + "' WHERE ID_sale='" + id + "'", connection); cmd.ExecuteNonQuery(); SelectTable("View_Sales"); } public void UpdateRecordsOfSale(string idFromCB1, string idFromCB2, string textFromTB, string id) { cmd = connection.CreateCommand(); cmd.CommandText = "Update_RecordOfSale"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@FK_sale", Convert.ToInt32(idFromCB1)); cmd.Parameters.AddWithValue("@FK_record_app", Convert.ToInt32(idFromCB2)); cmd.Parameters.AddWithValue("@Count_devices", Convert.ToInt32(textFromTB)); cmd.Parameters.AddWithValue("@ID", Convert.ToInt32(id)); cmd.ExecuteNonQuery(); SelectTable("View_RecordsOfSale"); } public int GetFkApplication(string FK_sale) { cmd = connection.CreateCommand(); cmd.CommandText = "Get_FKapplication"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@FK_sale", Convert.ToInt32(FK_sale)); var returnParameter = cmd.Parameters.Add("@FK_application", SqlDbType.Int); returnParameter.Direction = ParameterDirection.ReturnValue; cmd.ExecuteNonQuery(); return Convert.ToInt32(returnParameter.Value); } public int GetCountDevicesInRecordsOfApplication(string FK_record) { cmd = connection.CreateCommand(); cmd.CommandText = "Get_CountDevicesInRecordsOfApplication"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@FK_record", Convert.ToInt32(FK_record)); var returnParameter = cmd.Parameters.Add("@Count", SqlDbType.Int); returnParameter.Direction = ParameterDirection.ReturnValue; cmd.ExecuteNonQuery(); return Convert.ToInt32(returnParameter.Value); } public void InsertTableBrandsTypes(string table, string textFromTB) { cmd = new SqlCommand("INSERT INTO " + table + " (Name) VALUES ('" + textFromTB + "')", connection); cmd.ExecuteNonQuery(); SelectTable("View_" + table); } public void InsertTableModels(string idFromCB1, string idFromCB2, string textFromTB) { cmd = new SqlCommand("INSERT INTO Models (FK_brand, FK_type, Name) VALUES ('" + idFromCB1 + "', '" + idFromCB2 + "', '" + textFromTB + "')", connection); cmd.ExecuteNonQuery(); SelectTable("View_Models"); } public void InsertTableDevices(string idFromCB, string textFromTB) { cmd = new SqlCommand("INSERT INTO Devices (FK_model, Price) VALUES ('" + idFromCB + "', '" + textFromTB + "')", connection); cmd.ExecuteNonQuery(); SelectTable("View_Devices"); } public void InsertTableClientsStaff(string table, string textFromTB1, string textFromTB2, string textFromTB3, string textFromTB4, string textFromTB5, bool select) { cmd = new SqlCommand("INSERT INTO " + table + " (Surname, Name, Patronymic, Phone, Addres) VALUES ('" + textFromTB1 + "', '" + textFromTB2 + "', '" + textFromTB3 + "', '" + textFromTB4 + "', '" + textFromTB5 + "')", connection); cmd.ExecuteNonQuery(); if (select) SelectTable("View_" + table); } public void InsertTableSuppliers(string textFromTB1, string textFromTB2, string textFromTB3) { cmd = new SqlCommand("INSERT INTO Suppliers (Name, Phone, Addres) VALUES ('" + textFromTB1 + "', '" + textFromTB2 + "', '" + textFromTB3 + "')", connection); cmd.ExecuteNonQuery(); SelectTable("View_Suppliers"); } public void InsertTableApplications(string idFromCB1, string idFromCB2, string textFromTB) { cmd = new SqlCommand("INSERT INTO Applications (FK_client, FK_staff, Date_application, Status_application) VALUES ('" + idFromCB1 + "', '" + idFromCB2 + "', '" + textFromTB + "', 'Оформляется')", connection); cmd.ExecuteNonQuery(); SelectTable("View_Applications"); } public void InsertTableRecordsOfApplication(string idFromCB1, string idFromCB2, string textFromTB) { cmd = connection.CreateCommand(); cmd.CommandText = "Add_RecordOfApplication"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@FK_application", Convert.ToInt32(idFromCB1)); cmd.Parameters.AddWithValue("@FK_device", Convert.ToInt32(idFromCB2)); cmd.Parameters.AddWithValue("@Count_devices", Convert.ToInt32(textFromTB)); cmd.ExecuteNonQuery(); SelectTable("View_RecordsOfApplication"); } public void InsertTableOrders(string idFromCB1, string idFromCB2, string textFromTB1, string textFromTB2) { cmd = new SqlCommand("INSERT INTO Orders (FK_staff, FK_device, Count_devices, Date_order, Status_order) VALUES ('" + idFromCB1 + "', '" + idFromCB2 + "', '" + textFromTB1 + "', '" + textFromTB2 + "', 'Открыт')", connection); cmd.ExecuteNonQuery(); SelectTable("View_Orders"); } public void InsertTableDelivery(string idFromCB1, string idFromCB2) { cmd = connection.CreateCommand(); cmd.CommandText = "Add_Delivery"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@FK_supplier", Convert.ToInt32(idFromCB1)); cmd.Parameters.AddWithValue("@FK_order", Convert.ToInt32(idFromCB2)); cmd.ExecuteNonQuery(); SelectTable("View_Delivery"); } public void InsertTableSales(string idFromCB, string textFromTB) { cmd = new SqlCommand("INSERT INTO Sales (FK_application, Date_sale) VALUES ('" + idFromCB + "', '" + textFromTB + "')", connection); cmd.ExecuteNonQuery(); cmd = new SqlCommand("UPDATE Applications SET Status_application='Утверждён' WHERE ID_application='" + idFromCB + "'", connection); cmd.ExecuteNonQuery(); SelectTable("View_Sales"); } public void InsertTableRecordsOfSale(string idFromCB1, string idFromCB2, string textFromTB) { cmd = connection.CreateCommand(); cmd.CommandText = "Add_RecordOfSale"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@FK_sale", Convert.ToInt32(idFromCB1)); cmd.Parameters.AddWithValue("@FK_record_app", Convert.ToInt32(idFromCB2)); cmd.Parameters.AddWithValue("@Count_devices", Convert.ToInt32(textFromTB)); cmd.ExecuteNonQuery(); SelectTable("View_RecordsOfSale"); } public void DeleteFromTable(string table, string idColumn, string id) { cmd = new SqlCommand("UPDATE " + table + " SET Is_deleted='1' WHERE " + idColumn + "='" + id + "'", connection); cmd.ExecuteNonQuery(); SelectTable("View_" + table); } public void DeleteRecordOfApplication(string id) { cmd = connection.CreateCommand(); cmd.CommandText = "Delete_RecordOfApplication"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ID", Convert.ToInt32(id)); cmd.ExecuteNonQuery(); SelectTable("View_RecordsOfApplication"); } public void DeleteRecordOfSale(string id) { cmd = connection.CreateCommand(); cmd.CommandText = "Delete_RecordOfSale"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ID", Convert.ToInt32(id)); cmd.ExecuteNonQuery(); SelectTable("View_RecordsOfSale"); } } }<file_sep># About project Sample of a project that was given at the university. Using Microsoft SQL Server 2012 to store data and WPF client as the UI. # Login information - Login: _sa_ - Password: _<PASSWORD>_ # UI ![UI](https://raw.githubusercontent.com/imalexoff/ComputerStoreWPF/master/ui.png) <file_sep>using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; using System.Data; using System.Globalization; using Excel = Microsoft.Office.Interop.Excel; namespace DB_Store { public partial class MainWindow : Window { DB db; DispatcherTimer timer; DateTime time; Grid currGrid = new Grid(); Button currButton = new Button(); string currStyle; DataRowView row; bool canSelect = true; int countDevices; DataTable dt = new DataTable(); public MainWindow() { InitializeComponent(); LoginWindow form = new LoginWindow(); form.ShowDialog(); if (form.GetStatus()) Close(); else { db = new DB(dataGrid); db.SetConnection(form.GetConnection()); timer = new DispatcherTimer(); timer.Tick += new EventHandler(timerTick); timer.Interval = new TimeSpan(0, 0, 0, 1); time = DateTime.Now; timer.Start(); labelDate.Content = time.ToLongDateString(); buttonBrands_Click(null, new RoutedEventArgs()); } } private void Window_Loaded(object sender, RoutedEventArgs e) { Animation animation = new Animation(); animation.MoveMainWindow(this); } private void titleBar_MouseDown(object sender, MouseButtonEventArgs e) { try { DragMove(); } catch (InvalidOperationException) { } } private void buttonClose_Click(object sender, RoutedEventArgs e) { db.CloseConnection(); timer.Stop(); Close(); } private void buttonMinimize_Click(object sender, RoutedEventArgs e) { WindowState = WindowState.Minimized; } private void timerTick(object sender, EventArgs e) { labelTime.Content = DateTime.Now.Subtract(time).ToString(@"hh\:mm\:ss"); if (currGrid.Name == "gridApplications" && !canSelect) { textBoxDate.Clear(); textBoxDate.AppendText(DateTime.Now.ToString()); } if (currGrid.Name == "gridOrders" && !canSelect) { textBoxDateOrder.Clear(); textBoxDateOrder.AppendText(DateTime.Now.ToString()); } if (currGrid.Name == "gridSales" && !canSelect) { textBoxDateSale.Clear(); textBoxDateSale.AppendText(DateTime.Now.ToString()); } } private void GridVisibility(Grid newGrid) { currGrid.Visibility = Visibility.Hidden; newGrid.Visibility = Visibility.Visible; currGrid = newGrid; } private void ButtonStyle(Button button, string style) { try { currButton.Style = (Style)button.FindResource(currStyle); } catch (ArgumentNullException) { } button.Style = (Style)button.FindResource(style + "Active"); currButton = button; currStyle = style; } private void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) { if (e.PropertyName.Contains("ID") || e.PropertyName.Contains("FK") || e.PropertyName.Contains("-") || e.PropertyName == "Is_deleted") e.Column.Visibility = Visibility.Hidden; if (e.PropertyType == typeof(DateTime)) (e.Column as DataGridTextColumn).Binding.StringFormat = "dd.MM.yyyy"; if (currGrid.Name == "gridBrands" || currGrid.Name == "gridTypes") e.Column.Width = dataGrid.Width - 19; if (currGrid.Name == "gridModels" || currGrid.Name == "gridSuppliers") e.Column.Width = (dataGrid.Width - 19) / 3; if (currGrid.Name == "gridDevices") if (e.PropertyName == "Устройство") e.Column.Width = (dataGrid.Width - 19) / 1.5; else e.Column.Width = (dataGrid.Width - 19) / 3; if (currGrid.Name == "gridClients" || currGrid.Name == "gridStaff") if (e.PropertyName == "Адрес") e.Column.Width = (dataGrid.Width - 19) / 2.5; else e.Column.Width = (dataGrid.Width - 19) / 5; if (currGrid.Name == "gridOrders" || currGrid.Name == "gridRecordsOfSales" || currGrid.Name == "gridRecords") if (e.PropertyName == "Устройство") e.Column.Width = (dataGrid.Width - 19) / 2; else e.Column.Width = (dataGrid.Width - 19) / 5; if (currGrid.Name == "gridApplications") e.Column.Width = (dataGrid.Width - 19) / 5; if (currGrid.Name == "gridDelivery" || currGrid.Name == "gridStorage") if (e.PropertyName == "Заказ" || e.PropertyName == "Устройство") e.Column.Width = (dataGrid.Width - 19) / 2.5; else e.Column.Width = (dataGrid.Width - 19) / 3.34; if (currGrid.Name == "gridSales") e.Column.Width = (dataGrid.Width - 19) / 4; } private void buttonBrands_Click(object sender, RoutedEventArgs e) { ButtonStyle(buttonBrands, "TopButton"); GridVisibility(gridBrands); db.SelectTable("View_Brands"); labelCount.Content = db.GetRowsCount("View_Brands").ToString(); HideButton(0); } private void buttonTypes_Click(object sender, RoutedEventArgs e) { ButtonStyle(buttonTypes, "TopButton"); GridVisibility(gridTypes); db.SelectTable("View_TypesOfDevices"); labelCount.Content = db.GetRowsCount("View_TypesOfDevices").ToString(); HideButton(0); } private void buttonModels_Click(object sender, RoutedEventArgs e) { ButtonStyle(buttonModels, "TopButton"); GridVisibility(gridModels); db.SelectTable("View_Models"); labelCount.Content = db.GetRowsCount("View_Models").ToString(); HideButton(0); } private void buttonDevices_Click(object sender, RoutedEventArgs e) { ButtonStyle(buttonDevices, "TopButton"); GridVisibility(gridDevices); db.SelectTable("View_Devices"); labelCount.Content = db.GetRowsCount("View_Devices").ToString(); HideButton(0); } private void buttonClients_Click(object sender, RoutedEventArgs e) { ButtonStyle(buttonClients, "TopButton"); GridVisibility(gridClients); db.SelectTable("View_Clients"); labelCount.Content = db.GetRowsCount("View_Clients").ToString(); HideButton(0); } private void buttonStaff_Click(object sender, RoutedEventArgs e) { ButtonStyle(buttonStaff, "TopButton"); GridVisibility(gridStaff); db.SelectTable("View_Staff"); labelCount.Content = db.GetRowsCount("View_Staff").ToString(); HideButton(0); } private void buttonSuppliers_Click(object sender, RoutedEventArgs e) { ButtonStyle(buttonSuppliers, "TopButton"); GridVisibility(gridSuppliers); db.SelectTable("View_Suppliers"); labelCount.Content = db.GetRowsCount("View_Suppliers").ToString(); HideButton(0); } private void buttonApplications_Click(object sender, RoutedEventArgs e) { ButtonStyle(buttonApplications, "LeftMenuButtonApplication"); GridVisibility(gridApplications); db.SelectTable("View_Applications"); labelCount.Content = db.GetRowsCount("View_Applications").ToString(); HideButton(0); } private void buttonRecords_Click(object sender, RoutedEventArgs e) { ButtonStyle(buttonRecords, "LeftMenuButtonRecords"); GridVisibility(gridRecords); db.SelectTable("View_RecordsOfApplication"); labelCount.Content = db.GetRowsCount("View_RecordsOfApplication").ToString(); HideButton(0); } private void buttonOrders_Click(object sender, RoutedEventArgs e) { ButtonStyle(buttonOrders, "LeftMenuButtonOrders"); GridVisibility(gridOrders); db.SelectTable("View_Orders"); labelCount.Content = db.GetRowsCount("View_Orders").ToString(); HideButton(0); } private void buttonDelivery_Click(object sender, RoutedEventArgs e) { ButtonStyle(buttonDelivery, "LeftMenuButtonDelivery"); GridVisibility(gridDelivery); db.SelectTable("View_Delivery"); labelCount.Content = db.GetRowsCount("View_Delivery").ToString(); HideButton(0); } private void buttonStorage_Click(object sender, RoutedEventArgs e) { ButtonStyle(buttonStorage, "LeftMenuButtonStorage"); GridVisibility(gridStorage); db.SelectTable("View_Storage"); labelCount.Content = db.GetRowsCount("View_Storage").ToString(); HideButton(0); } private void buttonSale_Click(object sender, RoutedEventArgs e) { ButtonStyle(buttonSale, "LeftMenuButtonSale"); GridVisibility(gridSales); db.SelectTable("View_Sales"); labelCount.Content = db.GetRowsCount("View_Sales").ToString(); HideButton(0); } private void buttonRecordsOfSales_Click(object sender, RoutedEventArgs e) { ButtonStyle(buttonRecordsOfSales, "LeftMenuButtonRecordsOfSales"); GridVisibility(gridRecordsOfSales); db.SelectTable("View_RecordsOfSale"); labelCount.Content = db.GetRowsCount("View_RecordsOfSale").ToString(); HideButton(0); } private void buttonUpdateBrands_Click(object sender, RoutedEventArgs e) { if (textBoxBrand.Background == Brushes.White) { if (canSelect) { row = dataGrid.SelectedItem as DataRowView; db.UpdateTableBrandsTypes("Brands", textBoxBrand.Text, row[0].ToString()); dataGrid.SelectedIndex = 0; } else { if (db.CheckNames("Brand", textBoxBrand.Text) != 1) { db.InsertTableBrandsTypes("Brands", textBoxBrand.Text); int count = db.GetRowsCount("View_Brands"); HideButton(count - 1); labelCount.Content = count.ToString(); } else MessageBox.Show("Марка с таким названием уже существует!", "Ошибка данных", MessageBoxButton.OK, MessageBoxImage.Error); } } else MessageBox.Show("Некорректный ввод данных! Повторите ввод!", "Ошибка обновления таблицы", MessageBoxButton.OK, MessageBoxImage.Exclamation); } private void buttonUpdateTypes_Click(object sender, RoutedEventArgs e) { if (textBoxType.Background == Brushes.White) { if (canSelect) { row = dataGrid.SelectedItem as DataRowView; db.UpdateTableBrandsTypes("TypesOfDevices", textBoxType.Text, row[0].ToString()); dataGrid.SelectedIndex = 0; } else { if (db.CheckNames("Type", textBoxType.Text) != 1) { db.InsertTableBrandsTypes("TypesOfDevices", textBoxType.Text); int count = db.GetRowsCount("View_TypesOfDevices"); HideButton(count - 1); labelCount.Content = count.ToString(); } else MessageBox.Show("Такой тип уже существует!", "Ошибка данных", MessageBoxButton.OK, MessageBoxImage.Error); } } else MessageBox.Show("Некорректный ввод данных! Повторите ввод!", "Ошибка обновления таблицы", MessageBoxButton.OK, MessageBoxImage.Exclamation); } private void buttonUpdateModels_Click(object sender, RoutedEventArgs e) { if (comboBoxModelsBrands.Background == Brushes.White && comboBoxModelsTypes.Background == Brushes.White && textBoxModel.Background == Brushes.White) { if (canSelect) { row = dataGrid.SelectedItem as DataRowView; db.UpdateTableModels(comboBoxModelsBrands.SelectedValue.ToString(), comboBoxModelsTypes.SelectedValue.ToString(), textBoxModel.Text, row[0].ToString()); dataGrid.SelectedIndex = 0; } else { if (db.CheckModel(textBoxModel.Text, comboBoxModelsBrands.SelectedValue.ToString(), comboBoxModelsTypes.SelectedValue.ToString()) != 1) { db.InsertTableModels(comboBoxModelsBrands.SelectedValue.ToString(), comboBoxModelsTypes.SelectedValue.ToString(), textBoxModel.Text); int count = db.GetRowsCount("View_Models"); HideButton(count - 1); labelCount.Content = count.ToString(); } else MessageBox.Show("Такая модель уже существует!", "Ошибка данных", MessageBoxButton.OK, MessageBoxImage.Error); } } else MessageBox.Show("Некорректный ввод данных! Повторите ввод!", "Ошибка обновления таблицы", MessageBoxButton.OK, MessageBoxImage.Exclamation); } private void buttonUpdateDevices_Click(object sender, RoutedEventArgs e) { if (comboBoxDevicesModels.Background == Brushes.White && textBoxPrice.Background == Brushes.White) { if (canSelect) { row = dataGrid.SelectedItem as DataRowView; db.UpdateTableDevices(comboBoxDevicesModels.SelectedValue.ToString(), textBoxPrice.Text, row[0].ToString()); dataGrid.SelectedIndex = 0; } else { db.InsertTableDevices(comboBoxDevicesModels.SelectedValue.ToString(), textBoxPrice.Text); int count = db.GetRowsCount("View_Devices"); HideButton(count - 1); labelCount.Content = count.ToString(); } } else MessageBox.Show("Некорректный ввод данных! Повторите ввод!", "Ошибка обновления таблицы", MessageBoxButton.OK, MessageBoxImage.Exclamation); } private void buttonUpdateClients_Click(object sender, RoutedEventArgs e) { if (textBoxSurnameClients.Background == Brushes.White && textBoxNameClients.Background == Brushes.White && textBoxPatronymicClients.Background == Brushes.White && textBoxPhoneClients.Background == Brushes.White && textBoxAddresClients.Background == Brushes.White) { if (canSelect) { row = dataGrid.SelectedItem as DataRowView; db.UpdateTableClientsStaff("Clients", textBoxSurnameClients.Text, textBoxNameClients.Text, textBoxPatronymicClients.Text, textBoxPhoneClients.Text, textBoxAddresClients.Text, row[0].ToString()); dataGrid.SelectedIndex = 0; } else { if (db.CheckNames("ClientsAddres", textBoxAddresClients.Text) != 1) { db.InsertTableClientsStaff("Clients", textBoxSurnameClients.Text, textBoxNameClients.Text, textBoxPatronymicClients.Text, textBoxPhoneClients.Text, textBoxAddresClients.Text, true); int count = db.GetRowsCount("View_Clients"); HideButton(count - 1); labelCount.Content = count.ToString(); } else MessageBox.Show("Клиент с таким адресом уже существует!", "Ошибка данных", MessageBoxButton.OK, MessageBoxImage.Error); } } else MessageBox.Show("Некорректный ввод данных! Повторите ввод!", "Ошибка обновления таблицы", MessageBoxButton.OK, MessageBoxImage.Exclamation); } private void buttonUpdateStaff_Click(object sender, RoutedEventArgs e) { if (textBoxSurnameStaff.Background == Brushes.White && textBoxNameStaff.Background == Brushes.White && textBoxPatronymicStaff.Background == Brushes.White && textBoxPhoneStaff.Background == Brushes.White && textBoxAddresStaff.Background == Brushes.White) { if (canSelect) { row = dataGrid.SelectedItem as DataRowView; db.UpdateTableClientsStaff("Staff", textBoxSurnameStaff.Text, textBoxNameStaff.Text, textBoxPatronymicStaff.Text, textBoxPhoneStaff.Text, textBoxAddresStaff.Text, row[0].ToString()); dataGrid.SelectedIndex = 0; } else { if (db.CheckNames("StaffAddres", textBoxAddresStaff.Text) != 1) { db.InsertTableClientsStaff("Staff", textBoxSurnameStaff.Text, textBoxNameStaff.Text, textBoxPatronymicStaff.Text, textBoxPhoneStaff.Text, textBoxAddresStaff.Text, true); int count = db.GetRowsCount("View_Staff"); HideButton(count - 1); labelCount.Content = count.ToString(); } else MessageBox.Show("Сотрудник с таким адресом уже существует!", "Ошибка данных", MessageBoxButton.OK, MessageBoxImage.Error); } } else MessageBox.Show("Некорректный ввод данных! Повторите ввод!", "Ошибка обновления таблицы", MessageBoxButton.OK, MessageBoxImage.Exclamation); } private void buttonUpdateSupplier_Click(object sender, RoutedEventArgs e) { if (textBoxSupplier.Background == Brushes.White && textBoxPhoneSupplier.Background == Brushes.White && textBoxAddresSupplier.Background == Brushes.White) { if (canSelect) { row = dataGrid.SelectedItem as DataRowView; db.UpdateTableSuppliers(textBoxSupplier.Text, textBoxPhoneSupplier.Text, textBoxAddresSupplier.Text, row[0].ToString()); dataGrid.SelectedIndex = 0; } else { if (db.CheckNames("Supplier", textBoxSupplier.Text) != 1) { db.InsertTableSuppliers(textBoxSupplier.Text, textBoxPhoneSupplier.Text, textBoxAddresSupplier.Text); int count = db.GetRowsCount("View_Suppliers"); HideButton(count - 1); labelCount.Content = count.ToString(); } else MessageBox.Show("Поставщик с таким названием уже существует!", "Ошибка данных", MessageBoxButton.OK, MessageBoxImage.Error); } } else MessageBox.Show("Некорректный ввод данных! Повторите ввод!", "Ошибка обновления таблицы", MessageBoxButton.OK, MessageBoxImage.Exclamation); } private void buttonUpdateApplication_Click(object sender, RoutedEventArgs e) { if (comboBoxAppClients.Background == Brushes.White && comboBoxAppStaff.Background == Brushes.White && textBoxDate.Background == Brushes.White) { if (canSelect) { row = dataGrid.SelectedItem as DataRowView; db.UpdateTableApplications(comboBoxAppClients.SelectedValue.ToString(), comboBoxAppStaff.SelectedValue.ToString(), textBoxDate.Text, row[0].ToString()); dataGrid.SelectedIndex = 0; } else { db.InsertTableApplications(comboBoxAppClients.SelectedValue.ToString(), comboBoxAppStaff.SelectedValue.ToString(), textBoxDate.Text); int count = db.GetRowsCount("View_Applications"); HideButton(count - 1); labelCount.Content = count.ToString(); } } else MessageBox.Show("Некорректный ввод данных! Повторите ввод!", "Ошибка обновления таблицы", MessageBoxButton.OK, MessageBoxImage.Exclamation); } private void buttonUpdateRecords_Click(object sender, RoutedEventArgs e) { if (comboBoxRecordsApplications.Background == Brushes.White && comboBoxRecordsDevices.Background == Brushes.White && textBoxCount.Background == Brushes.White) { if (canSelect) { row = dataGrid.SelectedItem as DataRowView; db.UpdateRecordsOfApplication(comboBoxRecordsApplications.SelectedValue.ToString(), comboBoxRecordsDevices.SelectedValue.ToString(), textBoxCount.Text, row[0].ToString()); dataGrid.SelectedIndex = 0; } else { db.InsertTableRecordsOfApplication(comboBoxRecordsApplications.SelectedValue.ToString(), comboBoxRecordsDevices.SelectedValue.ToString(), textBoxCount.Text); int count = db.GetRowsCount("View_RecordsOfApplication"); HideButton(count - 1); labelCount.Content = count.ToString(); } } else MessageBox.Show("Некорректный ввод данных! Повторите ввод!", "Ошибка обновления таблицы", MessageBoxButton.OK, MessageBoxImage.Exclamation); } private void buttonUpdateOrders_Click(object sender, RoutedEventArgs e) { if (comboBoxOrdersStaff.Background == Brushes.White && comboBoxOrdersDevices.Background == Brushes.White && textBoxCountOrder.Background == Brushes.White && textBoxDateOrder.Background == Brushes.White) { if (canSelect) { row = dataGrid.SelectedItem as DataRowView; db.UpdateOrders(comboBoxOrdersStaff.SelectedValue.ToString(), comboBoxOrdersDevices.SelectedValue.ToString(), textBoxCountOrder.Text, textBoxDateOrder.Text, row[0].ToString()); dataGrid.SelectedIndex = 0; } else { db.InsertTableOrders(comboBoxOrdersStaff.SelectedValue.ToString(), comboBoxOrdersDevices.SelectedValue.ToString(), textBoxCountOrder.Text, textBoxDateOrder.Text); int count = db.GetRowsCount("View_Orders"); HideButton(count - 1); labelCount.Content = count.ToString(); } } else MessageBox.Show("Некорректный ввод данных! Повторите ввод!", "Ошибка обновления таблицы", MessageBoxButton.OK, MessageBoxImage.Exclamation); } private void buttonUpdateDelivery_Click(object sender, RoutedEventArgs e) { if (comboBoxDeliverySupplier.Background == Brushes.White && comboBoxDeliveryOrder.Background == Brushes.White) { if (!canSelect) { db.InsertTableDelivery(comboBoxDeliverySupplier.SelectedValue.ToString(), comboBoxDeliveryOrder.SelectedValue.ToString()); int count = db.GetRowsCount("View_Delivery"); HideButton(count - 1); labelCount.Content = count.ToString(); } } else MessageBox.Show("Некорректный ввод данных! Повторите ввод!", "Ошибка обновления таблицы", MessageBoxButton.OK, MessageBoxImage.Exclamation); } private void buttonUpdateSales_Click(object sender, RoutedEventArgs e) { if (comboBoxSaleApp.Background == Brushes.White && textBoxDateSale.Background == Brushes.White) { if (canSelect) { row = dataGrid.SelectedItem as DataRowView; db.UpdateSales(comboBoxSaleApp.SelectedValue.ToString(), textBoxDateSale.Text, row[0].ToString()); dataGrid.SelectedIndex = 0; } else { db.InsertTableSales(comboBoxSaleApp.SelectedValue.ToString(), textBoxDateSale.Text); int count = db.GetRowsCount("View_Sales"); HideButton(count - 1); labelCount.Content = count.ToString(); } } else MessageBox.Show("Некорректный ввод данных! Повторите ввод!", "Ошибка обновления таблицы", MessageBoxButton.OK, MessageBoxImage.Exclamation); } private void buttonUpdateRecordsOfSales_Click(object sender, RoutedEventArgs e) { if (comboBoxRecordsOfSalesSale.Background == Brushes.White && comboBoxRecordsOfSalesRecords.Background == Brushes.White && textBoxCountRecords.Background == Brushes.White) { if (canSelect) { row = dataGrid.SelectedItem as DataRowView; db.UpdateRecordsOfSale(comboBoxRecordsOfSalesSale.SelectedValue.ToString(), comboBoxRecordsOfSalesRecords.SelectedValue.ToString(), textBoxCountRecords.Text, row[0].ToString()); dataGrid.SelectedIndex = 0; } else { db.InsertTableRecordsOfSale(comboBoxRecordsOfSalesSale.SelectedValue.ToString(), comboBoxRecordsOfSalesRecords.SelectedValue.ToString(), textBoxCountRecords.Text); int count = db.GetRowsCount("View_RecordsOfSale"); HideButton(count - 1); labelCount.Content = count.ToString(); } } else MessageBox.Show("Некорректный ввод данных! Повторите ввод!", "Ошибка обновления таблицы", MessageBoxButton.OK, MessageBoxImage.Exclamation); } private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (canSelect) { if (currGrid.Name == "gridModels") { db.FillComboBox(comboBoxModelsTypes, "TypesOfDevices", "ID_type", "Name"); db.FillComboBox(comboBoxModelsBrands, "Brands", "ID_brand", "Name"); db.SelectValueForComboBox(comboBoxModelsTypes, "FK_type"); db.SelectValueForComboBox(comboBoxModelsBrands, "FK_brand"); try { row = dataGrid.SelectedItem as DataRowView; if (comboBoxModelsTypes.Text == "" || comboBoxModelsTypes.Text.Contains("(удалено)")) comboBoxModelsTypes.Text = row["Тип"].ToString() + " (удалено)"; if (comboBoxModelsBrands.Text == "" || comboBoxModelsBrands.Text.Contains("(удалено)")) comboBoxModelsBrands.Text = row["Марка"].ToString() + " (удалено)"; } catch (NullReferenceException) { } } else if (currGrid.Name == "gridDevices") { db.FillComboBox(comboBoxDevicesModels, "View_Models", "ID_model", "-Устройство"); db.SelectValueForComboBox(comboBoxDevicesModels, "FK_model"); try { row = dataGrid.SelectedItem as DataRowView; if (comboBoxDevicesModels.Text == "" || comboBoxDevicesModels.Text.Contains("(удалено)")) comboBoxDevicesModels.Text = row["-For_CB"].ToString() + " (удалено)"; } catch (NullReferenceException) { } } else if (currGrid.Name == "gridApplications") { db.FillComboBox(comboBoxAppClients, "View_Clients", "ID_client", "-ФИО"); db.FillComboBox(comboBoxAppStaff, "View_Staff", "ID_staff", "-ФИО"); db.SelectValueForComboBox(comboBoxAppClients, "FK_client"); db.SelectValueForComboBox(comboBoxAppStaff, "FK_staff"); try { row = dataGrid.SelectedItem as DataRowView; if (comboBoxAppClients.Text == "" || comboBoxAppClients.Text.Contains("(удалено)")) comboBoxAppClients.Text = row["Клиент"].ToString() + " (удалено)"; if (comboBoxAppStaff.Text == "" || comboBoxAppStaff.Text.Contains("(удалено)")) comboBoxAppStaff.Text = row["Сотрудник"].ToString() + " (удалено)"; if (row["Статус"].ToString() == "Утверждён") { comboBoxAppStaff.IsEnabled = false; comboBoxAppClients.IsEnabled = false; textBoxDate.IsReadOnly = true; buttonNewClient.IsEnabled = false; buttonUpdateApplication.IsEnabled = false; } else { comboBoxAppStaff.IsEnabled = true; comboBoxAppClients.IsEnabled = true; textBoxDate.IsReadOnly = false; buttonNewClient.IsEnabled = true; buttonUpdateApplication.IsEnabled = true; } } catch (NullReferenceException) { } try { DateTime dt = DateTime.Parse(textBoxDate.Text, CultureInfo.CreateSpecificCulture("en-us")); textBoxDate.Clear(); textBoxDate.AppendText(dt.ToString()); } catch (FormatException) { } } else if (currGrid.Name == "gridRecords") { db.FillComboBox(comboBoxRecordsApplications, "View_Applications", "ID_application", "-Дата (Клиент)"); db.FillComboBox(comboBoxRecordsDevices, "View_Devices", "ID_device", "-Устройство (Цена)"); db.SelectValueForComboBox(comboBoxRecordsApplications, "FK_application"); db.SelectValueForComboBox(comboBoxRecordsDevices, "FK_device"); try { row = dataGrid.SelectedItem as DataRowView; if (comboBoxRecordsApplications.Text == "" || comboBoxRecordsApplications.Text.Contains("(отсутствует)")) { comboBoxRecordsApplications.Text = row["-For_CB1"].ToString() + " (отсутствует)"; comboBoxRecordsApplications.IsEnabled = false; comboBoxRecordsDevices.IsEnabled = false; textBoxCount.IsReadOnly = true; buttonUpdateRecords.IsEnabled = false; } else { comboBoxRecordsApplications.IsEnabled = true; comboBoxRecordsDevices.IsEnabled = true; textBoxCount.IsReadOnly = false; buttonUpdateRecords.IsEnabled = true; } if (comboBoxRecordsDevices.Text == "" || comboBoxRecordsDevices.Text.Contains("(удалено)")) comboBoxRecordsDevices.Text = row["-For_CB2"].ToString() + " (удалено)"; } catch (NullReferenceException) { } } else if (currGrid.Name == "gridOrders") { db.FillComboBox(comboBoxOrdersStaff, "View_Staff", "ID_staff", "-ФИО"); db.FillComboBox(comboBoxOrdersDevices, "View_Devices", "ID_device", "-Устройство (Цена)"); db.SelectValueForComboBox(comboBoxOrdersStaff, "FK_staff"); db.SelectValueForComboBox(comboBoxOrdersDevices, "FK_device"); try { row = dataGrid.SelectedItem as DataRowView; if (comboBoxOrdersStaff.Text == "" || comboBoxOrdersStaff.Text.Contains("(удалено)")) comboBoxOrdersStaff.Text = row["Сотрудник"].ToString() + " (удалено)"; if (comboBoxOrdersDevices.Text == "" || comboBoxOrdersDevices.Text.Contains("(удалено)")) comboBoxOrdersDevices.Text = row["-For_CB"].ToString() + " (удалено)"; if (row["Статус"].ToString() == "Закрыт") { comboBoxOrdersStaff.IsEnabled = false; comboBoxOrdersDevices.IsEnabled = false; textBoxCountOrder.IsReadOnly = true; textBoxDateOrder.IsReadOnly = true; } else { comboBoxOrdersStaff.IsEnabled = true; comboBoxOrdersDevices.IsEnabled = true; textBoxCountOrder.IsReadOnly = false; textBoxDateOrder.IsReadOnly = false; } } catch (NullReferenceException) { } try { DateTime dt = DateTime.Parse(textBoxDateOrder.Text, CultureInfo.CreateSpecificCulture("en-us")); textBoxDateOrder.Clear(); textBoxDateOrder.AppendText(dt.ToString()); } catch (FormatException) { } } else if (currGrid.Name == "gridDelivery") { db.FillComboBox(comboBoxDeliverySupplier, "Suppliers", "ID_supplier", "Name"); db.FillComboBox(comboBoxDeliveryOrder, "View_Orders", "ID_order", "-Устройство (Дата)"); db.SelectValueForComboBox(comboBoxDeliverySupplier, "FK_supplier"); db.SelectValueForComboBox(comboBoxDeliveryOrder, "FK_order"); try { row = dataGrid.SelectedItem as DataRowView; if (comboBoxDeliverySupplier.Text == "" || comboBoxDeliverySupplier.Text.Contains("(удалено)")) comboBoxDeliverySupplier.Text = row["Поставщик"].ToString() + " (удалено)"; comboBoxDeliveryOrder.Text = row["Заказ"].ToString(); } catch (NullReferenceException) { } } else if (currGrid.Name == "gridStorage") { try { DateTime dt = DateTime.Parse(textBoxStorageDate.Text, CultureInfo.CreateSpecificCulture("en-us")); textBoxStorageDate.Clear(); textBoxStorageDate.AppendText(dt.ToString()); } catch (FormatException) { } } else if (currGrid.Name == "gridSales") { db.FillComboBox(comboBoxSaleApp, "View_Applications", "ID_application", "-Дата (Клиент)"); db.SelectValueForComboBox(comboBoxSaleApp, "FK_application"); try { row = dataGrid.SelectedItem as DataRowView; comboBoxSaleApp.Text = row["-For_CB"].ToString(); } catch (NullReferenceException) { } try { DateTime dt = DateTime.Parse(textBoxDateSale.Text, CultureInfo.CreateSpecificCulture("en-us")); textBoxDateSale.Clear(); textBoxDateSale.AppendText(dt.ToString()); } catch (FormatException) { } } else if (currGrid.Name == "gridRecordsOfSales") { db.FillComboBox(comboBoxRecordsOfSalesSale, "View_Sales", "ID_sale", "-Дата (Клиент)"); db.SelectValueForComboBox(comboBoxRecordsOfSalesSale, "FK_sale"); db.SelectValueForComboBox(comboBoxRecordsOfSalesRecords, "FK_record_app"); try { row = dataGrid.SelectedItem as DataRowView; comboBoxRecordsOfSalesRecords.Text = row["-For_CB"].ToString(); } catch (NullReferenceException) { } } } else dataGrid.SelectedItem = null; } private void buttonNewClient_Click(object sender, RoutedEventArgs e) { NewClientWindow form = new NewClientWindow(db); form.ShowDialog(); if (form.GetStatus()) { db.FillComboBox(comboBoxAppClients, "View_Clients", "ID_client", "-ФИО"); comboBoxAppClients.SelectedValue = db.GetID("Clients", "ID_client"); } } private void HideButton(int row) { buttonCancel.Visibility = Visibility.Hidden; canSelect = true; dataGrid.SelectedIndex = row; if (currGrid.Name == "gridApplications") textBoxDate.IsReadOnly = false; else if (currGrid.Name == "gridDelivery") { comboBoxDeliverySupplier.IsEnabled = false; comboBoxDeliveryOrder.IsEnabled = false; buttonUpdateDelivery.Visibility = Visibility.Hidden; } else if (currGrid.Name == "gridSales") { comboBoxSaleApp.IsEnabled = false; textBoxDateSale.IsReadOnly = true; buttonUpdateSales.Visibility = Visibility.Hidden; } else if (currGrid.Name == "gridOrders") textBoxDateOrder.IsReadOnly = false; else if (currGrid.Name == "gridRecordsOfSales") { comboBoxRecordsOfSalesSale.IsEnabled = false; comboBoxRecordsOfSalesRecords.IsEnabled = false; textBoxCountRecords.IsReadOnly = true; buttonUpdateRecordsOfSales.Visibility = Visibility.Hidden; labelCountDevicesInRecords.Content = "Количество (доступно 0 шт.)"; } if (currGrid.Name == "gridBrands") dt = db.GetDataTable("View_Brands"); else if (currGrid.Name == "gridTypes") dt = db.GetDataTable("View_TypesOfDevices"); else if (currGrid.Name == "gridModels") dt = db.GetDataTable("View_Models"); else if (currGrid.Name == "gridDevices") dt = db.GetDataTable("View_Devices"); else if (currGrid.Name == "gridClients") dt = db.GetDataTable("View_Clients"); else if (currGrid.Name == "gridStaff") dt = db.GetDataTable("View_Staff"); else if (currGrid.Name == "gridSuppliers") dt = db.GetDataTable("View_Suppliers"); else if (currGrid.Name == "gridApplications") dt = db.GetDataTable("View_Applications"); else if (currGrid.Name == "gridRecords") dt = db.GetDataTable("View_RecordsOfApplication"); else if (currGrid.Name == "gridOrders") dt = db.GetDataTable("View_Orders"); else if (currGrid.Name == "gridStorage") dt = db.GetDataTable("View_Storage"); else if (currGrid.Name == "gridDelivery") dt = db.GetDataTable("View_Delivery"); else if (currGrid.Name == "gridSales") dt = db.GetDataTable("View_Sales"); else if (currGrid.Name == "gridRecordsOfSales") dt = db.GetDataTable("View_RecordsOfSale"); } private void buttonAdd_Click(object sender, RoutedEventArgs e) { if (currGrid.Name != "gridStorage") { buttonCancel.Visibility = Visibility.Visible; canSelect = false; dataGrid.SelectedIndex = -1; } if (currGrid.Name == "gridBrands") textBoxBrand.Clear(); else if (currGrid.Name == "gridTypes") textBoxType.Clear(); else if (currGrid.Name == "gridModels") { comboBoxModelsTypes.Text = ""; comboBoxModelsBrands.Text = ""; textBoxModel.Clear(); } else if (currGrid.Name == "gridDevices") { comboBoxDevicesModels.Text = ""; textBoxPrice.Clear(); } else if (currGrid.Name == "gridClients") { textBoxSurnameClients.Clear(); textBoxNameClients.Clear(); textBoxPatronymicClients.Clear(); textBoxPhoneClients.Clear(); textBoxAddresClients.Clear(); } else if (currGrid.Name == "gridStaff") { textBoxSurnameStaff.Clear(); textBoxNameStaff.Clear(); textBoxPatronymicStaff.Clear(); textBoxPhoneStaff.Clear(); textBoxAddresStaff.Clear(); } else if (currGrid.Name == "gridSuppliers") { textBoxSupplier.Clear(); textBoxPhoneSupplier.Clear(); textBoxAddresSupplier.Clear(); } else if (currGrid.Name == "gridApplications") { comboBoxAppStaff.IsEnabled = true; comboBoxAppClients.IsEnabled = true; textBoxDate.IsReadOnly = true; buttonNewClient.IsEnabled = true; buttonUpdateApplication.IsEnabled = true; comboBoxAppClients.Text = ""; comboBoxAppStaff.Text = ""; } else if (currGrid.Name == "gridRecords") { comboBoxRecordsApplications.IsEnabled = true; comboBoxRecordsDevices.IsEnabled = true; textBoxCount.IsReadOnly = false; buttonUpdateRecords.IsEnabled = true; comboBoxRecordsApplications.Text = ""; comboBoxRecordsDevices.Text = ""; textBoxCount.Clear(); labelCountDevices.Content = "Количество (доступно 0 шт.)"; } else if (currGrid.Name == "gridOrders") { comboBoxOrdersStaff.IsEnabled = true; comboBoxOrdersDevices.IsEnabled = true; textBoxCountOrder.IsReadOnly = false; textBoxDateOrder.IsReadOnly = true; comboBoxOrdersStaff.Text = ""; comboBoxOrdersDevices.Text = ""; } else if (currGrid.Name == "gridDelivery") { comboBoxDeliverySupplier.IsEnabled = true; comboBoxDeliveryOrder.IsEnabled = true; buttonUpdateDelivery.Visibility = Visibility.Visible; comboBoxDeliverySupplier.Text = ""; comboBoxDeliveryOrder.Text = ""; } else if (currGrid.Name == "gridSales") { comboBoxSaleApp.IsEnabled = true; buttonUpdateSales.Visibility = Visibility.Visible; comboBoxSaleApp.Text = ""; textBoxDateSale.IsReadOnly = true; } else if (currGrid.Name == "gridRecordsOfSales") { comboBoxRecordsOfSalesSale.IsEnabled = true; comboBoxRecordsOfSalesRecords.IsEnabled = true; textBoxCountRecords.IsReadOnly = false; buttonUpdateRecordsOfSales.Visibility = Visibility.Visible; comboBoxRecordsOfSalesSale.Text = ""; comboBoxRecordsOfSalesRecords.Text = ""; textBoxCountRecords.Clear(); labelCountDevicesInRecords.Content = "Количество (доступно 0 шт.)"; } } private void buttonCancel_Click(object sender, RoutedEventArgs e) { HideButton(0); } private void buttonDelete_Click(object sender, RoutedEventArgs e) { if (currGrid.Name == "gridBrands") { row = dataGrid.SelectedItem as DataRowView; db.DeleteFromTable("Brands", dataGrid.Columns[0].Header.ToString(), row[0].ToString()); HideButton(0); labelCount.Content = db.GetRowsCount("View_Brands").ToString(); } else if (currGrid.Name == "gridTypes") { row = dataGrid.SelectedItem as DataRowView; db.DeleteFromTable("TypesOfDevices", dataGrid.Columns[0].Header.ToString(), row[0].ToString()); HideButton(0); labelCount.Content = db.GetRowsCount("View_TypesOfDevices").ToString(); } else if (currGrid.Name == "gridModels") { row = dataGrid.SelectedItem as DataRowView; db.DeleteFromTable("Models", dataGrid.Columns[0].Header.ToString(), row[0].ToString()); HideButton(0); labelCount.Content = db.GetRowsCount("View_Models").ToString(); } else if (currGrid.Name == "gridDevices") { row = dataGrid.SelectedItem as DataRowView; db.DeleteFromTable("Devices", dataGrid.Columns[0].Header.ToString(), row[0].ToString()); HideButton(0); labelCount.Content = db.GetRowsCount("View_Devices").ToString(); } else if (currGrid.Name == "gridClients") { row = dataGrid.SelectedItem as DataRowView; db.DeleteFromTable("Clients", dataGrid.Columns[0].Header.ToString(), row[0].ToString()); HideButton(0); labelCount.Content = db.GetRowsCount("View_Clients").ToString(); } else if (currGrid.Name == "gridStaff") { row = dataGrid.SelectedItem as DataRowView; db.DeleteFromTable("Staff", dataGrid.Columns[0].Header.ToString(), row[0].ToString()); HideButton(0); labelCount.Content = db.GetRowsCount("View_Staff").ToString(); } else if (currGrid.Name == "gridSuppliers") { row = dataGrid.SelectedItem as DataRowView; db.DeleteFromTable("Suppliers", dataGrid.Columns[0].Header.ToString(), row[0].ToString()); HideButton(0); labelCount.Content = db.GetRowsCount("View_Suppliers").ToString(); } else if (currGrid.Name == "gridApplications") { row = dataGrid.SelectedItem as DataRowView; db.DeleteFromTable("Applications", dataGrid.Columns[0].Header.ToString(), row[0].ToString()); HideButton(0); labelCount.Content = db.GetRowsCount("View_Applications").ToString(); } else if (currGrid.Name == "gridRecords") { row = dataGrid.SelectedItem as DataRowView; db.DeleteRecordOfApplication(row[0].ToString()); HideButton(0); labelCount.Content = db.GetRowsCount("View_RecordsOfApplication").ToString(); } else if (currGrid.Name == "gridOrders") { row = dataGrid.SelectedItem as DataRowView; db.DeleteFromTable("Orders", dataGrid.Columns[0].Header.ToString(), row[0].ToString()); HideButton(0); labelCount.Content = db.GetRowsCount("View_Orders").ToString(); } else if (currGrid.Name == "gridDelivery") { row = dataGrid.SelectedItem as DataRowView; db.DeleteFromTable("Delivery", dataGrid.Columns[0].Header.ToString(), row[0].ToString()); HideButton(0); labelCount.Content = db.GetRowsCount("View_Delivery").ToString(); } else if (currGrid.Name == "gridSales") { row = dataGrid.SelectedItem as DataRowView; db.DeleteFromTable("Sales", dataGrid.Columns[0].Header.ToString(), row[0].ToString()); HideButton(0); labelCount.Content = db.GetRowsCount("View_Sales").ToString(); } else if (currGrid.Name == "gridRecordsOfSales") { row = dataGrid.SelectedItem as DataRowView; db.DeleteRecordOfSale(row[0].ToString()); HideButton(0); labelCount.Content = db.GetRowsCount("View_RecordsOfSale").ToString(); } } private void PreviewTextInputCheck(object sender, TextCompositionEventArgs e) { if (!Checks.TextInput(sender as TextBox, e)) e.Handled = true; } private void PreviewKeyDownCheck(object sender, KeyEventArgs e) { if (e.Key == Key.Space) e.Handled = true; } private void TextChangedCheck(object sender, TextChangedEventArgs e) { Checks.TextChanged(sender as TextBox, countDevices); } private void SelectionChangedCheck(object sender, SelectionChangedEventArgs e) { if ((sender as ComboBox).Name == "comboBoxRecordsDevices") { try { countDevices = db.GetCountDevicesInStorage((e.AddedItems[0] as DataRowView).Row["ID_device"].ToString()); int count; if (textBoxCount.Text == "") count = 0; else count = Convert.ToInt32(textBoxCount.Text); if (count > countDevices || count == 0) textBoxCount.Background = new SolidColorBrush(Color.FromRgb(255, 197, 197)); else textBoxCount.Background = Brushes.White; } catch (IndexOutOfRangeException) { } labelCountDevices.Content = "Количество (доступно " + countDevices.ToString() + " шт.)"; } if ((sender as ComboBox).Name == "comboBoxRecordsOfSalesSale") { try { int fk = db.GetFkApplication((e.AddedItems[0] as DataRowView).Row["ID_sale"].ToString()); db.FillComboBoxWithCondition(comboBoxRecordsOfSalesRecords, fk.ToString()); db.SelectValueForComboBox(comboBoxRecordsOfSalesRecords, "FK_record_app"); } catch (IndexOutOfRangeException) { } } if ((sender as ComboBox).Name == "comboBoxRecordsOfSalesRecords") { try { countDevices = db.GetCountDevicesInRecordsOfApplication((e.AddedItems[0] as DataRowView).Row["ID_record"].ToString()); } catch (IndexOutOfRangeException) { } labelCountDevicesInRecords.Content = "Количество (доступно " + countDevices.ToString() + " шт.)"; } Checks.SelectionChanged(sender as ComboBox, e); } private void textBoxFilter_GotFocus(object sender, RoutedEventArgs e) { if (textBoxFilter.Text == "Поиск...") textBoxFilter.Text = ""; } private void textBoxFilter_LostFocus(object sender, RoutedEventArgs e) { if (textBoxFilter.Text == "") textBoxFilter.Text = "Поиск..."; } private void Search(string value) { DataTable newDT = dt.Clone(); newDT.Clear(); foreach (DataRow row in dt.Rows) { foreach (DataColumn column in dt.Columns) { try { if (column.DataType == typeof(string) && !column.ColumnName.Contains("-") && !column.ColumnName.Contains("_")) { if (row.Field<string>(column.ColumnName).ToLower().Contains(value.ToLower())) { newDT.ImportRow(row); break; } } if (column.DataType == typeof(DateTime) && !column.ColumnName.Contains("-") && !column.ColumnName.Contains("_")) { if (row.Field<DateTime>(column.ColumnName) > DateTime.Parse(value + " 00:00:00") && row.Field<DateTime>(column.ColumnName) < DateTime.Parse(value + " 23:59:59")) { newDT.ImportRow(row); break; } } if (column.DataType == typeof(int) && !column.ColumnName.Contains("-") && !column.ColumnName.Contains("_")) { if (value.StartsWith("=")) { if (row.Field<int>(column.ColumnName) == int.Parse(value.Substring(1))) { newDT.ImportRow(row); break; } } else if (value.StartsWith(">")) { if (row.Field<int>(column.ColumnName) > int.Parse(value.Substring(1))) { newDT.ImportRow(row); break; } } else if (value.StartsWith("<")) { if (row.Field<int>(column.ColumnName) < int.Parse(value.Substring(1))) { newDT.ImportRow(row); break; } } else { if (row.Field<int>(column.ColumnName).ToString().Contains(value)) { newDT.ImportRow(row); break; } } } } catch (Exception) { } } } dataGrid.ItemsSource = newDT.DefaultView; dataGrid.SelectedIndex = 0; } private void buttonReset_Click(object sender, RoutedEventArgs e) { dataGrid.ItemsSource = dt.DefaultView; dataGrid.SelectedIndex = 0; textBoxFilter.Text = "Поиск..."; } private void textBoxFilter_TextChanged(object sender, TextChangedEventArgs e) { try { if (textBoxFilter.Text == "" || textBoxFilter.Text == "Поиск..." || (textBoxFilter.Text.StartsWith(">") && textBoxFilter.Text.Length == 1) || (textBoxFilter.Text.StartsWith("<") && textBoxFilter.Text.Length == 1) || (textBoxFilter.Text.StartsWith("=") && textBoxFilter.Text.Length == 1)) { dataGrid.ItemsSource = dt.DefaultView; dataGrid.SelectedIndex = 0; } else Search(textBoxFilter.Text); } catch (Exception) { } } private void buttonReport_Click(object sender, RoutedEventArgs e) { if (MessageBox.Show("Формирование отчета может занять некоторое время! Продолжить?", "Формирование отчета", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes) { bool isHeader = true; Excel.Application ExcelApp = new Excel.Application(); Excel.Workbook ExcelBook = ExcelApp.Workbooks.Add(System.Reflection.Missing.Value); Excel.Worksheet ExcelWorkSheet = (Excel.Worksheet)ExcelBook.Sheets[1]; int i = 3; int j = 2; foreach (DataRow row in (dataGrid.ItemsSource as DataView).Table.Rows) { foreach (DataColumn column in (dataGrid.ItemsSource as DataView).Table.Columns) { if (!column.ColumnName.Contains("-") && !column.ColumnName.Contains("_")) { if (isHeader) { ExcelWorkSheet.Cells[i - 1, j].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; ExcelWorkSheet.Cells[i - 1, j].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(111, 126, 149)); ExcelWorkSheet.Cells[i - 1, j].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White); ExcelWorkSheet.Cells[i - 1, j] = column.ColumnName; } if (column.DataType == typeof(string)) { if (i % 2 == 0) ExcelWorkSheet.Cells[i, j].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(251, 252, 254)); else ExcelWorkSheet.Cells[i, j].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(255, 255, 255)); ExcelWorkSheet.Cells[i, j] = row.Field<string>(column); } if (column.DataType == typeof(int)) { if (i % 2 == 0) ExcelWorkSheet.Cells[i, j].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(251, 252, 254)); else ExcelWorkSheet.Cells[i, j].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(255, 255, 255)); ExcelWorkSheet.Cells[i, j] = row.Field<int>(column); } if (column.DataType == typeof(DateTime)) { if (i % 2 == 0) ExcelWorkSheet.Cells[i, j].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(251, 252, 254)); else ExcelWorkSheet.Cells[i, j].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(255, 255, 255)); ExcelWorkSheet.Cells[i, j] = row.Field<DateTime>(column); } j++; } } i++; j = 2; isHeader = false; } ExcelWorkSheet.Columns.AutoFit(); ExcelWorkSheet.Rows.RowHeight = 20; ExcelWorkSheet.Rows.VerticalAlignment = Excel.XlHAlign.xlHAlignCenter; ExcelApp.Visible = true; ExcelApp.UserControl = true; } } } }<file_sep>using System; using System.Windows; using System.Windows.Input; using System.Data; using System.Data.SqlClient; namespace DB_Store { public partial class LoginWindow : Window { bool close = true; SqlConnection connecion; public LoginWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { Animation animation = new Animation(); animation.MoveLoginWindow(this); } private void grid_MouseDown(object sender, MouseButtonEventArgs e) { try { DragMove(); } catch (InvalidOperationException) { } } private void buttonClose_Click(object sender, RoutedEventArgs e) { close = true; Close(); } public bool GetStatus() { return close; } public SqlConnection GetConnection() { return connecion; } private void buttonLogin_Click(object sender, RoutedEventArgs e) { connecion = new SqlConnection("Data Source=ALEXANDER;Initial Catalog=DB_Store;User ID=" + textBoxLogin.Text + ";Password=" + <PASSWORD> + ";"); try { connecion.Open(); } catch (SqlException) { MessageBox.Show("Неверный логин или пароль!", "Ошибка авторизации", MessageBoxButton.OK, MessageBoxImage.Error); } if (connecion.State == ConnectionState.Open) { close = false; Close(); } } private void textBoxLogin_PreviewTextInput(object sender, TextCompositionEventArgs e) { int code = Convert.ToChar(e.Text); if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) return; else e.Handled = true; } private void textBoxLogin_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Space) e.Handled = true; } private void textBoxLogin_LostFocus(object sender, RoutedEventArgs e) { if (textBoxLogin.Text == "") textBoxLogin.Text = "Имя пользователя"; } private void textBoxLogin_GotFocus(object sender, RoutedEventArgs e) { if (textBoxLogin.Text == "Имя пользователя") textBoxLogin.Text = ""; } private void passwordBox_GotFocus(object sender, RoutedEventArgs e) { if (passwordBox.Password == "<PASSWORD>") passwordBox.Password = ""; } private void passwordBox_LostFocus(object sender, RoutedEventArgs e) { if (passwordBox.Password == "") passwordBox.Password = "<PASSWORD>"; } } }
4f27382d87321ae9058a5f9ae79f97978a33271b
[ "Markdown", "C#" ]
7
C#
imalexoff/ComputerStoreWPF
435aa2a1a4fb456a4603a1107e00fb933e505a2e
4deb81823edc30abc0fc6e7df4ad16a057f343ee