blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
df8a9b21e7986da4ed5870f32f46cbd462e6e472 | Java | sizmoj/sizmoj-mybatis | /src/main/java/com/sizmoj/sizmoj/modules/sys/mapper/LogMapper.java | UTF-8 | 979 | 1.859375 | 2 | [] | no_license | package com.sizmoj.sizmoj.modules.sys.mapper;
import java.util.Date;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.sizmoj.sizmoj.common.persistence.MybatisRepository;
import com.sizmoj.sizmoj.modules.sys.entity.Log;
@MybatisRepository
public interface LogMapper {
public List<Log> findAllList();
public List<Log> findByPage(@Param("prefix") long prefix, @Param("suffix") long suffix);
public long count();
public long add(Log log);
public Log findById(long id);
public List<Log> findByCondition(@Param("id") Long id, @Param("requestUri") String requestUri,
@Param("exception") String exception, @Param("beginDate") Date beginDate, @Param("endDate") Date endDate, @Param("prefix") long prefix, @Param("suffix") long suffix);
public long findByConditionCount(@Param("id") Long id, @Param("requestUri") String requestUri,
@Param("exception") String exception, @Param("beginDate") Date beginDate, @Param("endDate") Date endDate);
}
| true |
2e937d9198df36877b3552bfc37761158341f08a | Java | mayaracaroline/bookstore | /src/servico/CalcularFrete.java | ISO-8859-1 | 2,934 | 2.65625 | 3 | [] | no_license | package servico;
import java.time.LocalDate;
import java.util.HashMap;
import dominio.DadosEntrega;
import dominio.Endereco;
import dominio.EntidadeDominio;
import util.Formatter;
import util.Resultado;
public class CalcularFrete implements IServico {
public Resultado calcularFrete(EntidadeDominio entidade) {
Resultado resultado = new Resultado();
Endereco endereco = (Endereco) entidade;
String cep = endereco.getCep();
HashMap<String, String> mapValorFretePorRegiao = new HashMap<>();
// 0 - Grande So Paulo
// 1 - Interior de So Paulo
// 2 - RJ e ES
// 3 - MG
// 4 - BA e SE
// 5 - PE, AL, PB, RN
// 6 - CE, PI, MA, AP, AM, RR, AC
// 7 - DF, GO, RO, TO, MT, MS
// 8 - PR e SC
// 9 - RS
mapValorFretePorRegiao.put("0", "10");
mapValorFretePorRegiao.put("1", "15");
mapValorFretePorRegiao.put("2", "20");
mapValorFretePorRegiao.put("3", "25");
mapValorFretePorRegiao.put("4", "25");
mapValorFretePorRegiao.put("5", "25");
mapValorFretePorRegiao.put("6", "25");
mapValorFretePorRegiao.put("7", "25");
mapValorFretePorRegiao.put("8", "25");
mapValorFretePorRegiao.put("9", "25");
String regiao = cep.substring(0, 1);
String frete = mapValorFretePorRegiao.get(regiao);
resultado.sucesso(frete);
return resultado;
}
@Override
public Resultado executarServico(EntidadeDominio entidade) {
Resultado resultado = new Resultado();
DadosEntrega dadosEntrega = (DadosEntrega) entidade;
Endereco endereco = dadosEntrega.getEnderecoEntrega();
String cep = endereco.getCep();
LocalDate dataEntrega;
int regiao = 0;
HashMap<Integer, Double> mapValorFretePorRegiao = new HashMap<>();
// 0 - Grande So Paulo
// 1 - Interior de So Paulo
// 2 - RJ e ES
// 3 - MG
// 4 - BA e SE
// 5 - PE, AL, PB, RN
// 6 - CE, PI, MA, AP, AM, RR, AC
// 7 - DF, GO, RO, TO, MT, MS
// 8 - PR e SC
// 9 - RS
mapValorFretePorRegiao.put(0, 10.00);
mapValorFretePorRegiao.put(1, 15.00);
mapValorFretePorRegiao.put(2, 20.00);
mapValorFretePorRegiao.put(3, 25.00);
mapValorFretePorRegiao.put(4, 25.00);
mapValorFretePorRegiao.put(5, 25.00);
mapValorFretePorRegiao.put(6, 25.00);
mapValorFretePorRegiao.put(7, 25.00);
mapValorFretePorRegiao.put(8, 25.00);
mapValorFretePorRegiao.put(9, 25.00);
regiao = Formatter.stringToInt(cep.substring(0, 1));
double frete = mapValorFretePorRegiao.get(regiao);
if (regiao == 0) {
dataEntrega = LocalDate.now().plusDays(3);
} else {
dataEntrega = LocalDate.now().plusDays(7);
}
dadosEntrega.setDataEntrega(dataEntrega);
dadosEntrega.setFrete(frete);
dadosEntrega.setEnderecoEntrega(endereco);
resultado.setResultado(dadosEntrega);
return resultado;
}
}
| true |
e3d13b29cd18b861f83b72115f302b85ecf717e4 | Java | BhawanaRani/TrainingMaterial | /Training/src/com/exilant/day2/WorkerInterface.java | UTF-8 | 83 | 1.75 | 2 | [] | no_license | package com.exilant.day2;
public interface WorkerInterface {
void doSomeWork();
}
| true |
fd7dad07d87c0ee8821f3c8ed3020a4950ebdf9c | Java | miguel-resource/Quiz | /src/com/company/view/CapturarPreguntasDialog.java | UTF-8 | 7,523 | 2.515625 | 3 | [] | no_license | package com.company.view;
import com.company.exception.PreguntaNoValidaException;
import com.company.exception.RespuestaRepetidaException;
import com.company.exception.RespuestaVaciaException;
import com.company.model.Pregunta;
import com.company.view.CapturarPreguntasInterface;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CapturarPreguntasDialog extends JDialog {
private JLabel lbPregunta;
private JTextField edtPregunta;
private JPanel pnlPregunta;
private JLabel lbrespuesta1;
private JTextField edtRespuesta1;
private JPanel pnlRespuesta1;
private JLabel lbRespuesta2;
private JTextField edtRespuesta2;
private JPanel pnlRespuesta2;
private JLabel lbRespuesta3;
private JTextField edtRespuesta3;
private JPanel pnlRespuesta3;
private JLabel lbRespuesta4;
private JTextField edtRespuesta4;
private JPanel pnlRespuesta4;
private JLabel lbRespuestaCorrecta;
private JComboBox cbRespuesta;
private JPanel pnlRespuestaCorrecta;
private JLabel lbMateria;
private JComboBox cbMateria;
private JPanel pnlMateria;
private JButton btnGenerar;
private JButton btnCancelar;
private JPanel pnlBotones;
private CapturarPreguntasInterface listener;
public CapturarPreguntasDialog(JFrame parent){
super(parent, true);
super.setLayout(new FlowLayout());
super.setDefaultCloseOperation(2);
super.setLocationRelativeTo(null);
super.setSize(330, 270);
lbPregunta = new JLabel("Pregunta:");
edtPregunta = new JTextField(15);
pnlPregunta = new JPanel();
pnlPregunta.add(lbPregunta);
pnlPregunta.add(edtPregunta);
pnlPregunta.setLayout(new GridLayout(1,2,-35,0));
lbrespuesta1 = new JLabel("Respuesta 1:");
edtRespuesta1 = new JTextField(15);
pnlRespuesta1 = new JPanel();
pnlRespuesta1.add(lbrespuesta1);
pnlRespuesta1.add(edtRespuesta1);
pnlRespuesta1.setLayout(new GridLayout(1,2,-35,0));
lbRespuesta2 = new JLabel("Respuesta 2:");
edtRespuesta2 = new JTextField(15);
pnlRespuesta2 = new JPanel();
pnlRespuesta2.add(lbRespuesta2);
pnlRespuesta2.add(edtRespuesta2);
pnlRespuesta2.setLayout(new GridLayout(1,2,-35,0));
lbRespuesta3 = new JLabel("Respuesta 3:");
edtRespuesta3 = new JTextField(15);
pnlRespuesta3 = new JPanel();
pnlRespuesta3.add(lbRespuesta3);
pnlRespuesta3.add(edtRespuesta3);
pnlRespuesta3.setLayout(new GridLayout(1,2,-35,0));
lbRespuesta4 = new JLabel("Respuesta 4:");
edtRespuesta4 = new JTextField(15);
pnlRespuesta4 = new JPanel();
pnlRespuesta4.add(lbRespuesta4);
pnlRespuesta4.add(edtRespuesta4);
pnlRespuesta4.setLayout(new GridLayout(1,2,-35,0));
lbRespuestaCorrecta = new JLabel("Respuesta correcta:");
cbRespuesta = new JComboBox();
cbRespuesta.addItem("Respuesta 1");
cbRespuesta.addItem("Respuesta 2");
cbRespuesta.addItem("Respuesta 3");
cbRespuesta.addItem("Respuesta 4");
pnlRespuestaCorrecta = new JPanel();
pnlRespuestaCorrecta.add(lbRespuestaCorrecta);
pnlRespuestaCorrecta.add(cbRespuesta);
pnlRespuestaCorrecta.setLayout(new GridLayout(1,2,10,0));
lbMateria = new JLabel("Materia:");
cbMateria = new JComboBox();
cbMateria.addItem("Matemáticas");
cbMateria.addItem("POO");
cbMateria.addItem("Inglés");
cbMateria.addItem("Estadística");
cbMateria.addItem("Circuitos");
pnlMateria = new JPanel();
pnlMateria.add(lbMateria);
pnlMateria.add(cbMateria);
pnlMateria.setLayout(new GridLayout(1,2,-35,0));
btnGenerar = new JButton("Generar");
btnCancelar = new JButton("Cancelar");
pnlBotones = new JPanel();
pnlBotones.add(btnGenerar);
pnlBotones.add(btnCancelar);
btnGenerar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
try{
Pregunta pregunta = new Pregunta(
edtPregunta.getText(),
edtRespuesta1(),
edtRespuesta2(),
edtRespuesta3(),
edtRespuesta4(),
cbMateria.getSelectedIndex(),
cbRespuesta.getSelectedIndex()
);
listener.clickGenerar(pregunta);
} catch (RespuestaRepetidaException | RespuestaVaciaException | PreguntaNoValidaException e) {
JOptionPane.showMessageDialog(CapturarPreguntasDialog.this, e.getMessage(), "Error", 0);
}
edtPregunta.setText(null);
edtRespuesta1.setText(null);
edtRespuesta2.setText(null);
edtRespuesta3.setText(null);
edtRespuesta4.setText(null);
System.out.println("Se tuvo que limpiar el edt");
cbMateria.setSelectedIndex(0);
cbRespuesta.setSelectedIndex(0);
}
});
btnCancelar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
listener.clickCancelar();
}
});
super.add(pnlPregunta);
super.add(pnlRespuesta1);
super.add(pnlRespuesta2);
super.add(pnlRespuesta3);
super.add(pnlRespuesta4);
super.add(pnlRespuestaCorrecta);
super.add(pnlMateria);
super.add(pnlBotones);
super.setLocationRelativeTo(null);
super.setVisible(false);
}
public void setListener(CapturarPreguntasInterface listener) {
this.listener = listener;
}
public String edtRespuesta1() throws RespuestaVaciaException {
if(edtRespuesta1.getText().length() > 0){
return edtRespuesta1.getText();
}else {
throw new RespuestaVaciaException("No puedes dejar una respuesta vacía krnal");
}
}
public String edtRespuesta2() throws RespuestaVaciaException {
if(edtRespuesta2.getText().length() > 0){
return edtRespuesta2.getText();
}else {
throw new RespuestaVaciaException("No puedes dejar una respuesta vacía krnal");
}
}
public String edtRespuesta3() throws RespuestaVaciaException {
if(edtRespuesta3.getText().length() > 0){
return edtRespuesta3.getText();
}else {
throw new RespuestaVaciaException("No puedes dejar una respuesta vacía krnal");
}
}
public String edtRespuesta4() throws RespuestaVaciaException {
if(edtRespuesta4.getText().length() > 0){
return edtRespuesta4.getText();
}else {
throw new RespuestaVaciaException("No puedes dejar una respuesta vacía krnal");
}
}
public void clearTextField(){
edtPregunta.setText(null);
edtRespuesta1.setText(null);
edtRespuesta2.setText(null);
edtRespuesta3.setText(null);
edtRespuesta4.setText(null);
cbMateria.setSelectedIndex(0);
cbRespuesta.setSelectedIndex(0);
}
}
| true |
f8ac522536ee3f6cf19237500a369108d0ceefb4 | Java | saberwolaopo/sword-to-offer | /src/com/company/Main.java | UTF-8 | 1,609 | 3.25 | 3 | [] | no_license | package com.company;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.TreeMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.lang.Throwable;
import java.lang.Exception;
public class Main {
public static void main(String[] args) throws InterruptedException {
OuterClass.NestedStaticClass printer = new OuterClass.NestedStaticClass();
printer.printmsg();
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display();
OuterClass.InnerClass inner2 = new OuterClass().new InnerClass();
inner2.display();
TimeUnit.DAYS.sleep(1);
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
queue.offer("12");
queue.put("23");
queue.take();
ArrayBlockingQueue queue1 = new ArrayBlockingQueue(10);
queue1.put("1");
queue1.offer("2");
PrintWriter out = new PrintWriter(
new java.io.OutputStreamWriter(System.out), true);
out.println("Hello");
ThreadLocal local = new ThreadLocal();
local.set("1223");
}
}
class OuterClass {
private static String msg = "saber";
public static class NestedStaticClass {
public void printmsg() {
System.out.println("静态内部类:" + msg);
}
}
public class InnerClass {
public void display() {
System.out.println("非静态内部类:" + msg);
}
}
}
| true |
2c231c46148bf2cabbfe7f83556aa11fcdc54feb | Java | Eaydroid/cjyApplication | /app/src/main/java/com/more/cjy/designpattern/factory/VolkswagenFactory.java | UTF-8 | 603 | 2.921875 | 3 | [] | no_license | package com.more.cjy.designpattern.factory;
import com.more.cjy.designpattern.factory.car.Car;
import com.more.cjy.designpattern.factory.car.Jetta;
import com.more.cjy.designpattern.factory.car.Magotan;
/**
* {大众汽车生产工厂}
* <p>
* <p>
* 作者:cjy on 2018/4/16 14:05
* 邮箱:303592161@qq.com
*/
public class VolkswagenFactory extends CarFactory {
@Override
public Car createCar(int modelNo) {
if(modelNo == Car.JETTA) {
return new Jetta();
} else if(modelNo == Car.MAGOTAN) {
return new Magotan();
}
return null;
}
}
| true |
343343086291bd411343fffccda8cc70831072f8 | Java | SanjanaKudige/JUnitTests | /JUnit Test Files/Problem1ClassTest.java | UTF-8 | 1,326 | 2.5 | 2 | [] | no_license | package com ;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import static junitparams.JUnitParamsRunner.$;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.runner.RunWith;
@RunWith(JUnitParamsRunner.class)
public class Problem1ClassTest {
private Problem1Class prob1 ;
@SuppressWarnings("unused")
private static final Object[] parametersForProblem1ClassTest () {
return $(
// Parameters are: Balance1 Balance2
//Test case 1
$(-0.01, -500.01),
//Test case 2
$(0.00, -150.00),
//Test case 3
$(799.99, 812.38),
//Test case 4
$(3499.99, 3589.23),
//Test case 5
$(249999.99, 257887.48),
//Test case 6
$(250000.00, 258225.00),
//Test case 7
$(-1000.00, -1500.00),
//Test case 8
$(0.01, 0.01),
//Test case 9
$(800.00, 820.40),
//Test case 10
$(3500.00, 3610.42),
//Test case 11
$(300000.00, 309850.00)
);
}
@Before
public void setUp () {
prob1 = new Problem1Class();
}
@Test
@Parameters(method="parametersForProblem1ClassTest")
public void test(double balance1 , double balance2) {
assertEquals(balance2 , prob1.calcBalance(balance1) , 1000);
}
}
| true |
8a822056e85ba7d25d45c8226a5cf612b8b1f41b | Java | jasonkoo/MRTreasury | /src/main/java/com/lenovo/push/data/mr/feedback/dimstat/Driver.java | UTF-8 | 5,373 | 2.125 | 2 | [] | no_license | package com.lenovo.push.data.mr.feedback.dimstat;
import java.util.Date;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
* Join feedback data with device attribute info from MongoDB
* and
* compute daily distributions of each event and failure in dimensions of devicemodel, cityname and peversion
*
* @author gulei2
*
*/
public class Driver extends Configured implements Tool {
private static final String INPUTPATH = "inputPath";
private static final String STAGE1OUTPUTPATH = "stage1OutputPath";
private static final String STAGE2OUTPUTPATH = "stage2OutputPath";
private static final String STAGE3BASEOUTPUTPATH = "stage3BaseOutputPath";
private static final String NUMREDUCERS = "numReducers";
private static final String THEDATE = "thedate";
public int run(String[] args) throws Exception {
Configuration conf = this.getConf();
String inputPath = conf.get(INPUTPATH);
String stage1OutputPath = conf.get(STAGE1OUTPUTPATH);
String stage2OutputPath = conf.get(STAGE2OUTPUTPATH);
String stage3BaseOutputPath = conf.get(STAGE3BASEOUTPUTPATH);
int numReducers = conf.getInt(NUMREDUCERS, 10);
int numReducersStage1 = numReducers;
int numReducersStage2 = numReducers;
int numReducersStage3 = numReducers;
//int numReducersStage2 = (int) 0.2 * numReducers;
//int numReducersStage3 = (int) 0.1 * numReducers;
String thedate = conf.get(THEDATE);
System.out.println("inputPath: " + inputPath);
System.out.println("stage1OutputPath: " + stage1OutputPath);
System.out.println("stage2OutputPath: " + stage2OutputPath);
System.out.println("stage3BaseOutputPath: " + stage3BaseOutputPath);
System.out.println("numReducers: " + numReducers);
System.out.println("thedate: " + thedate);
FileSystem fs = FileSystem.get(conf);
if (fs.exists(new Path(stage1OutputPath))) {
fs.delete(new Path(stage1OutputPath), true);
}
if (fs.exists(new Path(stage2OutputPath))) {
fs.delete(new Path(stage2OutputPath), true);
}
if (fs.exists(new Path(stage3BaseOutputPath))) {
fs.delete(new Path(stage3BaseOutputPath), true);
}
Job job1 = Job.getInstance(conf);
job1.setJobName("Stage1 " + new Date() + ": " + inputPath);
job1.setJarByClass(Driver.class);
FileInputFormat.setInputPaths(job1, new Path(inputPath));
FileOutputFormat.setOutputPath(job1, new Path(stage1OutputPath));
job1.setMapperClass(Stage1Mapper.class);
job1.setReducerClass(Stage1Reducer.class);
job1.setOutputKeyClass(Text.class);
job1.setOutputValueClass(NullWritable.class);
job1.setMapOutputKeyClass(Text.class);
job1.setMapOutputValueClass(IntWritable.class);
job1.setNumReduceTasks(numReducersStage1);
System.out.println(job1.getJobName() + " starting!" );
if (job1.waitForCompletion(true)) {
System.out.println(job1.getJobName() + " done!");
Job job2 = Job.getInstance(conf);
job2.setJobName("Stage2 " + new Date() + ": " + stage1OutputPath);
job2.setJarByClass(Driver.class);
FileInputFormat.setInputPaths(job2, new Path(stage1OutputPath));
FileOutputFormat.setOutputPath(job2, new Path(stage2OutputPath));
job2.setMapperClass(Stage2Mapper.class);
job2.setReducerClass(Stage2Reducer.class);
job2.setOutputKeyClass(Text.class);
job2.setOutputValueClass(IntWritable.class);
job2.setMapOutputKeyClass(Text.class);
job2.setMapOutputValueClass(IntWritable.class);
job2.setNumReduceTasks(numReducersStage2);
System.out.println(job2.getJobName() + " starting!" );
if (job2.waitForCompletion(true)) {
System.out.println(job2.getJobName() + " done!");
Job job3 = Job.getInstance(conf);
job3.setJobName("Stage3 " + new Date() + ": " + stage2OutputPath);
job3.setJarByClass(Driver.class);
FileInputFormat.setInputPaths(job3, new Path(stage2OutputPath));
FileOutputFormat.setOutputPath(job3, new Path(stage3BaseOutputPath));
job3.setMapperClass(Stage3Mapper.class);
job3.setReducerClass(Stage3Reducer.class);
job3.setOutputKeyClass(Text.class);
job3.setOutputValueClass(NullWritable.class);
job3.setMapOutputKeyClass(Text.class);
job3.setMapOutputValueClass(Text.class);
job3.setNumReduceTasks(numReducersStage3);
System.out.println(job3.getJobName() + " starting!" );
if (job3.waitForCompletion(true)) {
System.out.println(job3.getJobName() + " done!");
return 0;
} else {
System.out.println(job3.getJobName() + " fails!");
return 3;
}
} else {
System.out.println(job2.getJobName() + " fails!");
return 2;
}
} else {
System.out.println(job1.getJobName() + " fails!");
return 1;
}
}
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new Driver(), args);
System.exit(res);
}
}
| true |
923abd01e95f7b85f0ccd47f486f290d2949ecb1 | Java | BelleHan/DDIT-HighJava | /CollectionTest/src/kr/or/ddit/basic/VectorTest.java | UHC | 5,671 | 4 | 4 | [] | no_license | package kr.or.ddit.basic;
import java.util.Vector;
public class VectorTest {
public static void main(String[] args) {
// ü
Vector v1 = new Vector<>();
System.out.println("ó ũ: " + v1.size());
// ߰ϱ : add(߰ )
// ȯ : (true), (false)
v1.add("aaaa");
v1.add(new Integer(111));
v1.add(123); // ڽ
v1.add('a');
v1.add(true);
boolean r = v1.add(3.14);
System.out.println(" ũ: " + v1.size());
System.out.println("ȯ: " + r);
System.out.println("v1 => " + v1); //v1.toString toString
// ߰ϱ: addElement(߰ҵ);
// ==> α ֵ ϱ ִ
v1.addElement("CCC");
System.out.println("v1 => " + v1);
// ߰ϱ: add(index, )
// ==> 'index'° '' ִ´.
// ==> 'index' 0 , ȯ .
v1.add(1, "kkk");
System.out.println("v1 => " + v1);
// : set(index, ο );
// ==> 'index'° 'ο ' .
// ==> ȯ:
String temp = (String) v1.set(0, "zzz");
System.out.println("v1 => " + v1);
System.out.println(" : " + temp);
// : remove(index)
// ==> 'index'° Ѵ.
// ==> ȯ:
v1.remove(0);
System.out.println("v1 => " + v1);
temp = (String) v1.remove(0);
System.out.println(" v1 => " + v1);
System.out.println(" : " + temp);
// : remove( )
// ==> ' ' ã Ѵ.
// ==> ' ' ̸ տ ȴ.
// ==> ȯ: (true), (false)
// ==> ' ' ''̰ų 'char' 쿡 ݵ
// ü ȯؼ ؾ Ѵ.
v1.remove("CCC");
System.out.println(" v1 => " + v1);
v1.remove(new Integer(123)); // ׳ 123 (ε ʰ), ڽ ȵǾ ֱ ü ־.
System.out.println(" v1 => " + v1);
//v1.remove('a');
v1.remove(new Character('a'));
System.out.println(" v1 => " + v1);
v1.remove(true);
v1.remove(3.14);
System.out.println(" v1 => " + v1);
// : get(index)
// ==> 'index'° ȯѴ.
int data = (int) v1.get(0);
System.out.println("0° : " + data);
/*
Ÿ(Generic Type) ==> Ŭ ο Ÿ Ŭ ܺο ϴ
==> ü < >ȿ ü Ÿ ִ Ѵ.
==> ̷ ϰ Ǹ Ÿ ̿ ٸ .
==> ִ Ÿ Ŭ̾ Ѵ. (̾ Ѵ.)
, int Integer, boolean Boolean, char Character
ȯؼ ؾ Ѵ.
==> Ÿ ϰ Ǹ ȯ ʿ .
*/
Vector<String> v2 = new Vector<String>(); // String ִ
Vector<Integer> v3 = new Vector<>(); // int ִ (new Vector<> )
v2.add("aaa");
//v2.add(123); //
//String aaa = (String) v2.get(0);
String aaa = v2.get(0); //<String> ȯ <String> ȯ ൵ .
System.out.println("aaa = " + aaa);
Vector<Vector> vv = new Vector<>(); // ȿ Ͱ ̱ 迭 ġ 2 迭
Vector<Vector<Vector>> vvv = new Vector<>(); // 3 迭
// Ÿ ȿ ü ̸ ִ.
// -------------------------------------------
System.out.println("=======================================");
v2.clear(); // ü ϴ
System.out.println("v2 size = " + v2.size());
v2.add("AAAA");
v2.add("BBBB");
v2.add("CCCC");
v2.add("DDDD");
v2.add("EEEE");
Vector<String> v4 = new Vector<>();
v4.add("BBBB");
v4.add("EEEE");
System.out.println("v2 => " + v2);
System.out.println("v4 => " + v4);
// : removeAll(Collectionü)
// ==> 'Collectionü' ִ Ѵ.
// ==> ȯ : (true), (false)
v2.removeAll(v4);
System.out.println("v2 => " + v2);
System.out.println("v4 => " + v4);
System.out.println("--------------------------");
v2.clear();
v2.add("AAAA");
v2.add("BBBB");
v2.add("CCCC");
v2.add("DDDD");
v2.add("EEEE");
// ϰ ݺ Ѵ.
// ַ for
for(int i=0; i<v2.size(); i++) {
System.out.println(i + "° ڷ: " + v2.get(i));
}
System.out.println("-------------------------------");
// for - ڵ ŭ ݺ
for(String s : v2) {
System.out.println(s);
}
}
}
| true |
082382fd00521c1c6ad66d0ef2d652b45cc39d2c | Java | shohan/publisher-basic-spring | /src/main/java/net/inno/service/BookService.java | UTF-8 | 140 | 1.742188 | 2 | [] | no_license | package net.inno.service;
import net.inno.domian.Book;
import java.util.List;
public interface BookService {
List<Book> findAll();
}
| true |
41eb0a50fecbfc40eb89ced783a300652534df56 | Java | xlyinweilong/erp | /src/main/java/com/yin/erp/config/sysconfig/controller/ConfigController.java | UTF-8 | 1,252 | 2.015625 | 2 | [] | no_license | package com.yin.erp.config.sysconfig.controller;
import com.yin.common.controller.BaseJson;
import com.yin.erp.config.sysconfig.dao.ConfigDao;
import com.yin.erp.config.sysconfig.entity.po.ConfigPo;
import com.yin.erp.config.sysconfig.service.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 配置制器
*
* @author yin
*/
@RestController
@RequestMapping(value = "api/info/config")
public class ConfigController {
@Autowired
private ConfigDao configDao;
@Autowired
private ConfigService configService;
/**
* 保存
*
* @param list
* @return
*/
@PostMapping(value = "save", consumes = "application/json")
public BaseJson save(@Validated @RequestBody List<ConfigPo> list) throws Exception {
configService.save(list);
return BaseJson.getSuccess();
}
/**
* 列表
*
* @return
*/
@GetMapping(value = "all")
public BaseJson list(HttpServletRequest request) {
return BaseJson.getSuccess(configDao.findAll());
}
}
| true |
a68f4d58cf4f41f98e25b687b1f10838d58fd9e6 | Java | douglarek/java-climbing | /src/main/java/xin/lingchao/java/leetcode/lcof/_59_2/MaxQueue.java | UTF-8 | 2,007 | 3.796875 | 4 | [
"BSD-3-Clause"
] | permissive | package xin.lingchao.java.leetcode.lcof._59_2;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Queue;
/**
* 请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front
* 的时间复杂度都是O(1)。
* <p>
* 若队列为空,pop_front 和 max_value 需要返回 -1
* <p>
* <b>示例 1:</b>
*
* <pre>
* 输入:
* ["MaxQueue","push_back","push_back","max_value","pop_front","max_value"]
* [[],[1],[2],[],[],[]]
* 输出: [null,null,null,2,1,2]
* </pre>
*
* <p>
*
* See <a href=
* "https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/">https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/</a>
*/
class MaxQueue {
private Queue<Integer> queue; // 正常队列存储
private Deque<Integer> maxQueue; // 单调递减队列, 头部到尾部依次递减
public MaxQueue() {
queue = new ArrayDeque<>();
maxQueue = new ArrayDeque<>();
}
public int max_value() {
if (maxQueue.isEmpty()) {
return -1;
}
return maxQueue.peek();
}
/* 关键 */
public void push_back(int value) {
queue.add(value);
while (!maxQueue.isEmpty() && maxQueue.peekLast() < value) {// 单调递减, 栈明显不合适的, 和尾部比较, 如果大于尾部元素, 则尾部元素出列,
// 一直找尾部元素大于 value 的元素停止
maxQueue.pollLast();
}
maxQueue.add(value);
}
public int pop_front() {
if (queue.isEmpty()) {
return -1;
}
int top = queue.poll();
if (top == maxQueue.peek()) {
maxQueue.poll();
}
return top;
}
}
/**
* Your MaxQueue object will be instantiated and called as such: MaxQueue obj =
* new MaxQueue(); int param_1 = obj.max_value(); obj.push_back(value); int
* param_3 = obj.pop_front();
*/
| true |
eeb592f9546d982f7013ac4fa5473edc6974dc5a | Java | egjar/StartAndShutdown | /app/src/main/java/home/egjar/startandshutdown/Configuration.java | UTF-8 | 5,104 | 2.46875 | 2 | [
"Apache-2.0"
] | permissive | package home.egjar.startandshutdown;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.util.Log;
import android.widget.Toast;
import org.jetbrains.annotations.NotNull;
import static home.egjar.startandshutdown.DBContract.*;
class Configuration {
private int id;
private String ipAddress;
private String macAddress;
private String username;
private String password;
private boolean header_mode = false;
private String domain;
Configuration() {
}
//Getters and setters
String getIp() {
return ipAddress;
}
String getDomain() {
return domain;
}
String getMAC() {
return macAddress;
}
String getUsername() {
return username;
}
String getPassword() {
return password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
boolean ip_header_mode() {
return header_mode;
}
//Functions and methods
void switchHeader_mode() {
header_mode = !header_mode;
}
void saveToDB(Context context) {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ID, id);
contentValues.put(COLUMN_IPADDRESS, ipAddress);
contentValues.put(COLUMN_MACADDRESS, macAddress);
contentValues.put(COLUMN_USERNAME, username);
contentValues.put(COLUMN_PASSWORD, password);
contentValues.put(COLUMN_DOMAIN, domain);
try {
Cursor cursor = loadCursorFromDB(context);
if (cursor.moveToFirst()) {
String selection = COLUMN_ID + " LIKE ?";
String[] selectionArgs = {Integer.toString(id)};
widget.getDB(context).update(SETTINGS_TABLE, contentValues, selection, selectionArgs);
Toast.makeText(context, R.string.settings_updated, Toast.LENGTH_SHORT).show();
} else {
widget.getDB(context).insertOrThrow(SETTINGS_TABLE, null, contentValues);
Toast.makeText(context, R.string.settings_saved, Toast.LENGTH_SHORT).show();
}
cursor.close();
} catch (SQLException e) {
Toast.makeText(context, "Error" + e.getCause() + " " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void readFromCursor(@NotNull Cursor cursor) {
this.id = cursor.getInt(cursor.getColumnIndex(COLUMN_ID));
this.ipAddress = cursor.getString(cursor.getColumnIndex(COLUMN_IPADDRESS));
this.macAddress = cursor.getString(cursor.getColumnIndex(COLUMN_MACADDRESS));
this.username = cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME));
this.password = cursor.getString(cursor.getColumnIndex(COLUMN_PASSWORD));
this.domain = cursor.getString(cursor.getColumnIndex(COLUMN_DOMAIN));
}
boolean isEntryExist(Context context, int id){
boolean result=false;
this.id = id;
Cursor cursor = loadCursorFromDB(context);
result = cursor.moveToFirst();
cursor.close();
return result;
}
private Cursor loadCursorFromDB(Context context) {
String selection = COLUMN_ID + " = ?";
String[] selectionArgs = {Integer.toString(id)};
String sortOrder = COLUMN_ID + " DESC";
return widget.getDB(context).query(SETTINGS_TABLE,
null,
selection,
selectionArgs,
null,
null,
sortOrder);
}
void loadFromDB(Context context, int id) {
// Cursor cursor = db.rawQuery("SELECT * FROM " + SETTINGS_TABLE + " WHERE " +
// COLUMN_ID + " = '" + id + "'", null);
this.id = id;
Cursor cursor = loadCursorFromDB(context);
readFromCursor(cursor);
cursor.close();
}
PSRemoting initPSRemoting() {
return new PSRemoting(ipAddress, domain, username, password);
}
static class Builder {
private Configuration newConfiguration;
Builder() {
newConfiguration = new Configuration();
}
Builder withID(int id) {
newConfiguration.id = id;
return this;
}
Builder withIP(String ipAddress) {
newConfiguration.ipAddress = ipAddress;
return this;
}
Builder withMAC(String macAddress) {
newConfiguration.macAddress = macAddress;
return this;
}
Builder withUsername(String username) {
newConfiguration.username = username;
return this;
}
Builder withPassword(String password) {
newConfiguration.password = password;
return this;
}
Builder withDomain(String domain) {
newConfiguration.domain = domain;
return this;
}
Configuration build() {
return newConfiguration;
}
}
}
| true |
26bad744bff1d434995f829595740ed414ad5301 | Java | kevery/Algorithm | /src/com/kevery/algorithm/page74/StringOfStack.java | UTF-8 | 1,914 | 3.453125 | 3 | [] | no_license | package com.kevery.algorithm.page74;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;
/**
* 栈数组实现
* Created by kever
* 2016/10/1.
*/
public class StringOfStack<Item> implements Iterable<Item>{
private Item[] sts;
private int count;
public StringOfStack(int cap) {
sts = (Item[]) new Object[cap];
}
public void push(Item s) {
if (sts.length == count) {
reSize(2 * sts.length);
}
sts[count++] = s;
}
public Item pop() {
Item item = sts[--count];
sts[count] = null;
if (count > 0 && count == sts.length / 4) {
reSize(sts.length / 2);
}
return item;
}
public int size() {
return count;
}
public boolean isEmpty() {
return count == 0;
}
/**
* 数组扩容
*
* @param max
*/
public void reSize(int max) {
Item[] items = (Item[]) new Object[max];
for (int i = 0; i < count; i++) {
items[i] = sts[i];
}
sts = items;
}
public Item[] getSts() {
return sts;
}
public void setSts(Item[] sts) {
this.sts = sts;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public Iterator<Item> iterator() {
return new ReverserArrayIterator();
}
private class ReverserArrayIterator implements Iterator<Item> {
int i = -1;
@Override
public boolean hasNext() {
return ++i < count;
}
@Override
public Item next() {
return sts[i];
}
}
@Override
public void forEach(Consumer<? super Item> action) {
}
@Override
public Spliterator<Item> spliterator() {
return null;
}
}
| true |
e9f1c100f7bd2081d64d4a0a7356e762769091bb | Java | creative-active-technology/inkubator-hrm | /inkubator-hrm/src/main/java/com/inkubator/hrm/web/search/VacancyAdvertisementSearchParameter.java | UTF-8 | 1,697 | 2.03125 | 2 | [] | no_license | package com.inkubator.hrm.web.search;
import org.apache.commons.lang3.StringUtils;
import com.inkubator.webcore.util.SearchParameter;
/**
*
* @author rizkykojek
*/
public class VacancyAdvertisementSearchParameter extends SearchParameter {
private String vacancyAdvertisementCode;
private String advertisementMediaName;
private String advertisementCategoryName;
public String getVacancyAdvertisementCode() {
if (StringUtils.equalsIgnoreCase(getKeyParam(), "vacancyAdvertisementCode")) {
vacancyAdvertisementCode = getParameter();
} else {
vacancyAdvertisementCode = null;
}
return vacancyAdvertisementCode;
}
public void setVacancyAdvertisementCode(String vacancyAdvertisementCode) {
this.vacancyAdvertisementCode = vacancyAdvertisementCode;
}
public String getAdvertisementMediaName() {
if (StringUtils.equalsIgnoreCase(getKeyParam(), "advertisementMediaName")) {
advertisementMediaName = getParameter();
} else {
advertisementMediaName = null;
}
return advertisementMediaName;
}
public void setAdvertisementMediaName(String advertisementMediaName) {
this.advertisementMediaName = advertisementMediaName;
}
public String getAdvertisementCategoryName() {
if (StringUtils.equalsIgnoreCase(getKeyParam(), "advertisementCategoryName")) {
advertisementCategoryName = getParameter();
} else {
advertisementCategoryName = null;
}
return advertisementCategoryName;
}
public void setAdvertisementCategoryName(String advertisementCategoryName) {
this.advertisementCategoryName = advertisementCategoryName;
}
}
| true |
b98433a15b89591a83b059a8f45ae5c9ec791a98 | Java | nextyu/book-source | /Java7-Concurrency-Cookbook/src/main/java/com/nextyu/book/study/source/chapter6_concurrent_collections/_9_using_atomic_arrays/Incrementer.java | UTF-8 | 613 | 3.46875 | 3 | [] | no_license | package com.nextyu.book.study.source.chapter6_concurrent_collections._9_using_atomic_arrays;
import java.util.concurrent.atomic.AtomicIntegerArray;
/**
* @author zhouyu
*/
public class Incrementer implements Runnable {
/**
* store an array of integer numbers
*/
private AtomicIntegerArray vector;
public Incrementer(AtomicIntegerArray vector) {
this.vector = vector;
}
@Override
public void run() {
for (int i = 0; i < vector.length(); i++) {
// increments all the elements of the array
vector.getAndIncrement(i);
}
}
}
| true |
87c013ba30978a9126c9c85521835bbaac7523ed | Java | romanoConto/grafo-leilao-entregas | /src/main/java/com/grafo/leiaoEntregas/gerenciador/Gerenciador.java | UTF-8 | 6,102 | 2.953125 | 3 | [] | no_license | package com.grafo.leiaoEntregas.gerenciador;
import com.grafo.leiaoEntregas.Entradas;
import com.grafo.leiaoEntregas.entradas.LerEntradas;
import com.grafo.leiaoEntregas.entregas.Entregas;
import com.grafo.leiaoEntregas.entregas.Rota;
import com.grafo.leiaoEntregas.entregas.RotasEntrega;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Gerenciador {
private static Entradas entradas = new Entradas();
private static List<RotasEntrega> rotas = new ArrayList<>();
private static String path = null;
/**
* Construtor da classe que executa o menu
*/
public Gerenciador() throws Exception {
Scanner ler = new Scanner(System.in);
int iniciar;
while (true) {
System.out.println("\n=================== =================== LEILÃO DE ENTREGAS =================== ===================");
System.out.println("1 - Carregar Entradas ");
System.out.println("2 - Calcular Entregas ");
System.out.println("3 - Mostrar Rotas ");
System.out.println("4 - Limpar tela ");
System.out.println("0 - Sair ");
iniciar = ler.nextInt();
switch (iniciar) {
case 1:
System.out.println("\n=================== =================== ESCOLHA UMA OPÇÃO =================== ===================");
System.out.println("1 - Carregar Entradas Enunciado ");
System.out.println("2 - Carregar Bug Parametro ");
System.out.println("3 - Carregar Bug Aleatorio ");
System.out.println("4 - Carregar Bug Complexa ");
System.out.println("5 - Carregar Entradas 2");
System.out.println("0 - Voltar ");
iniciar = ler.nextInt();
switch (iniciar) {
case 1:
path = "src\\files\\entradas.txt";
ReadFile();
break;
case 2:
path = "src\\files\\bug_parametro.txt";
ReadFile();
break;
case 3:
path = "src\\files\\bug_aleatorio.txt";
ReadFile();
break;
case 4:
path = "src\\files\\bug_complexa.txt";
ReadFile();
break;
case 5:
path = "src\\files\\entradas2.txt";
ReadFile();
break;
case 0:
return;
}
break;
case 2:
calcRoute();
break;
case 3:
showRoute();
break;
case 4:
limpaTela();
break;
case 0:
System.out.println("Saindo ...");
System.exit(0);
break;
}
}
}
/**
* Mostra as rotas alternativas e a rota principal
*/
private void showRoute() {
int cont = 1;
int recompensa = 0;
System.out.println("\n=================== =================== #Entregas do dia# =================== ===================");
for (RotasEntrega re : rotas) {
Rota r = re.getRotaMenor();
System.out
.print("\n\n=================== =================== A " + cont + "º rota a ser realizada é de 'A' até '" + r.getDestino() + "' =================== ===================");
boolean isTrue = false;
if (r.getRecompensa() == 1) {
isTrue = true;
}
System.out.println("\n\nA rota Principal é: " + printRoute(r));
System.out.println(
"Com a chegada estimada de " + r.getDistancia() + " unidades de tempo no destino " + "'"
+ r.getDestino() + "'" + " e o valor para esta entrega será de " + (isTrue ?
r.getRecompensa() + " real" : r.getRecompensa() + " reais") + ".");
System.out.print("\nAs rotas alternativas são:" + getAlternativeRoutes(re.getRotas()));
recompensa += r.getRecompensa();
cont++;
}
System.out.println("\n\nO lucro total do dia: " + recompensa + ".");
}
/**
* Monta a tela de rotas alternativas
*/
private String getAlternativeRoutes(List<Rota> rotas) {
StringBuilder sb = new StringBuilder();
for (Rota r : rotas) {
sb.append("\nCusto = " + r.getDistancia() + ". Rota: " + printRoute(r));
}
return sb.toString();
}
/**
* Monta a tela da principal rota
*/
private String printRoute(Rota r) {
StringBuilder s = new StringBuilder();
for (String d : r.getPontos()) {
s.append(d + "->");
}
s = s.replace(s.length() - 2, s.length(), ".");
return s.toString();
}
/**
* Faz a leitura do arquivo, caso não seja possivel ler lança exception ao user
*/
private static void ReadFile() {
try {
LerEntradas read = new LerEntradas();
entradas = read.readFile(path);
} catch (Exception e) {
System.out.println("Formato de arquivo inválido!");
}
}
/**
* Faz o calculo das entregas retornando as rotas
*/
private static void calcRoute() throws CloneNotSupportedException {
Entregas matriz = new Entregas(entradas);
rotas = matriz.processarEntregas();
}
private static void limpaTela() throws IOException {
for (int i = 0; i < 100; ++i)
System.out.println();
}
}
| true |
f5955593234dfe5bb1515221e1626d915ca7de87 | Java | richibrancato/Proyecto-Java-Alquileres | /src/uy/proyectofinal/presentacion/VentanaLogin.java | UTF-8 | 8,741 | 2.328125 | 2 | [] | no_license | /*
* 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 uy.proyectofinal.presentacion;
import java.awt.Container;
import javax.swing.JOptionPane;
import uy.proyectofinal.excepciones.UsuarioException;
import uy.proyectofinal.logica.FachadaLogica;
import uy.proyectofinal.logica.Usuario;
import uy.proyectofinal.presentacion.Registro;
/**
*
* @author pc
*/
public class VentanaLogin extends javax.swing.JFrame {
Container contentpane;
/**
* Creates new form principal
*/
public VentanaLogin() {
initComponents();
setTitle("HomePage");
//setSize(1020,574);
setLocationRelativeTo(null);
setResizable(false);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jIngresar = new javax.swing.JButton();
jRegistrarse = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
txtUsuario = new javax.swing.JTextField();
txtClave = new javax.swing.JPasswordField();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jIngresar.setBackground(new java.awt.Color(204, 255, 204));
jIngresar.setFont(new java.awt.Font("SansSerif", 1, 18)); // NOI18N
jIngresar.setText("Ingresar");
jIngresar.setBorder(null);
jIngresar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jIngresarActionPerformed(evt);
}
});
getContentPane().add(jIngresar, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 450, 110, 40));
jRegistrarse.setFont(new java.awt.Font("SansSerif", 1, 11)); // NOI18N
jRegistrarse.setText("¡Registrate ahora!");
jRegistrarse.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jRegistrarseMouseClicked(evt);
}
});
jRegistrarse.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRegistrarseActionPerformed(evt);
}
});
getContentPane().add(jRegistrarse, new org.netbeans.lib.awtextra.AbsoluteConstraints(710, 540, 150, -1));
jLabel3.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Si aun no estas registrado...");
getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(690, 520, 200, 20));
txtUsuario.setFont(new java.awt.Font("SansSerif", 0, 18)); // NOI18N
getContentPane().add(txtUsuario, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 300, 320, -1));
getContentPane().add(txtClave, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 400, 320, 40));
jLabel2.setForeground(new java.awt.Color(153, 255, 153));
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/uy/proyectofinal/imagenesDeInterface/TODO ALQUILERES2.png"))); // NOI18N
jLabel2.setText("INGRESAR");
jLabel2.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel2.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1020, -1));
pack();
}// </editor-fold>//GEN-END:initComponents
private void jIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jIngresarActionPerformed
try{
Usuario usuario = new Usuario();
usuario.setNomUsuario(txtUsuario.getText());
usuario.setClave(txtClave.getText());
FachadaLogica fachada = new FachadaLogica();
//LE PIDO A LA FACHADA LA OPERACION QUE RESUELVE I FUNCIONALIDAD, LE PASO LOS DATOS AL OBJETO DE LA LOGICA
Boolean usuarioValido = fachada.validarIngreso(usuario);
if("admin".equals(usuario.getNomUsuario()) && usuarioValido ){ //CONSULTAR POR VALIDACIONES ADMIN
JOptionPane.showMessageDialog(this, "Bienvenido "+usuario.getNomUsuario() + " "+JOptionPane.INFORMATION_MESSAGE);
VentanaAdminUsuario vA = new VentanaAdminUsuario();
vA.setVisible(true);
dispose();
}else if(usuarioValido){
System.out.println("EL USUARIO ES VALIDO");
JOptionPane.showMessageDialog(this, "Bienvenido.", "TODO OK AMIGOS " ,JOptionPane.INFORMATION_MESSAGE);
VentanaHomePage hp = new VentanaHomePage();
hp.setVisible(true);
dispose();
}else{
System.out.println("EL USUARIO NO ES VALIDO");
JOptionPane.showMessageDialog(this, "El usuario que has introducido no coincide con ninguna cuenta", "MENSAJE DE ERROR " ,JOptionPane.INFORMATION_MESSAGE);
}
//CUANDO DEVULEVE TRUE REDIRIGO HACIA OTRA VENTANA
//CUANDO DEVUELVE FALSE REDIRIGO A UN MENSAJE DICIENDO QUE EL USUARIO NO ES VALIDO
}catch (UsuarioException ex){
JOptionPane.showMessageDialog(null, "No se puede validar el usuario","Confirmacion" , JOptionPane.INFORMATION_MESSAGE);
}
}//GEN-LAST:event_jIngresarActionPerformed
private void jRegistrarseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRegistrarseActionPerformed
}//GEN-LAST:event_jRegistrarseActionPerformed
private void jRegistrarseMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jRegistrarseMouseClicked
VentanaUsuario vu = new VentanaUsuario();
super.dispose();
vu.setVisible(true);
vu.setFocusable(true);
}//GEN-LAST:event_jRegistrarseMouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(VentanaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VentanaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VentanaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VentanaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new VentanaLogin().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jIngresar;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JButton jRegistrarse;
private javax.swing.JPasswordField txtClave;
private javax.swing.JTextField txtUsuario;
// End of variables declaration//GEN-END:variables
}
| true |
380a9b0dbca90c4de493265cbac4a04ea1698400 | Java | wintruelife/lovestaff | /app/src/main/java/love/wintrue/com/lovestaff/ui/activity/RegisterAndLoginActivity.java | UTF-8 | 6,961 | 1.859375 | 2 | [] | no_license | package love.wintrue.com.lovestaff.ui.activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.OnClick;
import love.wintrue.com.lovestaff.R;
import love.wintrue.com.lovestaff.base.BaseActivity;
import love.wintrue.com.lovestaff.ui.mine.MineActivity;
import love.wintrue.com.lovestaff.utils.ActivityUtil;
import love.wintrue.com.lovestaff.utils.AnimationUtils;
import love.wintrue.com.lovestaff.utils.Util;
import love.wintrue.com.lovestaff.widget.ClearEditText;
import love.wintrue.com.lovestaff.widget.StateButton;
import love.wintrue.com.lovestaff.widget.actionbar.CommonActionBar;
/**
* Created by XDHG on 2018/5/22.
*/
public class RegisterAndLoginActivity extends BaseActivity {
@Bind(R.id.title_actionbar_login)
CommonActionBar cab;
@Bind(R.id.btn_login)
StateButton btnLogin;
@Bind(R.id.btn_register_next)
StateButton btnRegisterNext;
@Bind(R.id.btn_register_next2)
StateButton btnRegisterNext2;
@Bind(R.id.tv_register)
TextView tvRegister;
@Bind(R.id.tv_login)
TextView tvLogin;
@Bind(R.id.ll_login_view)
LinearLayout llLoginView;
@Bind(R.id.ll_register_view)
LinearLayout llRegisterView;
@Bind(R.id.ll_register_view2)
LinearLayout llRegisterView2;
@Bind(R.id.iv_triangle)
ImageView ivTriangle;
@Bind(R.id.tv_count_down)
TextView tvCountDown;
@Bind(R.id.et_account_register)
ClearEditText etAccountRegister;
@Bind(R.id.tv_forget_pwd)
TextView tvForgetPwd;
private int[] start_location;
private int[] end_location;
private boolean registerHasNext;
private Handler timerHandler;
private int time = 60;
Thread timeThread;
MyTimerTask timerTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public int getLayoutId() {
return R.layout.activity_register_and_login;
}
@Override
public void initView() {
ActivityUtil.next(RegisterAndLoginActivity.this, MineActivity.class);
timerTask = new MyTimerTask();
timerHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int tempTime = msg.what;
if (time <= 0) {
tvCountDown.setEnabled(true);
tvCountDown.setTextColor(ContextCompat.getColor(THIS, R.color.color_31b3ef));
tvCountDown.setText("重新发送短信");
time = 60;
} else {
tvCountDown.setText(tempTime + "秒后重新发送短信");
}
}
};
cab.setActionBarTitle("爱员工");
cab.setLeftImgBtn(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
btnLogin.setNormalBackgroundColor(colors);
btnRegisterNext.setNormalBackgroundColor(colors);
btnRegisterNext2.setNormalBackgroundColor(colors);
}
@OnClick({R.id.btn_login, R.id.tv_login, R.id.tv_register, R.id.btn_register_next, R.id.btn_register_next2, R.id.tv_count_down, R.id.tv_forget_pwd})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.btn_login:
ActivityUtil.next(THIS, AddressBookActivity.class);
break;
case R.id.tv_login:
llLoginView.setVisibility(View.VISIBLE);
llRegisterView.setVisibility(View.GONE);
llRegisterView2.setVisibility(View.GONE);
startAnim("moveLeft");
break;
case R.id.tv_register:
llLoginView.setVisibility(View.GONE);
if (!registerHasNext) {
llRegisterView2.setVisibility(View.GONE);
llRegisterView.setVisibility(View.VISIBLE);
} else {
llRegisterView2.setVisibility(View.VISIBLE);
llRegisterView.setVisibility(View.GONE);
}
startAnim("moveRight");
break;
case R.id.btn_register_next:
if (!Util.isValidMobileNumber(etAccountRegister.getText().toString())) {
showToastMsg("请输入正确的手机号码");
return;
}
registerHasNext = true;
llLoginView.setVisibility(View.GONE);
llRegisterView.setVisibility(View.GONE);
llRegisterView2.setVisibility(View.VISIBLE);
startCountDown();
break;
case R.id.btn_register_next2:
ActivityUtil.next(THIS, ImproveInformationActivity.class);
break;
case R.id.tv_count_down:
startCountDown();
break;
case R.id.tv_forget_pwd:
ActivityUtil.next(THIS, ForgetPasswordActivity.class);
break;
}
}
/**
* 开始动画
*/
private void startAnim(String direction) {
start_location = new int[2];
tvLogin.getLocationInWindow(start_location);
end_location = new int[2];
tvRegister.getLocationInWindow(end_location);
AnimationUtils.translation(ivTriangle, start_location[0], end_location[0], null, 300, "translationX", direction);
if (TextUtils.equals("moveLeft", direction)) {
AnimationUtils.alphaAnimator(tvRegister, 1f, 0.6f);
AnimationUtils.alphaAnimator(tvLogin, 0.6f, 1f);
} else {
AnimationUtils.alphaAnimator(tvLogin, 1f, 0.6f);
AnimationUtils.alphaAnimator(tvRegister, 0.6f, 1f);
}
}
/**
* 开始倒计时
*/
private void startCountDown() {
tvCountDown.setEnabled(false);
tvCountDown.setTextColor(ContextCompat.getColor(THIS, R.color.color_969696));
timeThread = new Thread(timerTask);
timeThread.start();
}
/**
* 计时线程
*/
class MyTimerTask implements Runnable {
@Override
public void run() {
while (true) {
time--;
Message msg = new Message();
msg.what = time;
timerHandler.sendMessage(msg);
if (time <= 0)
break;
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
| true |
522ab732b7cb32bbf860b750d83010bac609746b | Java | youngmonkeys/ezyfox-server | /ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioDataHandler.java | UTF-8 | 341 | 1.789063 | 2 | [
"Apache-2.0"
] | permissive | package com.tvd12.ezyfoxserver.nio.handler;
import com.tvd12.ezyfox.constant.EzyConstant;
import com.tvd12.ezyfoxserver.socket.EzySocketDataHandler;
public interface EzyNioDataHandler extends EzySocketDataHandler {
void channelInactive(EzyConstant disconnectReason);
void exceptionCaught(Throwable throwable) throws Exception;
}
| true |
75d4e423750d4751170de9f7375eed869c3ae37c | Java | dmfrey/dataflow | /connection-handler/src/main/java/com/vmware/dmfrey/dataflow/tcpclient/TcpClient.java | UTF-8 | 3,303 | 1.945313 | 2 | [] | no_license | package com.vmware.dmfrey.dataflow.tcpclient;
import com.vmware.dmfrey.dataflow.config.TcpServerConfigurationProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.integration.ip.tcp.TcpReceivingChannelAdapter;
import org.springframework.integration.ip.tcp.TcpSendingMessageHandler;
import org.springframework.integration.ip.tcp.connection.TcpConnectionOpenEvent;
import org.springframework.integration.ip.tcp.connection.TcpNetClientConnectionFactory;
import org.springframework.integration.ip.tcp.serializer.ByteArrayLfSerializer;
import org.springframework.integration.leader.event.OnGrantedEvent;
import org.springframework.integration.leader.event.OnRevokedEvent;
@Configuration
public class TcpClient {
private static final Logger log = LoggerFactory.getLogger( TcpClient.class );
@Autowired
private ClientManager clientManager;
@Bean
TcpNetClientConnectionFactory connectionFactory( final TcpServerConfigurationProperties properties ) {
TcpNetClientConnectionFactory connectionFactory = new TcpNetClientConnectionFactory( properties.getUrl(), properties.getPort() );
connectionFactory.setSerializer( new ByteArrayLfSerializer() );
connectionFactory.setDeserializer( new ByteArrayLfSerializer() );
return connectionFactory;
}
@Bean
TcpSendingMessageHandler sendingMessageHandler( final TcpNetClientConnectionFactory connectionFactory ) {
TcpSendingMessageHandler sendingMessageHandler = new TcpSendingMessageHandler();
sendingMessageHandler.setConnectionFactory( connectionFactory );
return sendingMessageHandler;
}
@Bean
TcpReceivingChannelAdapter receivingChannelAdapter( final TcpNetClientConnectionFactory connectionFactory ) {
TcpReceivingChannelAdapter receivingChannelAdapter = new TcpReceivingChannelAdapter();
receivingChannelAdapter.setConnectionFactory( connectionFactory );
receivingChannelAdapter.setOutputChannelName( "payloadFlow.input" );
receivingChannelAdapter.setAutoStartup( false );
receivingChannelAdapter.setRole( "leader" );
return receivingChannelAdapter;
}
@Autowired
TcpSendingMessageHandler sendingMessageHandler;
@Autowired
TcpReceivingChannelAdapter receivingChannelAdapter;
@Autowired
RegisterClient registerClient;
@EventListener
void handleTcpConnectionOpenEvent( final TcpConnectionOpenEvent event ) {
log.info( "Opening TCP Connection {}", event );
String instanceId = event.getConnectionId().substring( event.getConnectionId().lastIndexOf( ":" ) );
clientManager.setInstanceId( instanceId );
sendingMessageHandler.handleMessage( registerClient.sendRegister() );
}
@EventListener
void handleOnGrantedEvent( final OnGrantedEvent event ) {
log.info( "Leadership Granted {}", event );
}
@EventListener
void handleOnRevokedEvent( final OnRevokedEvent event ) {
log.info( "Leadership Revoked {}", event );
}
}
| true |
ac2fb538d5498cdaac94d7e6a14b71c79c055404 | Java | ashlin-k/Personal-projects | /TennisBooker/Code/TennisBooker/src/booker/TennisThread.java | UTF-8 | 964 | 3.21875 | 3 | [] | no_license | package booker;
import booker.Tennis;
public class TennisThread extends Thread {
private Thread t;
private String threadName, secondPlayer;
private int time, court, hour, minute, second, millisec;
TennisThread(String name, int time, int court, String secondPlayer, int hour, int minute, int second, int millisec) {
threadName = name;
System.out.println("Creating " + threadName);
this.time = time;
this.court = court;
this.secondPlayer = secondPlayer;
this.hour = hour;
this.minute = minute;
this.second = second;
this.millisec = millisec;
}
public void run() {
System.out.println("Running " + threadName);
Tennis tennis = new Tennis();
tennis.bookCourt(time, court, secondPlayer, hour, minute, second, millisec);
System.out.println("Thread " + threadName + " exiting.");
}
public void start() {
System.out.println("Starting " + threadName);
if (t == null) {
t = new Thread(this, threadName);
t.start();
}
}
}
| true |
8a3711032277fdf5da4875353cf7b7dca4d843ef | Java | 2YSP/my-springboot | /src/main/java/cn/sp/dao/PersonDao.java | UTF-8 | 197 | 1.9375 | 2 | [] | no_license | package cn.sp.dao;
import cn.sp.entity.Person;
import java.util.List;
public interface PersonDao {
void save(Person person);
Person queryById(Integer id);
List<Person> queryPage();
}
| true |
e079392f4f5f80bdd133a963e7996abb8dc7f0d7 | Java | hitesh7878/endtoendFramework | /twg.nlapp.webservicesautomation2/src/test/java/Archieve/TC_01_VerifyCategory.java | UTF-8 | 1,963 | 2.0625 | 2 | [] | no_license | package Archieve;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.get;
import static io.restassured.RestAssured.given;
import static io.restassured.path.json.JsonPath.from;
import static org.hamcrest.Matchers.containsString;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;
import org.hamcrest.CoreMatchers.*;
import static org.hamcrest.Matchers.equalTo;
public class TC_01_VerifyCategory {
String response;
@Test
public void getCategory_API()
{
response=given().header("Ocp-Apim-Subscription-Key","c68fa40a7cb443ecbba9866f63e9edf2").when()
.get("https://twg.azure-api.net/twlYourWarehouseTest/Category.json?CategoryId=12704-mobilephones-smartphone")
.asString();
int statusCode=given().header("Ocp-Apim-Subscription-Key","c68fa40a7cb443ecbba9866f63e9edf2").when()
.get("https://twg.azure-api.net/twlYourWarehouseTest/Category.json?CategoryId=12704-mobilephones-smartphone")
.statusCode();
System.out.println("Status code is" + statusCode);
System.out.println("Response is ---->"+response);
if (statusCode == 200) {
JsonPath jp = new JsonPath(response);
//String attrTxt = jp.getString("attributionText");
//System.out.println("Attribution texyt is" + attrTxt);
List<String> names = from(response).getList("categoryTree.name");
//List<String> titles = from(response).getList("data.results.title");
for (String name : names) {
System.out.println("Title is" + name);
}
}
}
@Test
public void verifyCategory_Device()
{
}
}
| true |
cfc7e7d86948d8d75fd9bbb0dfcca5bdaf74787c | Java | donglonglong/schoolShop | /src/main/java/com/imooc/o2o/entity/WechatAuth.java | UTF-8 | 1,280 | 2.265625 | 2 | [] | no_license | package com.imooc.o2o.entity;
import java.util.Date;
/**
* 微信账号
*/
public class WechatAuth {
//微信ID
private Long wechatAuthId;
//微信openID
private String openId;
//创建时间
private Date createTime;
//跟用户表关联,创建用户类
private PersonInfo persionInfo;
public Long getWechatAuthId() {
return wechatAuthId;
}
public void setWechatAuthId(Long wechatAuthId) {
this.wechatAuthId = wechatAuthId;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public PersonInfo getPersionInfo() {
return persionInfo;
}
public void setPersionInfo(PersonInfo persionInfo) {
this.persionInfo = persionInfo;
}
@Override
public String toString() {
return "WechatAuth{" +
"wechatAuthId=" + wechatAuthId +
", openId='" + openId + '\'' +
", createTime=" + createTime +
", persionInfo=" + persionInfo +
'}';
}
}
| true |
edf6c4c0fa313b8f8e2a260378bdadd9b4e2aac5 | Java | lovehoroscoper/cadmium | /black-box-tests/src/main/java/com/meltmedia/cadmium/blackbox/test/GitBareRepoInitializer.java | UTF-8 | 2,924 | 2.0625 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright 2012 meltmedia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.meltmedia.cadmium.blackbox.test;
import com.meltmedia.cadmium.core.git.GitService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.InitCommand;
import java.io.File;
/**
* Manages a git repository for testing.
*/
public class GitBareRepoInitializer {
private String repoPath;
private String checkoutPath;
private Git bareRepo;
private GitService clonedGit;
public GitBareRepoInitializer() {}
public void init(String repoPath, String sourceDir, String sourceConfigDir) throws Exception {
File repoDir = new File(repoPath);
if(repoDir.exists()) {
FileUtils.forceDelete(repoDir);
}
File checkoutDir = new File(repoDir.getAbsoluteFile().getParent(), repoDir.getName()+".checkout");
if(checkoutDir.exists()) {
FileUtils.forceDelete(checkoutDir);
}
checkoutPath = checkoutDir.getAbsolutePath();
InitCommand init = Git.init();
init.setBare(true);
init.setDirectory(repoDir);
bareRepo = init.call();
clonedGit = GitService.cloneRepo(repoPath, checkoutPath);
clonedGit.checkinNewContent(sourceConfigDir, "Initial commit");
clonedGit.push(false);
clonedGit.newEmtpyRemoteBranch("cd-master");
clonedGit.switchBranch("cd-master");
clonedGit.checkinNewContent(sourceDir, "Initial commit");
clonedGit.push(false);
clonedGit.newEmtpyRemoteBranch("cfg-master");
clonedGit.switchBranch("cfg-master");
clonedGit.checkinNewContent(sourceConfigDir, "Initial commit");
clonedGit.push(false);
}
public String setupContentUpdate(String updateDir) throws Exception {
clonedGit.switchBranch("cd-master");
clonedGit.checkinNewContent(updateDir, "updated content");
clonedGit.push(false);
return clonedGit.getCurrentRevision();
}
public String setupConfigUpdate(String updateDir) throws Exception {
clonedGit.switchBranch("cfg-master");
clonedGit.checkinNewContent(updateDir, "updated config");
clonedGit.push(false);
return clonedGit.getCurrentRevision();
}
public void close() throws Exception {
IOUtils.closeQuietly(clonedGit);
bareRepo.getRepository().close();
}
public String getRepo() {
return clonedGit.getRemoteRepository();
}
}
| true |
bbe12d170480bd59473c27dbc6d2e80064b3f9bb | Java | gustavoballeste/safe-garage | /customer-service/src/main/java/br/com/safegarage/customer_service/service/CustomerService.java | UTF-8 | 2,203 | 2.5625 | 3 | [] | no_license | package br.com.safegarage.customer_service.service;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import br.com.safegarage.customer_service.entity.CustomerEntity;
import br.com.safegarage.customer_service.domain.model.Customer;
import br.com.safegarage.customer_service.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CustomerService {
@Autowired
private CustomerRepository customerRepository;
public Customer save(final Customer customer) {
final CustomerEntity savedCustomer = customerRepository.save(customer.toCustomerEntity());
return Customer.customerEntityToCustomer(savedCustomer);
}
public Optional<Customer> getById(final Long id) {
return customerRepository.findById(id)
.map(Customer::customerEntityToCustomer);
}
public List<Customer> getAll() {
return customerRepository.findAll()
.stream()
.map(Customer::customerEntityToCustomer)
.collect(Collectors.toList());
}
public void delete(final Long id) {
customerRepository.deleteById(id);
}
public Optional<Customer> update (final Customer customerRequest){
final Optional<Customer> optionalCustomer = getById(customerRequest.getId());
if (optionalCustomer.isPresent()) {
final Customer customer = optionalCustomer.get();
customer.setBornDate(customerRequest.getBornDate());
customer.setName(customerRequest.getName());
customer.setStreet(customerRequest.getStreet());
customer.setCity(customerRequest.getCity());
customer.setState(customerRequest.getState());
customer.setNumber(customerRequest.getNumber());
customer.setZipCode(customerRequest.getZipCode());
final CustomerEntity savedCustomer = customerRepository.save(customer.toCustomerEntity());
return Optional.of(Customer.customerEntityToCustomer(savedCustomer));
} else {
return Optional.empty();
}
}
}
| true |
51676ee11ba4f153e99c753a18045601786e22f8 | Java | SahakStepanyan/Some-random-code | /day5/task11.java | UTF-8 | 775 | 3.46875 | 3 | [] | no_license | package day5;
import java.util.Scanner;
public class task11 {
public static void main(String[] args) {
Scanner in1 = new Scanner(System.in);
System.out.print("Enter your number");
int op = in1.nextInt();
int oo = in1.nextInt();
Scanner in2 = new Scanner(System.in);
System.out.print("Enter the expression");
String ii = in2.next();
switch (ii){
case "+":
System.out.println(op + oo);
break;
case "-":
System.out.println(op - oo);
break;
case "*":
System.out.println(op * oo);
break;
case "/":
System.out.println(op / oo);
}
}
}
| true |
6cc07388d471cd6c2ed0c7289fafdecf0634c6c1 | Java | JustMeem/GraphicLab | /src/com/company/Polygon.java | UTF-8 | 1,212 | 3.5 | 4 | [] | no_license | package com.company;
import java.awt.*;
public class Polygon extends Figure {
private int[] x, y;
private double angle = 0;
public Polygon(int[] x, int[] y, int boundX, int boundY) {
this.x = x;
this.y = y;
this.boundX = boundX;
this.boundY = boundY;
}
@Override
public void rotate(double a) {
angle += a;
}
@Override
public void draw(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
int midX = 0, midY = 0, div = x.length;
for (int i = 0; i < div; i++) {
midX += x[i] / div;
midY += y[i] / div;
}
g2.rotate(angle, midX, midY);
g2.fillPolygon(x, y, div);
g2.rotate(-angle, midX, midY);
}
@Override
public void move() {
int midX = 0, midY = 0, div = x.length;
for (int i = 0; i < div; i++) {
midX += x[i] / div;
midY += y[i] / div;
}
if (midX > boundX || midX / 2 < 0) {
dx = -dx;
}
if (midY > boundY || midY / 2 < 0) {
dy = -dy;
}
for (int i = 0; i < div; i++) {
x[i] += dx;
y[i] += dy;
}
}
}
| true |
2ab83649abfb17ca6ffa03c33114042286b31c7c | Java | Nunchakus888/Monitor-Apis | /src/main/java/com/sumscope/cdh/web/interceptor/SecurityInterceptor.java | UTF-8 | 1,446 | 2.265625 | 2 | [] | no_license | package com.sumscope.cdh.web.interceptor;
import com.sumscope.cdh.web.domain.UserInfo;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Created by wenshuai.li on 2016/11/2.
*/
public class SecurityInterceptor implements HandlerInterceptor {
private static final String[] allowNames = {"admin"};
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
if(session.getAttribute("USER") != null && check(((UserInfo)session.getAttribute("USER")).getUserName())){
return true;
}else{
throw new SecurityException();
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
private boolean check(String name){
for(String allowName : allowNames){
if(allowName.equals(name)){
return true;
}
}
return false;
}
}
| true |
201a9883002e701ed82f911a8b6d28fa57b3603d | Java | ywISTE/student-project---Smart-Home | /DoorOpener/src/main/java/Touch.java | UTF-8 | 518 | 2.59375 | 3 | [] | no_license | import lejos.robotics.SampleProvider;
import lejos.robotics.filter.AbstractFilter;
/**
* @author Iheb Class for isPressed method.
*/
public class Touch extends AbstractFilter {
private float[] sample;
public Touch(SampleProvider source) {
super(source);
sample = new float[sampleSize];
}
/*
* Method for isPressed
*/
public boolean isPressed() {
super.fetchSample(sample, 0);
if (sample[0] == 0)
return false;
return true;
}
} | true |
f5483fc49f4137a889a5695a95b8af1bf16ffbfb | Java | RamkhanaCh/2014-Adv-Prog | /Adv_Com_ss3/src/TestJFrame.java | UTF-8 | 3,437 | 3.09375 | 3 | [] | no_license | import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TestJFrame extends JFrame {
static JSlider j;
static JLabel sliderLabel;
public static void createAndShowGUI() {
JFrame frame = new JFrame("Ramkhana's Self-Study 3");
frame.setVisible(true);
// JPanel
JPanel p = new JPanel();
p.setBackground(Color.pink);
JPanel p1 = new JPanel();
p1.setBackground(Color.pink);
frame.add(p);
frame.add(p1);
// JLabel
ImageIcon icon = new ImageIcon("D:\\coffee.PNG");
JLabel label = new JLabel("Hello java", icon, JLabel.CENTER);
p.add(label);
// JButton
JButton bt[] = new JButton[3];
frame.setLayout(new GridLayout(6, 1));
bt[0] = new JButton("Button 1");
p1.add(bt[0]);
bt[1] = new JButton("Button 2");
p1.add(bt[1]);
bt[2] = new JButton("Button 3");
p1.add(bt[2]);
// JTextArea
final JTextArea t = new JTextArea();
t.setBackground(Color.cyan);
frame.add(t);
JScrollPane scroll = new JScrollPane(t);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
frame.add(scroll);
// Actionlistener
bt[0].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
t.append("You clicked the first button \n");
}
});
bt[1].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
t.append("You clicked the second button \n");
}
});
bt[2].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
t.append("You clicked the last button \n");
}
});
// JSlider
j = new JSlider(JSlider.HORIZONTAL, 0, 20, 0);
j.setMajorTickSpacing(5);
j.setPaintTicks(true);
frame.add(j);
Event e = new Event();
j.addChangeListener(e);
sliderLabel = new JLabel("Current value = 0", JLabel.CENTER);
sliderLabel.setLayout(new BorderLayout());
frame.add(sliderLabel);
// Bottom part of page
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout());
frame.add(p2);
JButton button = new JButton("End");
JButton button2 = new JButton("Click");
p2.setBackground(Color.yellow);
p2.add(button, BorderLayout.WEST);
p2.add(button2, BorderLayout.EAST);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
t.append("Program is stopped. \n");
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
t.append("Welcome. \n");
}
});
frame.pack();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
| true |
abd0152edfb1a0e688992359436251442da64b8d | Java | trunghq3007/MVC3Layer | /CMC_JAVA_JDBC/src/cmc/data/dao/StudentDAO.java | UTF-8 | 2,422 | 2.859375 | 3 | [] | no_license | package cmc.data.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import cmc.data.model.Student;
import cmc.data.sqlserver.ConnectDB;
public class StudentDAO {
/**
* @description: handle insert to db
* @create_date: Nov 27, 2017
* @author: Ha Quang Trung CMC RDC-Traniner
* @modify_date: Nov 27, 2017
* @modifier: Ha Quang Trung
* @param student
* @return
* @throws ClassNotFoundException
* @throws SQLException
* @exception:
*/
public boolean insert(Student student) throws ClassNotFoundException, SQLException {
Connection connect = ConnectDB.connect();
String sql = "Insert into Student Values(?,?,?,?)";
PreparedStatement prepare = connect.prepareStatement(sql);
connect.setAutoCommit(false);
prepare.setInt(1, student.getStudentId());
prepare.setString(2, student.getFullName());
prepare.setString(3, student.getAddress());
prepare.setInt(4, student.getAge());
connect.setAutoCommit(true);
try {
prepare.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
connect.close();
}
return true;
}
/**
* @description: get all student from tbl student
* @create_date: Nov 27, 2017
* @author: Ha Quang Trung CMC RDC-Traniner
* @modify_date: Nov 27, 2017
* @modifier: Ha Quang Trung
* @param sql
* @return
* @throws SQLException
* @exception:
*/
public List<Student> getList(String sql) throws SQLException {
Connection connect;
// ConnectDB connectDB = new ConnectDB();
try {
connect = ConnectDB.connect();
List<Student> list = new ArrayList<Student>();
// Statement creation
Statement statement = connect.createStatement();
// for retrieve data
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
Student student = new Student();
student.setStudentId(rs.getInt("studentId"));
student.setFullName(rs.getString("fullName"));
student.setAddress(rs.getString("address"));
student.setAge(rs.getInt("age"));
list.add(student);
}
rs.close();
statement.close();
connect.close();
return list;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
| true |
13af4161211cea10c2373b10a74eea0d79680b8d | Java | aritropaul/Java-Lab | /Assignment 3/Donor.java | UTF-8 | 5,536 | 2.921875 | 3 | [
"MIT"
] | permissive | import java.io.*;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.joda.time.LocalDate;
import org.joda.time.DateTime;
import org.joda.time.Period;
import java.util.Date;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Donor {
String name,addr,contact,bldgrp;
Date date;
public static void main(String[] args) throws IOException{
int n, i;
SimpleDateFormat ft = new SimpleDateFormat("MM-dd-yyyy");
String temp;
String pattern = "[A|B|O|AB][+|-]";
Matcher m;
Pattern r = Pattern.compile(pattern);
// delete existing file first
try{
Files.deleteIfExists(Paths.get("donations.txt"));
}
catch(NoSuchFileException e)
{
System.out.println("No such file/directory exists");
}
catch(IOException e)
{
System.out.println("Invalid permissions.");
}
System.out.println("Deletion successful.");
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of donors: ");
n = sc.nextInt();
sc.nextLine();
Donor arr[] = new Donor[n]; // creating array of n donors
ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
FileOutputStream fos = new FileOutputStream("donations.txt"); // creating file to write to
for(i = 0; i < n; i++){
arr[i] = new Donor(); // initializing new donor
//taking input from user
System.out.print("Name: ");
arr[i].name = sc.nextLine();
System.out.print("Address: ");
arr[i].addr = sc.nextLine();
System.out.print("Contact: ");
arr[i].contact = sc.nextLine();
arr[i].bldgrp = "";
m = r.matcher(arr[i].bldgrp);
while(!m.find()){
System.out.print("Blood Group: ");
arr[i].bldgrp = sc.nextLine();
m = r.matcher(arr[i].bldgrp);
}
boolean flag = false;
while(!flag){
System.out.print("Date: ");
temp = sc.nextLine();
try {
arr[i].date = ft.parse(temp);
flag = true;
} catch (ParseException e) {
flag = false;
System.out.println("Unparseable using " + ft);
}
}
// concatenating all properties in donor object
// and converting to a byte stream
outputstream.write(("Donor " + (i+1) + "\n").getBytes());
outputstream.write("----------------\n".getBytes());
outputstream.write("Name: ".getBytes());
outputstream.write(arr[i].name.getBytes());
outputstream.write("\n".getBytes());
outputstream.write("Address: ".getBytes());
outputstream.write(arr[i].addr.getBytes());
outputstream.write("\n".getBytes());
outputstream.write("Contact: ".getBytes());
outputstream.write(arr[i].contact.getBytes());
outputstream.write("\n".getBytes());
outputstream.write("Blood Group: ".getBytes());
outputstream.write(arr[i].bldgrp.getBytes());
outputstream.write("\n".getBytes());
outputstream.write("Date: ".getBytes());
outputstream.write(arr[i].date.toString().getBytes());
outputstream.write("\n".getBytes());
outputstream.write("\n".getBytes());
}
// create a byte array to be written
byte c[] = outputstream.toByteArray();
fos.write(c); // writing byte array to file
fos.close();
// reading data from file
byte[] fileContent = Files.readAllBytes(Paths.get("donations.txt"));
String fileInput = new String(fileContent);
String[] content = fileInput.split("\n");
Date dt2;
String[] fileDate, fileGrp;
SimpleDateFormat ft2 = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
LocalDate current = LocalDate.now();
for(i = 5; i < content.length; i += 8){
fileGrp = content[i].split(": ");
fileDate = content[i+1].split(": ");
System.out.println("\n" + "Donors who haven't donated in 6 months and \"A+\"" + "\n");
try {
dt2 = ft2.parse(fileDate[1]);
DateTime dt3 = new DateTime(dt2);
LocalDate dt1 = new LocalDate(dt3);
Period p = new Period(dt1, current);
// if more than 6 months and blood group is A+, print details
if((p.getMonths() > 6 | p.getYears() >= 1) && fileGrp[1].equals("A+"))
{
System.out.println(content[i-3]); // name
System.out.println(content[i-2]); // address
System.out.println(content[i-1]); // contact
System.out.println(content[i]); // blood group
System.out.println(content[i+1]); // date
System.out.println("\n");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
} | true |
83b5ba9c1935c11df1d7d2fadd64fb3fc9e73578 | Java | cnamway/hsweb-payment | /hsweb-payment-api/src/main/java/org/hswebframework/payment/api/crypto/supports/MessageDigestSignature.java | UTF-8 | 1,887 | 2.3125 | 2 | [
"Apache-2.0"
] | permissive | package org.hswebframework.payment.api.crypto.supports;
import com.google.common.primitives.Bytes;
import org.hswebframework.payment.api.crypto.Signature;
import org.hswebframework.payment.api.utils.UrlUtils;
import org.apache.commons.codec.binary.Hex;
import java.security.MessageDigest;
import java.util.function.BiFunction;
/**
* @author zhouhao
* @since 1.0.0
*/
public class MessageDigestSignature implements Signature {
private byte[] key;
private MessageDigest messageDigest;
public static final BiFunction<Object, byte[], byte[]> DEFAULT_ENCODER = new UrlEncoder();
private BiFunction<Object, byte[], byte[]> encoder = DEFAULT_ENCODER;
private Type type;
public MessageDigestSignature(MessageDigest digest, Type type, byte[] key) {
this.key = key;
this.messageDigest = digest;
this.type = type;
}
public void setEncoder(BiFunction<Object, byte[], byte[]> encoder) {
this.encoder = encoder;
}
@Override
public Type getSignType() {
return type;
}
@Override
public String sign(Object plaintext) {
messageDigest.update(encoder.apply(plaintext, key));
return Hex.encodeHexString(messageDigest.digest()).toUpperCase();
}
@Override
public boolean verify(String sign, Object plaintext) {
return sign.equalsIgnoreCase(sign(plaintext));
}
public static class UrlEncoder implements BiFunction<Object, byte[], byte[]> {
static byte[] appendKeyBytes = "&".getBytes();
@Override
public byte[] apply(Object target, byte[] key) {
if (target instanceof byte[]) {
return Bytes.concat(((byte[]) target), appendKeyBytes, key);
}
return Bytes.concat(UrlUtils.objectToUrlParameters(target, k->!"sign".equals(k)).getBytes(), appendKeyBytes, key);
}
}
}
| true |
f64fe883a48029828745573e357487a72e6eb54a | Java | lukehuang/metrics-spring-boot | /monitor-spring/src/test/java/com/runcoding/monitor/MonitorTest.java | UTF-8 | 1,592 | 1.9375 | 2 | [] | no_license | package com.runcoding.monitor;
import com.alibaba.fastjson.JSON;
import com.runcoding.monitor.web.dao.MetricInfoMapper;
import com.runcoding.monitor.web.model.metrics.MetricInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import java.lang.ref.SoftReference;
import java.util.List;
/**
* @desc 服务
* @author xukai
* @date: 2018年01月31日
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Import(MonitorApplication.class)
public class MonitorTest {
private final Logger logger = LoggerFactory.getLogger(MonitorTest.class);
@Autowired
private MetricInfoMapper serviceAnalysisMapper;
@Test
public void findMetricInfo() {
List<MetricInfo> list = serviceAnalysisMapper.findMetricInfo(0);
logger.info(JSON.toJSONString(list));
}
@Test
public void insert(){
MetricInfo serviceAnalysis = new MetricInfo();
serviceAnalysis.setName("insert");
serviceAnalysis.setMinuteRate(1.2);
serviceAnalysis.setRefDate("2018-03-29 00:00:00");
serviceAnalysis.setCount(1L);
serviceAnalysisMapper.insert(serviceAnalysis);
}
@Test
public void delete(){
serviceAnalysisMapper.delete("2018-03-30 00:00:00");
}
}
| true |
dc14c4102c1b6364b5e42f48c9b431fcd78767f2 | Java | lannaican/Stars-API | /api/src/main/java/com/star/api/adapter/callback/Complete.java | UTF-8 | 223 | 1.632813 | 2 | [] | no_license | package com.star.api.adapter.callback;
import com.star.api.adapter.CallBack;
/**
* Detail:
* Author:Stars
* Create Time:2019/5/31 22:52
*/
public interface Complete {
void onComplete(CallBack callBack);
}
| true |
81fbfa1443217a72509fa7782b6c4f731f4db8da | Java | FanWenTao-Felix/taotao-cloud | /taotao-cloud-gateway/src/main/java/com/taotao/cloud/gateway/filter/gateway/ImageCodeGatewayFilterFactory.java | UTF-8 | 3,218 | 2.21875 | 2 | [] | no_license | package com.taotao.cloud.gateway.filter.gateway;
import cn.hutool.core.util.StrUtil;
import com.taotao.cloud.auth.exception.ValidateCodeException;
import com.taotao.cloud.common.constant.CommonConstant;
import com.taotao.cloud.common.constant.SecurityConstant;
import com.taotao.cloud.redis.template.RedisRepository;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.ResolvableType;
import org.springframework.core.codec.ByteArrayDecoder;
import org.springframework.http.codec.DecoderHttpMessageReader;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import reactor.core.publisher.Mono;
import java.util.Collections;
/**
* 图形验证码验证
*
* @author dengtao
* @date 2020/4/29 22:13
*/
@Slf4j
@Component
public class ImageCodeGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
@Autowired
private RedisRepository redisRepository;
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
if (!StrUtil.containsAnyIgnoreCase(request.getURI().getPath(), SecurityConstant.OAUTH_TOKEN_URL)) {
return chain.filter(exchange);
}
validateCode(request);
return chain.filter(exchange);
};
}
@SneakyThrows
private void validateCode(ServerHttpRequest request) {
MultiValueMap<String, String> params = request.getQueryParams();
// 验证码
String code = params.getFirst("code");
// 随机标识
String t = params.getFirst("t");
// 验证验证码流程
if (StrUtil.isBlank(code)) {
throw new ValidateCodeException("验证码不能为空");
}
String key = CommonConstant.TAOTAO_CAPTCHA_KEY + t;
if (!redisRepository.exists(key)) {
throw new ValidateCodeException("验证码不合法");
}
// 从redis中获取之前保存的验证码跟前台传来的验证码进行匹配
Object captcha = redisRepository.get(key);
if (captcha == null) {
throw new ValidateCodeException("验证码已失效");
}
if (!code.toLowerCase().equals(captcha)) {
throw new ValidateCodeException("验证码错误");
}
}
/**
* 从Flux<DataBuffer>中获取字符串的方法
*
* @return 请求体
*/
private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest) {
DecoderHttpMessageReader<byte[]> httpMessageReader = new DecoderHttpMessageReader(new ByteArrayDecoder());
ResolvableType resolvableType = ResolvableType.forClass(byte[].class);
Mono<byte[]> mono = httpMessageReader.readMono(resolvableType, serverHttpRequest, Collections.emptyMap());
return mono.map(String::new).block();
}
}
| true |
00c5801b281ace31334d488a7d8e5c13e6d7c04f | Java | sawshankscode/DSA | /MyProjct/src/BitMagic/MaxAND.java | UTF-8 | 881 | 3.25 | 3 | [] | no_license | package BitMagic;
public class MaxAND {
static int checkBit(int pattern, int arr[], int n)
{
int count = 0;
for (int i = 0; i < n; i++)
if ((pattern & arr[i]) == pattern)
count++;
return count;
}
// Function for finding maximum and value pair
public static int maxAND (int arr[], int n) {
int res = 0, count;
// iterate over total of 30bits
// from msb to lsb
for (int bit = 31; bit >= 0; bit--)
{
// find the count of element
// having set msb
count = checkBit(res | (1 << bit), arr, n);
// if count >= 2 set particular
// bit in result
if ( count >= 2 )
res |= (1 << bit);
}
return res;
// Complete the function
}
}
| true |
044b7c98b80ac2e52b518ed75bd34551aa40ee9e | Java | zhengzhixiong/xdtech-parent | /xdtech-core/src/main/java/com/xdtech/core/annotation/SchemaExportTool.java | UTF-8 | 4,391 | 2.03125 | 2 | [] | no_license | package com.xdtech.core.annotation;
import java.io.IOException;
import java.util.Properties;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;
import org.hibernate.MappingException;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.ClassUtils;
public class SchemaExportTool extends Configuration {
private static final long serialVersionUID = 1L;
private static final String RESOURCE_PATTERN = "/**/*.class";
private static final String PACKAGE_INFO_SUFFIX = ".package-info";
private static final TypeFilter[] ENTITY_TYPE_FILTERS = new TypeFilter[] {
new AnnotationTypeFilter(Entity.class, false),
new AnnotationTypeFilter(Embeddable.class, false),
new AnnotationTypeFilter(MappedSuperclass.class, false) };
private final ResourcePatternResolver resourcePatternResolver;
public SchemaExportTool() {
this.resourcePatternResolver = ResourcePatternUtils
.getResourcePatternResolver(new PathMatchingResourcePatternResolver());
}
private SchemaExportTool scanPackage(String... packagesToScan) {
try {
for (String pkg : packagesToScan) {
String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
+ ClassUtils.convertClassNameToResourcePath(pkg)
+ RESOURCE_PATTERN;
Resource[] resources = this.resourcePatternResolver
.getResources(pattern);
MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(
this.resourcePatternResolver);
for (Resource resource : resources) {
if (resource.isReadable()) {
MetadataReader reader = readerFactory
.getMetadataReader(resource);
String className = reader.getClassMetadata()
.getClassName();
if (matchesEntityTypeFilter(reader, readerFactory)) {
addAnnotatedClass(this.resourcePatternResolver
.getClassLoader().loadClass(className));
} else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {
addPackage(className.substring(
0,
className.length()
- PACKAGE_INFO_SUFFIX.length()));
}
}
}
}
return this;
} catch (IOException ex) {
throw new MappingException(
"Failed to scan classpath for unlisted classes", ex);
} catch (ClassNotFoundException ex) {
throw new MappingException(
"Failed to load annotated classes from classpath", ex);
}
}
/**
* Check whether any of the configured entity type filters matches the
* current class descriptor contained in the metadata reader.
*/
private boolean matchesEntityTypeFilter(MetadataReader reader,
MetadataReaderFactory readerFactory) throws IOException {
for (TypeFilter filter : ENTITY_TYPE_FILTERS) {
if (filter.match(reader, readerFactory)) {
return true;
}
}
return false;
}
}
| true |
cb66830cd0d360f654bf853f8ebcf480e13e5991 | Java | joey-greenowlmobile/MobiPark_Backend | /src/main/java/com/greenowl/callisto/config/metrics/DatabaseHealthIndicator.java | UTF-8 | 1,864 | 2.375 | 2 | [] | no_license | package com.greenowl.callisto.config.metrics;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* SpringBoot Actuator HealthIndicator check for the Database.
*/
public class DatabaseHealthIndicator extends AbstractHealthIndicator {
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
private static final String TEST_QUERY = "SELECT 1";
private String query = null;
public DatabaseHealthIndicator(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
String query = detectQuery();
if (StringUtils.hasText(query)) {
try {
builder.withDetail("hello",
this.jdbcTemplate.queryForObject(query, Object.class));
} catch (Exception ex) {
builder.down(ex);
}
}
}
private String getProduct() {
return this.jdbcTemplate.execute(new ConnectionCallback<String>() {
@Override
public String doInConnection(Connection connection) throws SQLException,
DataAccessException {
return connection.getMetaData().getDatabaseProductName();
}
});
}
protected String detectQuery() {
return TEST_QUERY;
}
public void setQuery(String query) {
this.query = query;
}
}
| true |
d467bd82e6ada8bb31a38e60db5e28002d2c315c | Java | rkts7258/OOT-Java | /LabTest/lab9/Test2/ContractBook.java | UTF-8 | 330 | 2.96875 | 3 | [] | no_license | package Test2;
public class ContractBook {
private String name = "";
private String tel = "";
public ContractBook(String name,String tel){
this.name = name;
this.tel = tel;
}
public String getName(){
return name;
}
public String getTel(){
return tel;
}
}
| true |
9e7969481639e728de6e46c29702d24830599187 | Java | AGESIC-UY/geo-mvd | /SIGEditor/src/main/java/imm/gis/core/gui/editedfeatures/EditedFeaturesEventManager.java | UTF-8 | 3,341 | 2.234375 | 2 | [] | no_license | package imm.gis.core.gui.editedfeatures;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import imm.gis.core.gui.GuiUtils;
import imm.gis.core.interfaces.IForm;
import imm.gis.core.interfaces.IMap;
import imm.gis.core.interfaces.IModel;
import imm.gis.core.interfaces.ISelection;
import imm.gis.core.model.IStatus;
import javax.swing.AbstractAction;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import org.geotools.feature.Feature;
public class EditedFeaturesEventManager extends MouseAdapter{
private Object userObject;
private JPopupMenu popup;
private JTree tree;
private TreePath selPath;
private AbstractAction editInfoAction;
private AbstractAction centerMapAction;
private IForm form;
private IMap map;
private ISelection selection;
private IModel model;
public EditedFeaturesEventManager(IForm form, IMap map, ISelection selection,
IModel model, JTree editionHistoryTree) {
this.form = form;
this.map = map;
this.selection = selection;
this.model = model;
tree = editionHistoryTree;
createActions();
popup = new JPopupMenu();
popup.add(editInfoAction);
popup.add(centerMapAction);
tree.add(popup);
}
private void createActions(){
editInfoAction = new AbstractAction("Editar datos", GuiUtils.loadIcon("EditInfo16.gif")){
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e){
try {
form.openEditFeatureForm((Feature)userObject);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
};
centerMapAction = new AbstractAction("Centrar mapa"){
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent evt){
Feature f = (Feature)userObject;
map.center(f.getDefaultGeometry().getCentroid().getCoordinate());
selection.selectFeature(f);
}
};
}
public void mouseClicked(MouseEvent e){
if (e.isPopupTrigger() || selPath == null || userObject == null)
return;
/*
if (e.getClickCount() == 2){
if (userObject instanceof Feature) {
Feature f = (Feature)userObject;
try {
coreAccess.getIForm().openEditFeatureForm(f);
}
catch (Exception e1) {
e1.printStackTrace();
}
}
}
*/
else if (e.getClickCount() == 1) {
if (userObject instanceof Feature) {
Feature f = (Feature)userObject;
selection.selectFeature(f);
}
}
}
public void mousePressed(MouseEvent e) {
manejarPopup(e);
}
public void mouseReleased(MouseEvent e){
manejarPopup(e);
}
private void manejarPopup(MouseEvent e) {
selPath = tree.getPathForLocation(e.getX(), e.getY());
userObject = selPath != null ? ((DefaultMutableTreeNode)selPath.getLastPathComponent()).getUserObject() : null;
if (e.isPopupTrigger() && userObject != null && userObject instanceof Feature) {
editInfoAction.setEnabled(model.getStatus((Feature) userObject) != IStatus.DELETED_ATTRIBUTE);
popup.show(tree, e.getX(), e.getY());
}
}
}
| true |
2a3b3ec085863ba735607161a23b3a9e65a473f5 | Java | 0-fps/Spaghetti | /src/me/pabszito/sc/tasks/RepeatingTask.java | UTF-8 | 574 | 2.078125 | 2 | [] | no_license | //
// Decompiled by Procyon v0.5.36
//
package me.pabszito.sc.tasks;
import org.bukkit.plugin.Plugin;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
public abstract class RepeatingTask implements Runnable
{
private int taskId;
public RepeatingTask(final JavaPlugin plugin, final int arg1, final int arg2) {
this.taskId = Bukkit.getScheduler().scheduleSyncRepeatingTask((Plugin)plugin, (Runnable)this, (long)arg1, (long)arg2);
}
public void cancel() {
Bukkit.getScheduler().cancelTask(this.taskId);
}
}
| true |
7aadbaed7c3b21489cb676096369cf605e5b7928 | Java | eiroa/tp-obj3-planificacionDeConferencias | /ar.unq.edu.objetos3.pdc/src-gen/ar/unq/edu/objetos3/parser/antlr/PdcParser.java | UTF-8 | 1,019 | 1.8125 | 2 | [] | no_license | /*
* generated by Xtext
*/
package ar.unq.edu.objetos3.parser.antlr;
import com.google.inject.Inject;
import org.eclipse.xtext.parser.antlr.XtextTokenStream;
import ar.unq.edu.objetos3.services.PdcGrammarAccess;
public class PdcParser extends org.eclipse.xtext.parser.antlr.AbstractAntlrParser {
@Inject
private PdcGrammarAccess grammarAccess;
@Override
protected void setInitialHiddenTokens(XtextTokenStream tokenStream) {
tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT");
}
@Override
protected ar.unq.edu.objetos3.parser.antlr.internal.InternalPdcParser createParser(XtextTokenStream stream) {
return new ar.unq.edu.objetos3.parser.antlr.internal.InternalPdcParser(stream, getGrammarAccess());
}
@Override
protected String getDefaultRuleName() {
return "PDC";
}
public PdcGrammarAccess getGrammarAccess() {
return this.grammarAccess;
}
public void setGrammarAccess(PdcGrammarAccess grammarAccess) {
this.grammarAccess = grammarAccess;
}
}
| true |
3af5f8714edd2c3db4e87fbb7bb5e8244934e631 | Java | jimmyya/xxxxxx | /my_hadoop/src/main/java/com/chen/client/service/FtpService.java | UTF-8 | 12,950 | 2.53125 | 3 | [] | no_license | package com.chen.client.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.util.Properties;
import java.util.Scanner;
import com.chen.client.FtpClient;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import com.chen.client.model.FileModel;
import com.chen.client.model.UserModel;
import com.chen.client.utils.ScannerUtil;
/**
* @description this is the ftpsevice
* 这是一个ftp服务层,主要作用就是翻译用户的输入然后调用工具类,
* 只做了一些基本的检验
* @time 2016/6/6
* @author CHEN
*
*/
public class FtpService {
private Logger logger = Logger.getLogger(FtpService.class);
/**
* 用户登陆
*
* @return
*/
public boolean loginUser(UserModel user) {
InetAddress netAddress=null;
try {
netAddress = InetAddress.getLocalHost();
logger.info("记录日记\n"
+ "访问者ip:"+netAddress.getHostName());
} catch (UnknownHostException e1) {
logger.info("获取不到客户端主机");
logger.error(e1.getMessage(),e1);
} //获得ftp客户端信息
boolean flag = false;
Scanner scanner = ScannerUtil.getScanner();
System.out.print("ftp> open ");
user.setHostname(scanner.next());
System.out.println("连接到" + user.getHostname());
System.out.print("端口号<" + user.getHostname() + ">:");
try {
user.setPort(scanner.nextInt());
}catch (Exception e) {
System.out.println("ftp> 参数错误,连接默认端口21");
user.setPort(21);
}
System.out.print("用户 <" + user.getHostname() + ">:");
user.setUsername(scanner.next());
System.out.print("密码<" + user.getHostname() + ">:");
user.setPassword(scanner.next());
FTPClient ftpClient = new FTPClient();
ftpClient.setControlEncoding("UTF-8");// 设置编码
try {
// 链接服务器
ftpClient.connect(user.getHostname(), user.getPort());
// 登陆服务器
ftpClient.login(user.getUsername(), user.getPassword());
// 判断是否成功登陆
if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
flag = true;
ftpClient.setBufferSize(1024);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
user.setFtpClient(ftpClient);
user.setLogin(true);
user.setWorkPath(File.separator);
System.out.println("登陆成功");
} else {
System.out.println("登陆失败");
ftpClient.disconnect();
}
} catch (SocketException e) {
logger.error(e.getMessage(),e);
} catch (IOException e) {
logger.error(e.getMessage(),e);
}
return flag;
}
/**
* 读取当前目录所有的文件
*
* @return
* @throws IOException
*/
public boolean readAllFile(UserModel user) {
boolean flag = false;
System.setProperty("org.apache.commons.net.ftp.systemType.default","WINDOWS");
FTPClient ftpClient = user.getFtpClient();
FTPFile[] files;
try {
files = ftpClient.listFiles(user.getWorkPath());
for (FTPFile file : files) {
if (file.isFile()) {
// System.out.println(user.getSimpleDateFormat(file
// .getTimestamp()) + " " + file.getName());
System.out.println(file.toString());
} else if (file.isDirectory()) {
System.out.println(file.toString());
// System.out.println(user.getSimpleDateFormat(file.getTimestamp()) + " <dir> /" + file.getName());
} else {
System.out.println("no file or have been broken");
}
}
if(files.length==0) {
System.out.println("no file or have been broken");
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return flag;
}
/**
* 下载一个文件
* @param user
* @return
*/
public boolean getOneFile(UserModel user) {
boolean flag = false;
Scanner scanner = ScannerUtil.getScanner();
FTPClient ftpClient = user.getFtpClient();
System.out.print("远程文件 ");
FileModel file = new FileModel();
file.setOldFileURL(scanner.next());
System.out.print("本地文件 ");
file.setNewFileURL(scanner.next());
// 遍历文件
try {
// 切换到相应的文件夹
// ftpClient.changeWorkingDirectory(user.getWorkPath());
// 下载文件
File localFile = new File(file.getNewFileURL());
OutputStream os = new FileOutputStream(localFile);
if(ftpClient.retrieveFile(file.getOldFileURL(), os)) {
System.out.println("下载成功 "+file.getNewFileURL());
} else {
System.out.println("下载失败");
}
os.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return flag;
}
/**
* 上传一个文件
* @param user
* @return
*/
public boolean sendOneFile(UserModel user) {
boolean flag = false;
Scanner scanner = ScannerUtil.getScanner();
FTPClient ftpClient = user.getFtpClient();
ftpClient.enterLocalActiveMode();
FileModel file = new FileModel();
System.out.print("远程文件 ");
file.setNewFileURL(scanner.next());
System.out.print("本地文件 ");
file.setOldFileURL(scanner.next());
// 分析远程文件
String fileUrl = file.getNewFileURL();
String filePath = null;
try {
filePath = fileUrl.substring(0, fileUrl.indexOf(File.separator));// 获得父级路径
if (File.separator.equals(filePath) || filePath.length() == 0) {
throw new Exception();
}
} catch (Exception e) {
filePath = user.getWorkPath();// 换成当前工作区
}
String fileName = fileUrl.substring(fileUrl.indexOf(File.separator) + 1);// 获得文件名
File originFile = new File(file.getOldFileURL());
try {
String md5Str=getMd5ByFile(originFile);
fileName=fileName+"#"+md5Str;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 上传文件
try {
InputStream is = new FileInputStream(originFile);
// 准备服务器
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// ftpClient.makeDirectory(filePath);
// ftpClient.changeWorkingDirectory(filePath);
if(ftpClient.storeFile(fileName, is)) {
System.out.println("上传成功");
} else {
System.out.println("上传失败");
}
is.close();
flag = true;
} catch (FileNotFoundException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return flag;
}
/**
* 修改工作区间
*
* @param user
*/
public void changDirectory(UserModel user) {
Scanner scanner = ScannerUtil.getScanner();
String tempPath = scanner.next();
FTPClient ftpClient = user.getFtpClient();
// try {
// ftpClient.makeDirectory(tempPath);
// } catch (IOException e) {
// logger.error(e.getMessage(), e);
// }
try {
if(ftpClient.changeWorkingDirectory(tempPath)) {
if(tempPath.startsWith("/")) {
user.setWorkPath(tempPath);
} else {
if("/".equals(user.getWorkPath())) {
user.setWorkPath("/"+tempPath);
} else {
user.setWorkPath(user.getWorkPath() + "/" + tempPath);
}
}
user.setFtpClient(ftpClient);
} else {
System.out.println("路径不存在");
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
/**
* 自动登陆
*
* @param user
*/
public void loginUserByAuto(UserModel user) {
boolean flag = false;
System.out.print("ftp> open ");
// 默认端口号 21
user.setHostname("127.0.0.1");
user.setPort(21);
user.setUsername("chen");
user.setPassword("chen");
FTPClient ftpClient = new FTPClient();
ftpClient.setControlEncoding("UTF-8");// 设置编码
try {
// 链接服务器
ftpClient.connect(user.getHostname(), user.getPort());
// 登陆服务器
ftpClient.login(user.getUsername(), user.getPassword());
// 判断是否成功登陆
if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
flag = true;
ftpClient.enterLocalActiveMode();
user.setFtpClient(ftpClient);
user.setLogin(true);
user.setWorkPath("/");
System.out.println("登陆成功");
} else {
System.out.println("登陆失败");
}
} catch (SocketException e) {
// logger.error(e.getMessage(),e);
} catch (IOException e) {
// logger.error(e.getMessage(),e);
}
}
/**
* 删除文件
*
* @param user
*/
public void deleteOneFile(UserModel user) {
boolean flag = false;
Scanner scanner = ScannerUtil.getScanner();
FTPClient ftpClient = user.getFtpClient();
System.out.print("删除文件 ");
try {
// ftpClient.changeWorkingDirectory(user.getWorkPath());
if(ftpClient.deleteFile(scanner.next())) {
System.out.println("删除成功");
} else {
System.out.println("删除失败");
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
public void mkDir(UserModel user) {
FTPClient ftpClient=user.getFtpClient();
Scanner scanner = ScannerUtil.getScanner();
try {
if(ftpClient.makeDirectory(scanner.next())) {
System.out.println("创建文件夹成功");
} else {
System.out.println("创建文件夹失败");
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 断开链接
*
* @param user
*/
public boolean disConnection(UserModel user) {
try {
user.getFtpClient().disconnect();
// 初始化
user.setFtpClient(null);
user.setHostname("");
user.setPort(0);
user.setLogin(false);
user.setUsername("");
user.setPassword("");
user.setWorkPath(File.separator);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return true;
}
private static String getMd5ByFile(File file) throws FileNotFoundException {
String value = null;
FileInputStream in = new FileInputStream(file);
try {
MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(byteBuffer);
BigInteger bi = new BigInteger(1, md5.digest());
value = bi.toString(16);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return value;
}
}
| true |
502a29a41639724fe0944f5c80a3c5f1093a664f | Java | JayeshMulwani93/VaccNow | /src/main/java/com/xebia/solutions/dto/CompletedVaccinationDTO.java | UTF-8 | 229 | 1.546875 | 2 | [] | no_license | package com.xebia.solutions.dto;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
public class CompletedVaccinationDTO extends ScheduledVaccinationDTO {
private String vaccine;
} | true |
13bda7459ded43fec468acc2e675b7156bd0d562 | Java | damaikurnia/si-kp-agus-adhi | /SistemInformasiPensiunPegawai/src/Model/Instansi.java | UTF-8 | 2,381 | 2.21875 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Model;
/**
*
* @author a9uszT
*/
public class Instansi {
private String idInstansi;
private String nmInstansi;
private String nm_kepala;
private String nip_kepala;
private String pangkatGolkepala;
private PNS pns;
public Instansi() {
}
public Instansi(String idInstansi, String nmInstansi, String nm_kepala, String nip_kepala, String pangkatGolkepala, PNS pns) {
this.idInstansi = idInstansi;
this.nmInstansi = nmInstansi;
this.nm_kepala = nm_kepala;
this.nip_kepala = nip_kepala;
this.pangkatGolkepala = pangkatGolkepala;
this.pns = pns;
}
/**
* @return the idInstansi
*/
public String getIdInstansi() {
return idInstansi;
}
/**
* @param idInstansi the idInstansi to set
*/
public void setIdInstansi(String idInstansi) {
this.idInstansi = idInstansi;
}
/**
* @return the nm_kepala
*/
public String getNm_kepala() {
return nm_kepala;
}
/**
* @param nm_kepala the nm_kepala to set
*/
public void setNm_kepala(String nm_kepala) {
this.nm_kepala = nm_kepala;
}
/**
* @return the nip_kepala
*/
public String getNip_kepala() {
return nip_kepala;
}
/**
* @param nip_kepala the nip_kepala to set
*/
public void setNip_kepala(String nip_kepala) {
this.nip_kepala = nip_kepala;
}
/**
* @return the pns
*/
public PNS getPns() {
return pns;
}
/**
* @param pns the pns to set
*/
public void setPns(PNS pns) {
this.pns = pns;
}
/**
* @return the nmInstansi
*/
public String getNmInstansi() {
return nmInstansi;
}
/**
* @param nmInstansi the nmInstansi to set
*/
public void setNmInstansi(String nmInstansi) {
this.nmInstansi = nmInstansi;
}
/**
* @return the pangkatGolkepala
*/
public String getPangkatGolkepala() {
return pangkatGolkepala;
}
/**
* @param pangkatGolkepala the pangkatGolkepala to set
*/
public void setPangkatGolkepala(String pangkatGolkepala) {
this.pangkatGolkepala = pangkatGolkepala;
}
}
| true |
4318b75330d44297aafc865f013e526e00173eea | Java | JRRRRRRR/Java | /Lab6/lab61.java | UTF-8 | 270 | 3.28125 | 3 | [] | no_license | public class lab61{
public static void main(String[] args) {
int sum = 0;
double average;
for (int i = 0; i < 10; i++){
int random = (int)(Math.random()*100);
sum += random;
}
average = sum / 10.0;
System.out.println("The average is " + average);
}
} | true |
243a7d6f1739c70b7b799a3b1a68ec6740f62d12 | Java | rkenny/rcam-coordinator | /src/main/java/tk/bad_rabbit/rcam/coordinator/server/PollingException.java | UTF-8 | 362 | 2.203125 | 2 | [] | no_license | package tk.bad_rabbit.rcam.coordinator.server;
public class PollingException extends Exception {
private String remoteConnection;
public PollingException(String remoteConnection) {
this();
this.remoteConnection = remoteConnection;
}
public PollingException() {}
public String getRemoteConnection() { return this.remoteConnection; }
}
| true |
f6b8a22d0a2b7db54e11bd1eb7f3ebc01f033018 | Java | AnYu9/manySport | /exam/src/com/znsd/util/ConditionSqlMapperFactory.java | UTF-8 | 2,784 | 2.578125 | 3 | [] | no_license | package com.znsd.util;
import com.znsd.bean.ConditionType;
import com.znsd.bean.ConditionSqlMapper;
public class ConditionSqlMapperFactory {
public static ConditionSqlMapper mapperByType(String name,ConditionType type,int valueLength) {
if(type==ConditionType.EQUALS) {
return equalsMapper(name);
}else if(type==ConditionType.IN) {
return inMapper(name, valueLength);
}else if(type==ConditionType.LIKE) {
return likeMapper(name);
}else if(type==ConditionType.INTERVAL) {
return intervalMapper(name);
}else if(type==ConditionType.START) {
return startMapper(name);
}else if(type==ConditionType.END) {
return endMapper(name);
}else if(type==ConditionType.NOTEQUALS) {
return notEqualsMapper(name);
}
return null;
}
public static ConditionSqlMapper equalsMapper(String name) {
ConditionSqlMapper mapper=new ConditionSqlMapper(name,ConditionType.EQUALS) {
{
String startStr=" ";
this.setConditionSql(startStr+name+" = ?");
}
};
return mapper;
}
public static ConditionSqlMapper likeMapper(String name) {
ConditionSqlMapper mapper=new ConditionSqlMapper(name,ConditionType.LIKE) {
{
String startStr=" ";
this.setConditionSql(startStr+name+" like ?");
}
};
return mapper;
}
public static ConditionSqlMapper inMapper(String name,int valueLength) {
ConditionSqlMapper mapper=new ConditionSqlMapper(name,ConditionType.IN) {
{
String startStr=" ";
StringBuilder paramStr=new StringBuilder(" in (");
for(int i=0;i<valueLength;i++) {
paramStr.append("?");
if(i!=valueLength-1) {
paramStr.append(", ");
}else {
paramStr.append(")");
}
}
this.setConditionSql(startStr+name+paramStr);
}
};
return mapper;
}
public static ConditionSqlMapper intervalMapper(String name) {
ConditionSqlMapper mapper=new ConditionSqlMapper(name,ConditionType.INTERVAL) {
{
String startStr=" ";
this.setConditionSql(startStr+name+" between ? and ?");
}
};
return mapper;
}
public static ConditionSqlMapper startMapper(String name) {
ConditionSqlMapper mapper=new ConditionSqlMapper(name,ConditionType.START) {
{
String startStr=" ";
this.setConditionSql(startStr+name+" >= ?");
}
};
return mapper;
}
public static ConditionSqlMapper endMapper(String name) {
ConditionSqlMapper mapper=new ConditionSqlMapper(name,ConditionType.END) {
{
String startStr=" ";
this.setConditionSql(startStr+name+" =< ?");
}
};
return mapper;
}
public static ConditionSqlMapper notEqualsMapper(String name) {
ConditionSqlMapper mapper=new ConditionSqlMapper(name,ConditionType.NOTEQUALS) {
{
String startStr=" not ";
this.setConditionSql(startStr+name+" = ?");
}
};
return mapper;
}
}
| true |
845d7c5b453e1414b7fcd79b1f8002efbdacf33d | Java | 11michi11/SDJ2 | /CookieJar/src/toilet/Main.java | UTF-8 | 520 | 2.421875 | 2 | [] | no_license | package toilet;
public class Main {
public static void main(String[] args) {
ToiletBuilding tb = new ToiletBuilding(2, 3, 1);
new Thread(new Person("name1", tb)).start();
new Thread(new Person("name2", tb)).start();
new Thread(new Person("name3", tb)).start();
new Thread(new Person("name4", tb)).start();
new Thread(new Person("name5", tb)).start();
new Thread(new Person("name6", tb)).start();
new Thread(new Person("name7", tb)).start();
}
}
| true |
6c25ff434cc2f73c55859b6828c179c7670cee62 | Java | tangrufeng/dachong | /Dachong/src/com/jcyt/lottery/commons/BaseController.java | UTF-8 | 958 | 2.234375 | 2 | [] | no_license | package com.jcyt.lottery.commons;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jcyt.lottery.dto.JsonResult;
/**
* <p>Title: BaseController.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2014</p>
* <p>Company: jc-yt.com</p>
* @author tang
* @date 2014-11-22 下午4:02:05
* @version 1.0
*
*/
public class BaseController {
private static Logger log=Logger.getLogger(BaseController.class);
/**
* 异常处理
* @param ex
* @return
*/
@ExceptionHandler(RuntimeException.class)
public @ResponseBody String handleException(RuntimeException ex){
log.error(ex);
ex.printStackTrace();
JsonResult jr=new JsonResult();
jr.setError(true);
jr.setRespCode(JsonResult.SYS_EXCEPTION);
jr.setRespMsg("Take it easy,as you see,some strange things happened!(o^_^o)");
return jr.toString();
}
}
| true |
9e36fab13133082327c78fa5841fd5b5af124937 | Java | mingchuizihuo/Cjyl | /TotalModule/src/test/java/com/web/OlderNuringLogTest.java | UTF-8 | 900 | 2.3125 | 2 | [] | no_license | package com.web;
import SupportTest.SupportTest;
import com.idea.cjyl.totalmodule.web.domain.pojo.OlderNurseLog;
import com.idea.cjyl.totalmodule.web.domain.vo.OlderNurseLogVO;
import com.idea.cjyl.totalmodule.web.service.OlderNurseLogService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
* Created by xiao on 2016/12/9.
*/
public class OlderNuringLogTest extends SupportTest{
@Autowired
private OlderNurseLogService olderNurseLogService;
@Test
public void findExampleTest(){
OlderNurseLog olderNurseLog = new OlderNurseLog();
olderNurseLog.setOlderId(1l);
List<OlderNurseLogVO> olderNurseLogVOS = olderNurseLogService.findVOByExapmle(olderNurseLog,1,10);
for(OlderNurseLogVO olderNurseLogVO:olderNurseLogVOS){
System.out.println(olderNurseLogVO);
}
}
}
| true |
8e7d0529501471078f023c7318e7b5ce9a2dd56d | Java | MishaShvetsov/Practical_1-32 | /src/Pr03/Ex3/HumanTest.java | UTF-8 | 354 | 2.78125 | 3 | [] | no_license | package Pr03.Ex3;
public class HumanTest {
public static void main(String[] args) {
Leg leg = new Leg(false, 27, 54);
Hand hand = new Hand(false, 7, 27);
Head head = new Head(15, 21);
Human human = new Human(head, leg, hand);
String out_info = human.toString();
System.out.println(out_info);
}
} | true |
b8af29df164e1e0ef14a6e5b314d774ccc98cbf5 | Java | jaeyeun95/java_programming_bible | /src/exercise/Animal.java | UTF-8 | 643 | 3.578125 | 4 | [] | no_license | package exercise;
public class Animal {
private boolean live;
private int age;
private String name;
Animal(){}
Animal(boolean live, int age, String name){
this.live = live;
this.age = age;
this.name = name;
}
public void setName(String name){
this.name = name;
}
public String getName(String name){
return name;
}
public boolean getLive(Boolean live){
return live;
}
public String showInfo(boolean live, int age, String name){
return "동물의 이름은 " + name + "이고 나이는 " + age + " live : " + live;
}
}
| true |
e94310604fe1aedd3be1511e50d0d4c2f2516747 | Java | blueprint00/AlgorithmStudy | /LEVEL2/CompressString.java | UTF-8 | 1,346 | 3.609375 | 4 | [] | no_license | package LEVEL2;
public class CompressString {
public static void main(String[] args){
String s = "ababcdcdababcdcd";
System.out.println(solution(s));
}
public static int solution(String s) {
int answer = s.length();
int length = 1;
while(length <= s.length() / 2){
String pattern = "";
String compression = "";
int cnt = 1;
for(int i = 0; i < s.length() + length; i += length){
String curr = "";
if(i >= s.length()){ // 현재 문자열이 없을 때
curr = "";
} else if(s.length() < i + length){ // 마지막 현재 문자열 일 때
curr = s.substring(i);
} else {
curr = s.substring(i, i + length);
}
if(i != 0){
if(curr.equals(pattern)) cnt ++;
else if(cnt >= 2){
compression += cnt + pattern;
cnt = 1;
} else {
compression += pattern;
}
}
pattern = curr;
}
length ++;
answer = Math.min(answer, compression.length());
}
return answer;
}
} | true |
91dddd5c783d003d34b828ad3ec1c5adc2441a6a | Java | dubshfjh/LeetCode | /Leetcode1031.java | UTF-8 | 1,768 | 3.453125 | 3 | [] | no_license | public class Leetcode1031 {
class Solution {
/**
* 本题看上去像是双指针,但确实不能够每次放弃一半,两个指针start和end,会让问题变得极为复杂
* 考虑只使用1个坐标,作为第1个子数组,第2个子数组的整体右边界。
* 问题的实质,针对每个下标i:Max({L个元素}...i-M{M个元素}i,{M个元素}...i-L{L个元素}i)
* 因此,只需要针对每个下标i,记录i-M左侧的Max(L个元素),i-L左侧的Max(M个元素)即可
* @param A
* @param L
* @param M
* @return
*/
public int maxSumTwoNoOverlap(int[] A, int L, int M) {
if (null == A || 0 == A.length) {
return 0;
}
int[] preSum = new int[A.length];
preSum[0] = A[0];
for (int i = 1; i < A.length; i++) {
preSum[i] = preSum[i - 1] + A[i];
}
int result = preSum[L + M - 1];
// Max Lsum Before i-M
int maxLsum = preSum[L - 1];
// Max Msum Before i-L
int maxMsum = preSum[M - 1];
for (int i = L + M; i < A.length; i++) {
// i-L-M+1 ... i-L(长度为M);i-L+1...i
maxMsum = Math.max(maxMsum, preSum[i - L] - preSum[i - L - M]);
result = Math.max(result, maxMsum + preSum[i] - preSum[i - L]);
// i-L-M+1 ...i-M(长度为L);i-M+1...i
maxLsum = Math.max(maxLsum, preSum[i - M] - preSum[i - L - M]);
result = Math.max(result, maxLsum + preSum[i] - preSum[i - M]);
}
return result;
}
}
}
| true |
de998b29b78e3a9363cf93f6b19fa279b83dc631 | Java | apache/hudi | /hudi-hadoop-mr/src/main/java/org/apache/hudi/hadoop/realtime/RealtimeSplit.java | UTF-8 | 5,522 | 1.703125 | 2 | [
"CC0-1.0",
"MIT",
"JSON",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hudi.hadoop.realtime;
import org.apache.hudi.common.model.HoodieLogFile;
import org.apache.hudi.common.util.Option;
import org.apache.hudi.hadoop.CachingPath;
import org.apache.hudi.hadoop.InputSplitUtils;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.InputSplitWithLocationInfo;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Realtime Input Split Interface.
*/
public interface RealtimeSplit extends InputSplitWithLocationInfo {
/**
* Return Log File Paths.
* @return
*/
default List<String> getDeltaLogPaths() {
return getDeltaLogFiles().stream().map(entry -> entry.getPath().toString()).collect(Collectors.toList());
}
List<HoodieLogFile> getDeltaLogFiles();
void setDeltaLogFiles(List<HoodieLogFile> deltaLogFiles);
/**
* Return Max Instant Time.
* @return
*/
String getMaxCommitTime();
/**
* Return Base Path of the dataset.
* @return
*/
String getBasePath();
/**
* Returns Virtual key info if meta fields are disabled.
* @return
*/
Option<HoodieVirtualKeyInfo> getVirtualKeyInfo();
/**
* Returns the flag whether this split belongs to an Incremental Query
*/
boolean getBelongsToIncrementalQuery();
/**
* Update Maximum valid instant time.
* @param maxCommitTime
*/
void setMaxCommitTime(String maxCommitTime);
/**
* Set Base Path.
* @param basePath
*/
void setBasePath(String basePath);
/**
* Sets the flag whether this split belongs to an Incremental Query
*/
void setBelongsToIncrementalQuery(boolean belongsToIncrementalQuery);
void setVirtualKeyInfo(Option<HoodieVirtualKeyInfo> virtualKeyInfo);
default void writeToOutput(DataOutput out) throws IOException {
InputSplitUtils.writeString(getBasePath(), out);
InputSplitUtils.writeString(getMaxCommitTime(), out);
InputSplitUtils.writeBoolean(getBelongsToIncrementalQuery(), out);
out.writeInt(getDeltaLogFiles().size());
for (HoodieLogFile logFile : getDeltaLogFiles()) {
InputSplitUtils.writeString(logFile.getPath().toString(), out);
out.writeLong(logFile.getFileSize());
}
Option<HoodieVirtualKeyInfo> virtualKeyInfoOpt = getVirtualKeyInfo();
if (!virtualKeyInfoOpt.isPresent()) {
InputSplitUtils.writeBoolean(false, out);
} else {
InputSplitUtils.writeBoolean(true, out);
InputSplitUtils.writeString(virtualKeyInfoOpt.get().getRecordKeyField(), out);
InputSplitUtils.writeString(String.valueOf(virtualKeyInfoOpt.get().getRecordKeyFieldIndex()), out);
InputSplitUtils.writeBoolean(virtualKeyInfoOpt.get().getPartitionPathField().isPresent(), out);
if (virtualKeyInfoOpt.get().getPartitionPathField().isPresent()) {
InputSplitUtils.writeString(virtualKeyInfoOpt.get().getPartitionPathField().get(), out);
InputSplitUtils.writeString(String.valueOf(virtualKeyInfoOpt.get().getPartitionPathFieldIndex()), out);
}
}
}
default void readFromInput(DataInput in) throws IOException {
setBasePath(InputSplitUtils.readString(in));
setMaxCommitTime(InputSplitUtils.readString(in));
setBelongsToIncrementalQuery(InputSplitUtils.readBoolean(in));
int totalLogFiles = in.readInt();
List<HoodieLogFile> deltaLogPaths = new ArrayList<>(totalLogFiles);
for (int i = 0; i < totalLogFiles; i++) {
String logFilePath = InputSplitUtils.readString(in);
long logFileSize = in.readLong();
deltaLogPaths.add(new HoodieLogFile(new CachingPath(logFilePath), logFileSize));
}
setDeltaLogFiles(deltaLogPaths);
boolean hoodieVirtualKeyPresent = InputSplitUtils.readBoolean(in);
if (hoodieVirtualKeyPresent) {
String recordKeyField = InputSplitUtils.readString(in);
int recordFieldIndex = Integer.parseInt(InputSplitUtils.readString(in));
boolean isPartitionPathFieldPresent = InputSplitUtils.readBoolean(in);
Option<String> partitionPathField = isPartitionPathFieldPresent ? Option.of(InputSplitUtils.readString(in)) : Option.empty();
Option<Integer> partitionPathIndex = isPartitionPathFieldPresent ? Option.of(Integer.parseInt(InputSplitUtils.readString(in))) : Option.empty();
setVirtualKeyInfo(Option.of(new HoodieVirtualKeyInfo(recordKeyField, partitionPathField, recordFieldIndex, partitionPathIndex)));
}
}
/**
* The file containing this split's data.
*/
Path getPath();
/**
* The position of the first byte in the file to process.
*/
long getStart();
/**
* The number of bytes in the file to process.
*/
long getLength();
}
| true |
78c090742d922eb9ce05c9dbd22248d588a26bcf | Java | gruzzle/council | /src/secret/council/MainActivity.java | UTF-8 | 6,664 | 2.65625 | 3 | [] | no_license | package secret.council;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import secret.council.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends Activity
implements android.widget.SeekBar.OnSeekBarChangeListener {
public static final String TAG = "MainActivity";
private Player player = null;
private Councilman[] councilmen = new Councilman[5];
private Random random = new Random();
private DatabaseHelper db;
// TODO try to remove?
protected Player getPlayer() { return player; }
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // no titlebar, maybe do a better way
initializeBadGuys(); // TODO currently needs to be before setContentView, fix?
setContentView(R.layout.activity_main);
// create fragments
FragmentManager fragmentManager = getFragmentManager();
SliderFragment sliderFragment = new SliderFragment();
fragmentManager.beginTransaction().add(R.id.fragment_container_left, sliderFragment).commit();
DetailFragment detailFragment = new DetailFragment();
fragmentManager.beginTransaction().add(R.id.fragment_container_right, detailFragment).commit();
// make sure we're using most recent db file
DatabaseHelper.forceDatabaseReload(this);
db = new DatabaseHelper(this);
updateBar();
}
/*
* Update status bar with resources etc.
*/
private void updateBar() {
String resources = String.format("Money: $%d\nAgents: %d\nMedia reach: %d\nPopulation unrest: %d"
, player.getMoney(), player.getAgentNumber(), player.getMediaReach(), player.getUnrestSpread());
((TextView) findViewById(R.id.text_resource_display_left)).setText(resources);
resources = String.format("\nAgent skill: %.0f%%\nMedia influence: %.0f%%\nPopulation care: %.0f%%"
, player.getAgentSkill(), player.getMediaPerception(), player.getUnrestStrength());
((TextView) findViewById(R.id.text_resource_display_right)).setText(resources);
}
/*
* Create player and councilmen
*/
private void initializeBadGuys() {
player = new Player();
for (int i = 0; i < councilmen.length; i++) {
councilmen[i] = new Councilman();
}
}
/*
* Tick everything and do events
* Then update status bar
*/
public void nextTurn() {
Log.d(TAG, "nextTurn()");
tickPeople();
//doEvents();
updateBar();
}
/*
* Tick player and councilmen
*/
private void tickPeople() {
player.tick();
for (Councilman councilman: councilmen) {
councilman.tick();
}
}
/*
* Creates some events and applies their effects
*/
private void doEvents() {
applyEvents(generateEvents());
}
/*
* Generate a list of new events for this turn
*/
private List<Event> generateEvents() {
List<Event> events = new ArrayList<Event>();
int numEvents = random.nextInt(2) + 1;
for (int i = 0; i < numEvents; i++) {
Event newEvent = null;
do {
newEvent = new Event(db);
} while (events.contains(newEvent)); // make sure only one instance of an event occurs per turn
events.add(newEvent);
}
return events;
}
/*
* Present events to the player and carry out their effects
*/
private void applyEvents(List<Event> events) {
for (Event event : events) {
for (Event.Effect effect : event.getEffects()) {
applyEffect(effect);
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(event.getName()).setMessage(event.getDescription()).setCancelable(false).setNeutralButton("OK", null);
builder.create().show();
}
}
/*
* Carries out an effect by applying it to the game state
*/
private void applyEffect(Event.Effect effect) {
int change = (int) effect.getValue();
switch(effect.getType()) {
case INCREASE_MONEY:
player.setMoney(player.getMoney() + change);
break;
case DECREASE_MONEY:
player.setMoney(player.getMoney() - change);
break;
case INCREASE_AGENTS:
player.setAgentNumber(player.getAgentNumber() + change);
break;
case DECREASE_AGENTS:
player.setAgentNumber(player.getAgentNumber() - change);
break;
case INCREASE_AGENT_SKILL:
player.setAgentSkill(player.getAgentSkill() + change);
break;
case DECREASE_AGENT_SKILL:
player.setAgentSkill(player.getAgentSkill() - change);
break;
case INCREASE_MEDIA_REACH:
player.setMediaReach(player.getMediaReach() + change);
break;
case DECREASE_MEDIA_REACH:
player.setMediaReach(player.getMediaReach() - change);
break;
case INCREASE_MEDIA_INFLUENCE:
player.setMediaPerception(player.getMediaPerception() + change);
break;
case DECREASE_MEDIA_INFLUENCE:
player.setMediaPerception(player.getMediaPerception() - change);
break;
default:
// TODO handle error
}
}
/*
* A slider has changed, update resources to reflect change
* Then update the text on the details fragment
*/
private void sliderChanged(int sliderID, int progress) {
switch (sliderID) {
case R.id.slider_agent:
updateAgentChangeFromSlider(progress);
break;
case R.id.slider_media:
updateMediaChangeFromSlider(progress);
break;
case R.id.slider_unrest:
updateUnrestChangeFromSlider(progress);
break;
}
// update detail fragment UI
((DetailFragment) getFragmentManager().findFragmentById(R.id.fragment_container_right)).updateUI();
}
private void updateAgentChangeFromSlider(int progress) {
// TODO turn progress percentage into a number
player.setAgentNumberChange(progress / 10);
}
private void updateMediaChangeFromSlider(int progress) {
// TODO turn progress percentage into a number
player.setMediaReachChange(progress / 10);
}
private void updateUnrestChangeFromSlider(int progress) {
// TODO turn progress percentage into a number
player.setUnrestSpreadChange(progress / 10);
}
public void onClickNextTurn(View view) {
nextTurn();
}
/*
* Begin SeekBar listener methods
*/
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
sliderChanged(seekBar.getId(), progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
return;
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
return;
}
/*
* End SeekBar listener methods
*/
}
| true |
e06c22c81112dd66cd67f8f9818cf8d230209d8f | Java | javber/CPU_java | /src/tp/pr5/mv/instrucciones/Instruction.java | UTF-8 | 770 | 2.59375 | 3 | [
"MIT"
] | permissive | package tp.pr5.mv.instrucciones;
import tp.pr5.mv.instrucciones.excepciones.InstructionExecutionException;
import tp.pr5.mv.modulos.*;
import tp.pr5.mv.modulos.streams.InMethod;
import tp.pr5.mv.modulos.streams.OutMethod;
public interface Instruction {
abstract public String getMnemonic();
abstract public void execute(OperandStack pilaOperandos, Memory memoria,
ProgramCounter pc, InMethod input, OutMethod output) throws InstructionExecutionException;
abstract public String getInstructionRepresentation();
abstract public Instruction parse(String cadena[]);
}
/*
ZeroDivException
-> División por cero
StackOperandException
-> Faltan operandos en la pila
MemoryException
-> Dirección de memoria no válida(negativa, memoria llena...)
*/ | true |
32d6091c70d4af2a5db53de990207e7b32befbaf | Java | ShravanthiB/trunk | /target/generated-sources/mule/org/mule/modules/jbpm/adapters/JBPMConnectorCapabilitiesAdapter.java | UTF-8 | 1,050 | 1.851563 | 2 | [] | no_license |
package org.mule.modules.jbpm.adapters;
import javax.annotation.Generated;
import org.mule.api.devkit.capability.Capabilities;
import org.mule.api.devkit.capability.ModuleCapability;
import org.mule.modules.jbpm.JBPMConnector;
/**
* A <code>JBPMConnectorCapabilitiesAdapter</code> is a wrapper around {@link JBPMConnector } that implements {@link org.mule.api.Capabilities} interface.
*
*/
@SuppressWarnings("all")
@Generated(value = "Mule DevKit Version 3.7.1", date = "2015-12-10T05:22:27+05:30", comments = "Build UNNAMED.2613.77421cc")
public abstract class JBPMConnectorCapabilitiesAdapter
extends JBPMConnector
implements Capabilities
{
/**
* Returns true if this module implements such capability
*
*/
public boolean isCapableOf(ModuleCapability capability) {
if (capability == ModuleCapability.LIFECYCLE_CAPABLE) {
return true;
}
if (capability == ModuleCapability.CONNECTION_MANAGEMENT_CAPABLE) {
return true;
}
return false;
}
}
| true |
d2416c3db8e1022ac692dd2bf1547e516e4871ae | Java | SZUE/iolapCharts | /src/main/java/com/instantolap/charts/renderer/impl/annotation/AnnotationDrawer.java | UTF-8 | 2,798 | 2.671875 | 3 | [] | no_license | package com.instantolap.charts.renderer.impl.annotation;
import com.instantolap.charts.renderer.ChartColor;
import com.instantolap.charts.renderer.ChartFont;
import com.instantolap.charts.renderer.Renderer;
import com.instantolap.charts.renderer.impl.TextInfo;
public class AnnotationDrawer {
public static void draw(Renderer r, ChartFont font, ChartColor foreground,
ChartColor background, Double pointerX, Double pointerY,
Double boxX, Double boxY, int anchor, double rotation, String text)
{
// find bubble size
final double x;
final double y;
if (pointerX != null) {
x = pointerX;
y = pointerY;
} else if (boxX != null) {
x = boxX;
y = boxY;
} else {
return;
}
r.setFont(font);
final TextInfo i = r.getTextInfo(x, y, text, rotation, anchor);
final double padding = 5;
final double distance = 20;
double bx = i.x - padding;
double by = i.y - padding;
final double bw = i.w + 2 * padding;
final double bh = i.h + 2 * padding;
if (pointerX != null && pointerY != null) {
switch (anchor) {
case Renderer.NORTH:
by = pointerY - distance - bh;
if (by < 0) {
by = (int) (pointerY + distance);
}
break;
case Renderer.SOUTH:
by = pointerY + distance;
if (by + bh > r.getHeight()) {
by = (int) (pointerY - distance - bh);
}
break;
case Renderer.WEST:
bx = pointerX - distance - bw;
if (bx < 0) {
bx = pointerX + distance;
}
break;
case Renderer.EAST:
bx = pointerX + distance;
if (bx + bw > r.getWidth()) {
bx = pointerX - distance - bw;
}
break;
}
}
// move into area
if (boxX != null) {
bx = boxX;
}
bx = Math.max(bx, 0);
bx = Math.min(bx, r.getWidth() - bw);
if (boxY != null) {
by = boxY;
}
by = Math.max(by, 0);
by = Math.min(by, r.getHeight() - bh);
final int arc = 5;
r.setColor(ChartColor.SHADOW);
if (pointerX != null) {
r.fillBubble(bx + 3, by + 3, bw, bh, pointerX + 3, pointerY + 3, arc);
} else {
r.fillRoundedRect(bx + 3, by + 3, bw, bh, arc);
}
r.setColor(background);
if (pointerX != null) {
r.fillBubble(bx, by, bw, bh, pointerX, pointerY, arc);
} else {
r.fillRoundedRect(bx, by, bw, bh, arc);
}
r.setColor(ChartColor.BLACK);
if (pointerX != null) {
r.drawBubble(bx, by, bw, bh, pointerX, pointerY, arc);
} else {
r.drawRoundedRect(bx, by, bw, bh, arc);
}
r.setColor(foreground);
r.drawText(bx + bw / 2, by + bh / 2, text, rotation, Renderer.CENTER, false);
}
}
| true |
61ad5501b1848e7d95b7e82410d43915b1596944 | Java | thiagocrestani/jdownloader-service | /src/jd/plugins/hoster/FilestoreTo.java | UTF-8 | 4,621 | 1.765625 | 2 | [] | no_license | // jDownloader - Downloadmanager
// Copyright (C) 2008 JD-Team support@jdownloader.org
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.http.Browser;
import jd.http.RandomUserAgent;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.DownloadLink;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.DownloadLink.AvailableStatus;
@HostPlugin(revision = "$Revision: 12350 $", interfaceVersion = 2, names = { "filestore.to" }, urls = { "http://[\\w\\.]*?filestore\\.to/\\?d=[A-Z0-9]+" }, flags = { 0 })
public class FilestoreTo extends PluginForHost {
public FilestoreTo(PluginWrapper wrapper) {
super(wrapper);
this.setStartIntervall(2000l);
}
@Override
public void init() {
Browser.setRequestIntervalLimitGlobal(getHost(), 500);
}
@Override
public String getAGBLink() {
return "http://www.filestore.to/rules.php?setlang=en";
}
@Override
public AvailableStatus requestFileInformation(DownloadLink downloadLink) throws IOException, InterruptedException, PluginException {
this.setBrowserExclusive();
br.getHeaders().put("User-Agent", RandomUserAgent.generate());
String url = downloadLink.getDownloadURL();
String downloadName = null;
String downloadSize = null;
for (int i = 1; i < 10; i++) {
try {
br.getPage(url);
} catch (Exception e) {
continue;
}
if (!br.containsHTML("<strong>Download-Datei wurde nicht gefunden</strong")) {
downloadName = Encoding.htmlDecode(br.getRegex("\">Dateiname:</td>.*?<td colspan=\"2\" style=\"color:.*?;\">(.*?)</td>").getMatch(0));
downloadSize = (br.getRegex("\">Dateigr\\ö\\ße:</td>.*?<td width=\"\\d+\" style=\".*?\">(.*?)</td>").getMatch(0));
if (downloadName != null) {
downloadLink.setName(downloadName);
if (downloadSize != null) downloadLink.setDownloadSize(Regex.getSize(downloadSize.replaceAll(",", "\\.")));
return AvailableStatus.TRUE;
}
}
}
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
@Override
public void handleFree(DownloadLink downloadLink) throws Exception {
requestFileInformation(downloadLink);
String sid = br.getRegex("name=\"sid\" value=\"(.*?)\"").getMatch(0);
String fid = new Regex(downloadLink.getDownloadURL(), "filestore\\.to/\\?d=([A-Z0-9]+)").getMatch(0);
// String ajaxFun = "http://filestore.to/ajax/download.php?a=1&f=" + fid
// + "&s=" + sid;
// br.getPage(ajaxFun);
String ajaxDownload = "http://filestore.to/ajax/download.php?f=" + fid + "&s=" + sid;
br.getPage(ajaxDownload);
br.setFollowRedirects(true);
String dllink = br.toString().trim();
if (!dllink.startsWith("http://")) throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, 0);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
}
@Override
public int getTimegapBetweenConnections() {
return 2000;
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void reset() {
}
@Override
public void resetPluginGlobals() {
}
@Override
public void resetDownloadlink(DownloadLink link) {
}
}
| true |
d859e0b042da379984d2f7f09e1575656577c2b2 | Java | CQJames/EmotionWebsite | /src/com/ew/entity/User.java | UTF-8 | 3,301 | 1.984375 | 2 | [] | no_license | package com.ew.entity;
import java.util.HashSet;
import java.util.Set;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
@Controller("user")
@Scope("prototype")
public class User extends BaseEntity {
/**
* 用户实体
*/
private static final long serialVersionUID = -5170142231358661154L;
// 自身表id
private String userID;
// 真实姓名
private String name;
// 性别
private Boolean sex;
// 手机号码
private String phoneNumber;
// 电子邮箱
private String email;
// 头像图标路径
private String icon;
// 备注
private String remark;
// 用户名
private String username;
// 密码
private String password;
// 是否删除该用户
private Boolean isDelete;
//一对多自我提升评论
private Set<SelfEnhancementComment> selfEnhancementComment = new HashSet<SelfEnhancementComment>();
//一对多交往技巧评论
private Set<CommunicationSkillsComment> communicationSkillsComment = new HashSet<CommunicationSkillsComment>();
private Set<Reply> reply = new HashSet<Reply>();
private Set<Collection> collection = new HashSet<Collection>();
public Set<Collection> getCollection() {
return collection;
}
public void setCollection(Set<Collection> collection) {
this.collection = collection;
}
public Set<Reply> getReply() {
return reply;
}
public void setReply(Set<Reply> reply) {
this.reply = reply;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getSex() {
return sex;
}
public void setSex(Boolean sex) {
this.sex = sex;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Boolean getIsDelete() {
return isDelete;
}
public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete;
}
public Set<SelfEnhancementComment> getSelfEnhancementComment() {
return selfEnhancementComment;
}
public void setSelfEnhancementComment(Set<SelfEnhancementComment> selfEnhancementComment) {
this.selfEnhancementComment = selfEnhancementComment;
}
public Set<CommunicationSkillsComment> getCommunicationSkillsComment() {
return communicationSkillsComment;
}
public void setCommunicationSkillsComment(Set<CommunicationSkillsComment> communicationSkillsComment) {
this.communicationSkillsComment = communicationSkillsComment;
}
}
| true |
ba41210c9ac188bc6beb61ef3169bd58e93cb8af | Java | kiabthao/forum | /Exo07Forum/Exo07ForumBusiness/src/main/java/fr/afpa/formation/service/CommentaireServiceImp.java | UTF-8 | 6,205 | 2.234375 | 2 | [] | no_license | package fr.afpa.formation.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import fr.afpa.formation.entity.Commentaire;
import fr.afpa.formation.entity.SujetContent;
//import fr.afpa.formation.interfaceService.CommentaireService;
import fr.afpa.formation.interfaceService.IService;
import fr.afpa.formation.repository.CommentaireRepository;
import fr.afpa.formation.service.exception.CommentaireAllreadyExistsException;
import fr.afpa.formation.service.exception.CommentaireNotAviableException;
import fr.afpa.formation.service.exception.CommentaireNotFoundExcpetion;
import fr.afpa.formation.service.exception.CommentaireNotValidException;
@Service
public class CommentaireServiceImp implements IService<Commentaire, Exception>{
@Autowired
CommentaireRepository commentaireRepository;
// @Override
public List<Commentaire> list() throws CommentaireNotAviableException {
List<Commentaire> commentaires = (List<Commentaire>) commentaireRepository.findAll();
if (commentaires == null || commentaires.size() == 0) {
throw new CommentaireNotAviableException();
}
return commentaires;
}
// @Override
public Commentaire create(Commentaire commentaire) throws CommentaireNotValidException, CommentaireAllreadyExistsException {
if (commentaire == null) {
throw new CommentaireNotValidException();
}
if (commentaire.getId() != null) {
Optional<Commentaire> commentaireFromDB = commentaireRepository.findById(commentaire.getId());
if (commentaireFromDB.isPresent()) {
throw new CommentaireAllreadyExistsException();
} else {
throw new CommentaireNotValidException();
}
}
return commentaireRepository.save(commentaire);
}
// @Override
public Commentaire update(Commentaire commentaire) throws CommentaireNotValidException, CommentaireNotFoundExcpetion {
if (commentaire == null) {
throw new CommentaireNotValidException();
}
if (commentaire.getId() == null) {
throw new CommentaireNotValidException();
} else {
Optional<Commentaire> commentaireFromDB = commentaireRepository.findById(commentaire.getId());
if (!commentaireFromDB.isPresent()) {
throw new CommentaireNotFoundExcpetion();
}
}
return commentaireRepository.save(commentaire);
}
// @Override
public List<Commentaire> createAll(List<Commentaire> commentaires)
throws CommentaireNotValidException, CommentaireAllreadyExistsException {
if (commentaires == null || commentaires.size() == 0) {
throw new CommentaireNotValidException();
}
for (Commentaire commentaire : commentaires) {
if (commentaire == null) {
throw new CommentaireNotValidException();
}
if (commentaire.getId() != null) {
Optional<Commentaire> commentaireFromDB = commentaireRepository.findById(commentaire.getId());
if (commentaireFromDB.isPresent()) {
throw new CommentaireAllreadyExistsException();
} else {
throw new CommentaireNotValidException();
}
}
}
return (List<Commentaire>) commentaireRepository.saveAll(commentaires);
}
// @Override
public List<Commentaire> updateAll(List<Commentaire> commentaires) throws CommentaireNotFoundExcpetion, CommentaireNotValidException {
if (commentaires == null) {
throw new CommentaireNotValidException();
}
if (commentaires.size() == 0) {
throw new CommentaireNotValidException();
}
for (Commentaire commentaire : commentaires) {
if (commentaire == null) {
throw new CommentaireNotValidException();
}
if (commentaire.getId() == null) {
throw new CommentaireNotValidException();
} else {
Optional<Commentaire> commentaireFromDB = commentaireRepository.findById(commentaire.getId());
if (!commentaireFromDB.isPresent()) {
throw new CommentaireNotFoundExcpetion();
}
}
}
return (List<Commentaire>) commentaireRepository.saveAll(commentaires);
}
// @Override
public void delete(Commentaire commentaire)
throws CommentaireNotValidException, CommentaireNotFoundExcpetion, CommentaireNotAviableException {
if (commentaire == null) {
throw new CommentaireNotValidException();
} else if (commentaire.getId() == null) {
throw new CommentaireNotFoundExcpetion();
}
if (!list().contains(commentaire)) {
throw new CommentaireNotAviableException();
}
commentaireRepository.delete(commentaire);
}
// @Override
public void deleteAll(List<Commentaire> commentaires) throws CommentaireNotFoundExcpetion {
if (commentaires == null) {
throw new CommentaireNotFoundExcpetion();
}
if (commentaires.size() == 0) {
throw new CommentaireNotFoundExcpetion();
}
for (Commentaire commentaire : commentaires) {
if (commentaire.getId() == null) {
throw new CommentaireNotFoundExcpetion();
}
}
commentaireRepository.deleteAll(commentaires);
}
// @Override
public void deleteById(Long id) throws CommentaireNotFoundExcpetion {
if (id == null) {
throw new CommentaireNotFoundExcpetion();
}
commentaireRepository.deleteById(id);
}
// @Override
public Commentaire findById(Long id) throws CommentaireNotFoundExcpetion {
if (id == null) {
throw new CommentaireNotFoundExcpetion();
}
// Commentaire commentaire = commentaireRepository.findById(id).get();
// if(commentaireRepository == null) {
// System.out.println("commentaireRepository NULL !!!!!");
//
// }
Optional<Commentaire> commentaire = commentaireRepository.findById(id);
if(commentaire == null || !commentaire.isPresent()) {
throw new CommentaireNotFoundExcpetion();
}
return commentaire.get();
}
// @Override
public SujetContent findSujetContentByCommentaireId(Long id) throws CommentaireNotFoundExcpetion {
if (id == null) {
throw new CommentaireNotFoundExcpetion();
}
Optional<Commentaire> commentaire = commentaireRepository.findById(id);
if(commentaire == null || !commentaire.isPresent()) {
throw new CommentaireNotFoundExcpetion();
}
//TODO EXCEPTION FOR THE CASE WHENE THE FINDBY RETURN A NULL
SujetContent sujetContent = commentaireRepository.findSujetContentByCommentaireId(id);
return sujetContent;
}
} | true |
542b69e8d6e84d7d55a52a432a021b58b5130c8e | Java | kevmodonahoe/AI-HMM | /src/HMM/BeliefState.java | UTF-8 | 813 | 3.078125 | 3 | [] | no_license | package HMM;
/**
* Created by kdonahoe on 11/11/16.
*/
import java.util.ArrayList;
public class BeliefState {
ArrayList<Double> state;
MapCreator.Map map;
public BeliefState() {
state = new ArrayList<>();
}
public BeliefState(MapCreator.Map map) {
this.map = map;
}
/*
Initializes the first belief state with proper probabilities.
*/
public void initialBelifState(int numWalls, ArrayList<Integer> wallLocations) {
Double prob = (1.0 / (16 - numWalls));
for(int i=0; i<16; i++) {
if(wallLocations.contains(i)) {
state.add(0.0); // if there's a wall in that location, the probability of moving there should be 0%
} else {
state.add(prob);
}
}
}
}
| true |
97fa23fb2bb8899bf991050684ba49e3e094d7bf | Java | writeonly/eq-for-java | /equals/src/main/java/pl/writeonly/java/equals/impl/BaroqueTag.java | UTF-8 | 944 | 2.703125 | 3 | [
"MIT"
] | permissive | package pl.writeonly.java.equals.impl;
import com.google.common.base.MoreObjects;
import pl.writeonly.java.equals.api.BoilerplateEqable;
import java.util.Objects;
public class BaroqueTag implements BoilerplateEqable<BaroqueTag> {
private final String name;
private final int count;
public BaroqueTag(String name, int count) {
this.name = name;
this.count = count;
}
@Override
public boolean equals(Object other) {
return defaultEquals(other);
}
@Override
public boolean eq(BaroqueTag that) {
return Objects.equals(name, that.name) && Objects.equals(count, that.count);
}
@Override
public int hashCode() {
return Objects.hash(name, count);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("name", name)
.add("count", count)
.toString();
}
}
| true |
4bd8d81b13963eb285a786dbbbad22c8c25b434e | Java | honza801/eplconfig | /src/cz/rexcontrols/epl/editor/ProfileInterface.java | UTF-8 | 3,975 | 2.203125 | 2 | [] | no_license | package cz.rexcontrols.epl.editor;
/**
* Copyright 2010 Jan Krcmar. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY Jan Krcmar ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Jan Krcmar OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of Jan Krcmar.
*
*/
import java.io.File;
import java.util.List;
import java.util.Properties;
/**
* Methods defining profile/node interface.
* Profile should contain following items:
* <ul>
* <li>profile name</li>
* <li>profile id</li>
* <li>profile source file name</li>
* </ul>
*
* @author honza801
*
*/
public interface ProfileInterface extends Comparable<ProfileInterface> {
/**
*
* @return Name of this Profile
*/
public String getProfileName();
/**
* Sets name of this profile
* @param profileName
*/
public void setProfileName(String profileName);
/**
*
* @return Id of this Profile
*/
public int getProfileId();
/**
* Sets Id of this Profile
* @param profileId
*/
public void setProfileId(int profileId);
/**
*
* @return Root nodes of the DocumentInterface.
*/
public List<RootNodeInterface> getRootNodes();
/**
*
* @return Source file of the profile.
*/
public File getSourceFile();
/**
* Set source file for DocumentInterface.
* @param file
*/
public void setSourceFile(File file);
/**
*
* @return Document that was used to create this object.
*/
public DocumentInterface getDocument();
public String getSourceFileName();
/**
*
* @return Properties of this profile for viewing.
*/
public Properties getViewProperties();
/**
* Adds object to the profile.
* @param object
* @return position of child subobject in list
*/
public int addObject(EplIndex object);
/**
* Removes object from list.
* @param object
*/
public void removeObject(EplIndex object);
/**
*
* @return Objects owned by this profile.
*/
public List<EplIndex> getObjects();
/**
*
* @param index
* @return ObjectNode specified by index.
*/
public EplIndex getByIndex(int index);
public EplSubindex getSubindex(int index, int subindex);
public boolean isMN();
/**
* Saves document in specified folder.
* @param targetDir
*/
public void saveDocument(File targetDir);
public BaseNodeInterface getObject(int index, int subindex);
/**
* @param isRex the isRex to set
*/
public void setRexNode(boolean rexNode);
/**
* @return the isRex
*/
public boolean isRexNode();
public boolean isModified();
public void setModified(boolean modified);
public boolean isDisabled();
public void setDisabled(boolean disabled);
public boolean isAdvanced();
}
| true |
d1b0b66941117e87a4171e248b1af135ecba2d1f | Java | godkkoo/BEshop-Project- | /BEshop 1차/View/TabIdPwd.java | UTF-8 | 3,190 | 2.390625 | 2 | [] | no_license | package View;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
public class TabIdPwd extends JFrame{
//id찾기
JRadioButton idtel;
JRadioButton idemail;
ButtonGroup idg;
JPanel idbtn_next;
JPanel idtype;
JButton idbtnn;
//pwd찾기
JRadioButton pwdtel;
JRadioButton pwdemail;
ButtonGroup pwdg;
JPanel pwdbtn_next;
JPanel pwdtype;
JButton pwdbtnn;
//tab
JTabbedPane tab;
public TabIdPwd() {
// TODO Auto-generated constructor stub
//idŸ��
idtype=new JPanel();
idtel=new JRadioButton("회원정보에 등록한 휴대전화로 인증");
idemail=new JRadioButton("본인확인 이메일로 인증");
idg=new ButtonGroup();
idg.add(idtel);
idg.add(idemail);
idbtnn=new JButton("다음");
idbtnn.setPreferredSize(new Dimension(300, 30));
//idbtn_next.add(idbtnn);
idtype=new JPanel();
idtype.setLayout(new GridLayout(3,1));
idtype.add(idtel);
idtype.add(idemail);
idtype.add(idbtnn);
idbtnn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Findid f=new Findid();
try {
if(idtel.isSelected())
{
f.Findidtel();
}
else if(idemail.isSelected())
{
f.Findidemail();
}
} catch (Exception e2) {
// TODO: handle exception
System.out.println(e2.getMessage());
}
}
});
//pwdŸ��
pwdtype=new JPanel();
pwdtel=new JRadioButton("회원정보에 등록한 휴대전화로 인증");
pwdemail=new JRadioButton("본인확인 이메일로 인증");
pwdg=new ButtonGroup();
pwdg.add(pwdtel);
pwdg.add(pwdemail);
pwdbtnn=new JButton("다음");
pwdbtnn.setPreferredSize(new Dimension(300, 30));
//pwdbtn_next.add(pwdbtnn);
pwdtype=new JPanel();
pwdtype.setLayout(new GridLayout(3,1));
pwdtype.add(pwdtel);
pwdtype.add(pwdemail);
pwdtype.add(pwdbtnn);
pwdbtnn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
FindPwd p=new FindPwd();
try {
if(pwdtel.isSelected())
{
p.FindPwdtel();
}
else if(pwdemail.isSelected())
{
p.Findpwdemail();
}
} catch (Exception e2) {
// TODO: handle exception
System.out.println(e2.getMessage());
}
}
});
//tab
tab=new JTabbedPane();
tab.addTab("아이디 찾기",idtype);
tab.addTab("비밀번호 찾기",pwdtype);
add(tab);
setSize(600, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new TabIdPwd();
}
}
| true |
e7b8dffa9d6ae6317515fa9950b181ec1849e9b5 | Java | aburgosd91/MasterNisiraPatos | /src/com/nisira/vista/formularios/reportes/RptConsolidadoEnvio.java | UTF-8 | 2,933 | 2.265625 | 2 | [] | no_license | package com.nisira.vista.formularios.reportes;
import com.nisira.dao.DocumentosEnviadosDao;
import com.nisira.vista.controles.NSRDatePicker;
import com.nisira.vista.controles.NSRTable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JLabel;
import java.awt.Dimension;
@SuppressWarnings("serial")
public class RptConsolidadoEnvio extends AbstractReporte {
private NSRDatePicker dpDesde;
private NSRDatePicker dpHasta;
DocumentosEnviadosDao deDAO = new DocumentosEnviadosDao();
public RptConsolidadoEnvio() {
pnlFiltro.setPreferredSize(new Dimension(10, 35));
setTitle("Consolidado de Envios");
setName("RptConsolidadoEnvio");
dpDesde = new NSRDatePicker();
dpDesde.setBounds(66, 7, 104, 22);
pnlFiltro.add(dpDesde);
dpHasta = new NSRDatePicker();
dpHasta.setBounds(236, 7, 104, 22);
pnlFiltro.add(dpHasta);
JLabel lblDesde = new JLabel("Desde");
lblDesde.setBounds(10, 11, 46, 14);
pnlFiltro.add(lblDesde);
JLabel lblHasta = new JLabel("Hasta");
lblHasta.setBounds(180, 11, 46, 14);
pnlFiltro.add(lblHasta);
dpDesde.setDate(new Date());
dpHasta.setDate(new Date());
}
@Override
public List<Object[]> getData() {
Date desde, hasta;
desde = dpDesde.getDate();
hasta = dpHasta.getDate();
List<Object[]> consolidado = new ArrayList<Object[]>();
try {
List<Object[]> lista = deDAO.getRPTConsolidado(1,desde, hasta);
if (!lista.isEmpty()) {
for (int i = 0; i < lista.size(); i++) {
Object[] row = null;
Object[] cc = lista.get(i);
String idorigen = cc[0].toString().trim();
String idunico = cc[2].toString().trim();
for (Object[] o : consolidado) {
if (o[0].toString().equalsIgnoreCase(idorigen) && o[2].toString().equalsIgnoreCase(idunico)) {
row = o;
break;
}
}
String descripcion = "";
if (cc[9] != null) {
descripcion = cc[9].toString().trim();
}
if (row == null) {
row = new Object[9];
row[0] = cc[0];
row[1] = cc[1];
row[2] = cc[2];
row[3] = cc[3];
row[4] = cc[4];
row[5] = cc[5];
row[6] = cc[6];
row[7] = cc[7];
row[8] = "";
//row[8] = descripcion;
consolidado.add(row);
}
if (!descripcion.isEmpty()) {
row[8] = row[8].toString() + (row[8].toString().isEmpty()? "" : ", ") + descripcion;
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return consolidado;
}
@Override
public String[] getCabeceras() {
return new String[] {"Cód. Origen", "Origen", "Cód Unico", "Documento", "Cód. Cliente", "Razon Social", "Fecha", "Nombre Archivo", "Mensajes"};
}
@Override
public boolean isFiltrosValidos() {
return true;
}
@Override
public NSRTable[] getTablasConfigurar() {
return new NSRTable[] {tblDatos};
}
}
| true |
91e6433bdc55b4d9d22d54460ea831f435a63fff | Java | xiemingjin/SpringBoot | /src/main/java/com/xiemj/service/TestService.java | UTF-8 | 1,409 | 1.953125 | 2 | [] | no_license | package com.xiemj.service;
import com.xiemj.dao.TestDao;
import com.xiemj.dao1.TestDao1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class TestService {
@Autowired
private TestDao dao;
@Autowired
private TestDao1 dao1;
public Map<String,Object> queryList()
{
Map<String,Object> resultMap = new HashMap<>();
Map<String,Object> resultData = new HashMap<>();
List<Map<String,Object>> list = new ArrayList<>();
resultMap.put("resultCode",true);
list = dao.queryList();
resultData.put("rows",list);
resultData.put("total",list.size());
resultMap.put("resultData",resultData);
return resultMap;
}
public Map<String,Object> queryList1()
{
Map<String,Object> resultMap = new HashMap<>();
Map<String,Object> resultData = new HashMap<>();
List<Map<String,Object>> list = new ArrayList<>();
resultMap.put("resultCode",true);
list = dao1.queryList();
resultData.put("rows",list);
resultData.put("total",list.size());
resultMap.put("resultData",resultData);
return resultMap;
}
}
| true |
31a72e8e9e637bc0d6495916e3fc47536cc25ff9 | Java | dengbin19910916/authority-center | /security-demo/src/main/java/com/runoob/app/DataConfig.java | UTF-8 | 662 | 1.867188 | 2 | [] | no_license | package com.runoob.app;
/**
* @author DENGBIN
* @since 2018-3-26
*/
//@Configuration
public class DataConfig {
// @Value("${spring.datasource.url}")
// private String url;
// @Value("${spring.datasource.username}")
// private String username;
// @Value("${spring.datasource.password}")
// private String password;
//
// @Bean
// public DataSource dataSource() {
// DruidDataSource dataSource = new DruidDataSource();
// dataSource.setUrl(url);
// dataSource.setUsername(username);
// dataSource.setPassword(password);
// dataSource.setTestWhileIdle(false);
// return dataSource;
// }
}
| true |
d99e32aaf981602dd85e692adcfa6f478b2b49fe | Java | CarlosAv1/Formulario | /app/src/main/java/com/example/formularioestudiantes/MainActivity.java | UTF-8 | 6,814 | 2.46875 | 2 | [] | no_license | package com.example.formularioestudiantes;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText ET_Matricula, ET_Nombre, ET_APaterno, ET_AMaterno;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ET_Matricula = (EditText) findViewById(R.id.Matricula);
ET_Nombre = (EditText) findViewById(R.id.Nombre);
ET_APaterno = (EditText) findViewById(R.id.APaterno);
ET_AMaterno = (EditText) findViewById(R.id.AMaterno);
}
public void Registrar(View view)
{
Conexion CN = new Conexion(this, "Escuela", null, 1);
SQLiteDatabase cn = CN.getWritableDatabase();
String matricula = ET_Matricula.getText().toString();
String nombre = ET_Nombre.getText().toString();
String materno = ET_AMaterno.getText().toString();
String paterno = ET_APaterno.getText().toString();
if (!matricula.isEmpty() && !nombre.isEmpty() && !materno.isEmpty() && !paterno.isEmpty())
{
ContentValues registro = new ContentValues();
registro.put("Matricula", matricula);
registro.put("Nombre", nombre);
registro.put("APaterno", paterno);
registro.put("AMaterno", materno);
cn.insert("Alumnos", null, registro);
cn.close();
ET_Matricula.setText("");
ET_Nombre.setText("");
ET_APaterno.setText("");
ET_AMaterno.setText("");
Toast.makeText(this, "Registro guardado", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Debes llenar todos los campos", Toast.LENGTH_SHORT).show();
}
}
public void Buscar(View view)
{
Conexion CN = new Conexion(this, "Escuela", null, 1);
SQLiteDatabase cn = CN.getWritableDatabase();
String matricula = ET_Matricula.getText().toString();
if (!matricula.isEmpty())
{
Cursor fila = cn.rawQuery
("Select Nombre, APaterno, AMaterno from Alumnos WHERE Matricula =" + matricula, null);
if (fila.moveToFirst())
{
ET_Nombre.setText(fila.getString(0));
ET_APaterno.setText(fila.getString(1));
ET_AMaterno.setText(fila.getString(2));
cn.close();
}
else
{
Toast.makeText(this, "El alumno no está registrado", Toast.LENGTH_SHORT).show();
cn.close();
}
}
else
{
Toast.makeText(this, "Debes ingresar una matricula", Toast.LENGTH_SHORT).show();
}
}
public void BuscarTodo(View view)
{
String registros = "";
Conexion CN = new Conexion(this, "Escuela", null, 1);
SQLiteDatabase cn = CN.getWritableDatabase();
if (cn != null) {
Cursor cursor = cn.rawQuery("SELECT * FROM Alumnos", null);
if (cursor.moveToFirst())
{
do
{
registros += cursor.getInt(cursor.getColumnIndex("Matricula"));
registros += " ";
registros += cursor.getString(cursor.getColumnIndex("Nombre"));
registros += " ";
registros += cursor.getString(cursor.getColumnIndex("APaterno"));
registros += " ";
registros += cursor.getString(cursor.getColumnIndex("AMaterno"));
registros += "\n";
}
while (cursor.moveToNext());
}
if (registros.equals(""))
{
Toast.makeText(MainActivity.this, "No hay registros", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, registros, Toast.LENGTH_LONG).show();
cn.close();
}
cn.close();
}
}
public void Actualizar(View view)
{
Conexion CN = new Conexion(this, "Escuela", null, 1);
SQLiteDatabase cn = CN.getWritableDatabase();
String matricula = ET_Matricula.getText().toString();
String nombre = ET_Nombre.getText().toString();
String materno = ET_AMaterno.getText().toString();
String paterno = ET_APaterno.getText().toString();
if (!matricula.isEmpty() && !nombre.isEmpty() && !materno.isEmpty() && !paterno.isEmpty())
{
ContentValues registro = new ContentValues();
registro.put("Matricula", matricula);
registro.put("Nombre", nombre);
registro.put("APaterno", paterno);
registro.put("AMaterno", materno);
int Actualizados = cn.update
("Alumnos", registro, "Matricula =" + matricula, null);
cn.close();
if(Actualizados == 1)
{
Toast.makeText(this, "Alumno actualizado", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "El alumno no está registrado", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(this, "Llena todos los campos", Toast.LENGTH_SHORT).show();
}
}
public void Eliminar(View view)
{
Conexion CN = new Conexion(this, "Escuela", null, 1);
SQLiteDatabase cn = CN.getWritableDatabase();
String matricula = ET_Matricula.getText().toString();
if (!matricula.isEmpty())
{
int Eliminados = cn.delete
("Alumnos", "Matricula =" + matricula, null);
cn.close();
ET_Nombre.setText("");
ET_Matricula.setText("");
ET_AMaterno.setText("");
ET_APaterno.setText("");
if(Eliminados == 1)
{
Toast.makeText(this, "Alumno dado de baja", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "El alumno no está registrado", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(this, "Introduce una matricula", Toast.LENGTH_SHORT).show();
}
}
}
| true |
7454a04bb22fd9c09d9e668dbb4ff3f8efa92336 | Java | odavid/rally-plugin | /src/test/java/com/jenkins/plugins/rally/integration/steps/StepStateContainer.java | UTF-8 | 1,400 | 1.617188 | 2 | [
"MIT"
] | permissive | package com.jenkins.plugins.rally.integration.steps;
import com.jenkins.plugins.rally.service.RallyService;
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.response.QueryResponse;
import cucumber.runtime.java.guice.ScenarioScoped;
@ScenarioScoped
public class StepStateContainer {
private QueryResponse preexistingRepositoryObjectQueryResponse;
private RallyService rallyService;
private Exception caughtException;
private RallyRestApi rallyApi;
public QueryResponse getPreexistingRepositoryObjectQueryResponse() {
return preexistingRepositoryObjectQueryResponse;
}
public void setPreexistingRepositoryObjectQueryResponse(QueryResponse preexistingRepositoryObjectQueryResponse) {
this.preexistingRepositoryObjectQueryResponse = preexistingRepositoryObjectQueryResponse;
}
public RallyService getRallyService() {
return rallyService;
}
public void setRallyService(RallyService rallyService) {
this.rallyService = rallyService;
}
public Exception getCaughtException() {
return caughtException;
}
public void setCaughtException(Exception caughtException) {
this.caughtException = caughtException;
}
public RallyRestApi getRallyApi() {
return rallyApi;
}
public void setRallyApi(RallyRestApi rallyApi) {
this.rallyApi = rallyApi;
}
}
| true |
8f3e872c221a5989e12f272f5ee0f200eaff9618 | Java | latdev/netman | /src/com/latdev/netman/Netman.java | UTF-8 | 155 | 1.59375 | 2 | [] | no_license | package com.latdev.netman;
class Netman {
public static void main(String[] args) {
AppMain app = new AppMain();
app.start();
}
} | true |
bfa9c1e42fd171db584f7866d0a1f6c3eb5ea145 | Java | AmerSarajlic/BILD-IT-zadaci | /src/mini4_Battleship_Hangman/Hangman.java | UTF-8 | 5,638 | 3.5 | 4 | [] | no_license | package mini4_Battleship_Hangman;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Hangman {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
startApplication(input);
}
/**
* pokretanje aplikacije
*/
public static void startApplication(Scanner input) throws IOException {
String[] words = null;
try {
words = readWordsFromFile();
} catch (IOException ex) {
System.out.println("File not found.");
}
String userInput = "";
char guess = ' ';
char playAgain = 'Y';
while (playAgain == 'Y') {
String randomWord = "";
try {
randomWord = generateRandomWord(words);
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("File is empthy.");
return;
}
char[] wordArray = fillWithAsterisk(randomWord);
boolean gameOver = false;
int countMissed = 0;
while (!gameOver) {
displayAsteriskWord(wordArray);
userInput = input.next();
while (!isUserInputValid(userInput)) {
System.out.println("\nUnos mora biti jedno slovo. Pokusajte ponovo: ");
userInput = input.next();
}
guess = userInput.charAt(0);
if (isLetterAlreadyInWord(wordArray, guess)) {
System.out.println(guess + " je vec u rijeci.");
countMissed++;
} else if (!isLetterInTheWord(randomWord, guess)) {
System.out.println(guess + " nije u rijeci.");
countMissed++;
} else {
checkUserinput(randomWord, wordArray, guess);
}
if (isEverythingGuessed(wordArray)) {
gameOver = true;
}
}
String str = (countMissed > 1) ? " puta" : " put";
if (countMissed == 0)
System.out.println("Rijec je " + randomWord + ". Pogodili ste bez pogreske.");
else
System.out.println("Rijec je " + randomWord + ". Pogrijesili ste " + countMissed + str);
System.out.println("Da li zelite igrati ponovo, Y / N: ");
playAgain = Character.toUpperCase(input.next().charAt(0));
while (!isCharInputValid(playAgain)) {
System.out.println("\nUnos nije validan, pokusajte ponovo: ");
playAgain = Character.toUpperCase(input.next().charAt(0));
}
}
System.out.println("Kraj igre!");
}
/**
* Validacija unosa
*
* @param guess
* @return
*/
public static boolean isUserInputValid(String guess) {
return (guess.length() == 1 && !Character.isDigit(guess.charAt(0)));
}
/**
* Citanje rijeci iz fajla
*
* @return
* @throws IOException
*/
public static String[] readWordsFromFile() throws IOException {
Path path = Paths.get("hangman.txt");
if (!Files.exists(path)) {
Files.createFile(path);
}
ArrayList<String> list = new ArrayList<>();
try {
BufferedReader reader = Files.newBufferedReader(path);
String line = null;
while ((line = reader.readLine()) != null) {
list.addAll(Arrays.asList(line.split(" ")));
}
reader.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
return (String[]) list.toArray(new String[list.size()]);
}
/**
* Validacija slova u rijeci
*
* @param randomWord
* @param guess
* @return
*/
public static boolean isLetterInTheWord(String randomWord, char guess) {
boolean is = false;
for (int i = 0; i < randomWord.length(); i++) {
if (randomWord.charAt(i) != guess) {
is = false;
} else {
is = true;
break;
}
}
return is;
}
/**
* Validacija da li je slovo vec u rijeci
*
* @param wordArray
* @param guess
* @return
*/
public static boolean isLetterAlreadyInWord(char[] wordArray, char guess) {
for (int i = 0; i < wordArray.length; i++)
if (wordArray[i] == guess)
return true;
return false;
}
/**
* Validacija da li je sve pogodjeno
*
* @param wordArray
* @return
*/
public static boolean isEverythingGuessed(char[] wordArray) {
for (int i = 0; i < wordArray.length; i++)
if (wordArray[i] == '*')
return false;
return true;
}
/**
* Validacija unosa za novu igru
*
* @param playAgain
* @return
*/
public static boolean isCharInputValid(char playAgain) {
return (playAgain == 'Y' || playAgain == 'N');
}
/**
* Validacija unosa korisnika
*
* @param randomWord
* @param wordArray
* @param guess
*/
public static void checkUserinput(String randomWord, char[] wordArray, char guess) {
for (int i = 0; i < randomWord.length(); i++) {
if (randomWord.charAt(i) == guess)
wordArray[i] = guess;
}
}
/**
* Metoda za prikaz zvjezdica u rijeci
*
* @param word
* @param guess
*/
public static void displayAsteriskWord(char[] wordArray) {
System.out.print("(Guess) Enter a letter in word ");
for (int i = 0; i < wordArray.length; i++) {
System.out.print(wordArray[i]);
}
System.out.print(" > ");
}
/**
* Popunjavanje rijeci zvjezdicama
*
* @param randomWord
* @return
*/
public static char[] fillWithAsterisk(String randomWord) {
char[] word = new char[randomWord.length()];
for (int i = 0; i < word.length; i++)
word[i] = '*';
return word;
}
/**
* Random rijec iz niza rijeci
*
* @param words
* @return
*/
public static String generateRandomWord(String[] words) {
return words[(int) (Math.random() * words.length)];
}
}
| true |
59f1c58a86a58eb2ff60000be798c0d5de9eb2f5 | Java | doandroiding/opengl | /sample7/src/main/java/top/lc951/sample7/MainActivity.java | UTF-8 | 730 | 1.960938 | 2 | [] | no_license | package top.lc951.sample7;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sample7_1(View view){
Sample7_1_Activity.actionActivity(this);
}
public void sample7_2(View view){
Sample7_2_Activity.actionActivity(this);
}
public void sample7_3(View view){
Sample7_3_Activity.actionActivity(this);
}
public void sample7_4(View view){
Sample7_4_Activity.actionActivity(this);
}
}
| true |
43f6e47ec64a079149c393e300790832add36e51 | Java | bellmit/mobsters-server | /mobsters-db/src/main/java/com/lvl6/mobsters/db/jooq/generated/tables/daos/StructurePvpBoardConfigDao.java | UTF-8 | 2,177 | 2.265625 | 2 | [] | no_license | /**
* This class is generated by jOOQ
*/
package com.lvl6.mobsters.db.jooq.generated.tables.daos;
import com.lvl6.mobsters.db.jooq.generated.tables.StructurePvpBoardConfig;
import com.lvl6.mobsters.db.jooq.generated.tables.pojos.StructurePvpBoardConfigPojo;
import com.lvl6.mobsters.db.jooq.generated.tables.records.StructurePvpBoardConfigRecord;
import java.util.List;
import javax.annotation.Generated;
import org.jooq.Configuration;
import org.jooq.impl.DAOImpl;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.6.1"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class StructurePvpBoardConfigDao extends DAOImpl<StructurePvpBoardConfigRecord, StructurePvpBoardConfigPojo, Integer> {
/**
* Create a new StructurePvpBoardConfigDao without any configuration
*/
public StructurePvpBoardConfigDao() {
super(StructurePvpBoardConfig.STRUCTURE_PVP_BOARD_CONFIG, StructurePvpBoardConfigPojo.class);
}
/**
* Create a new StructurePvpBoardConfigDao with an attached configuration
*/
public StructurePvpBoardConfigDao(Configuration configuration) {
super(StructurePvpBoardConfig.STRUCTURE_PVP_BOARD_CONFIG, StructurePvpBoardConfigPojo.class, configuration);
}
/**
* {@inheritDoc}
*/
@Override
protected Integer getId(StructurePvpBoardConfigPojo object) {
return object.getStructId();
}
/**
* Fetch records that have <code>struct_id IN (values)</code>
*/
public List<StructurePvpBoardConfigPojo> fetchByStructId(Integer... values) {
return fetch(StructurePvpBoardConfig.STRUCTURE_PVP_BOARD_CONFIG.STRUCT_ID, values);
}
/**
* Fetch a unique record that has <code>struct_id = value</code>
*/
public StructurePvpBoardConfigPojo fetchOneByStructId(Integer value) {
return fetchOne(StructurePvpBoardConfig.STRUCTURE_PVP_BOARD_CONFIG.STRUCT_ID, value);
}
/**
* Fetch records that have <code>power_limit IN (values)</code>
*/
public List<StructurePvpBoardConfigPojo> fetchByPowerLimit(Integer... values) {
return fetch(StructurePvpBoardConfig.STRUCTURE_PVP_BOARD_CONFIG.POWER_LIMIT, values);
}
}
| true |
d9e6415d62b0ffd6ef41f740c866d837a5664adb | Java | cheshi-mantu/qa-guru-files-content-tests | /src/test/java/helpers/Environment.java | UTF-8 | 248 | 1.890625 | 2 | [] | no_license | package helpers;
public class Environment {
public static final String
url = System.getProperty("url", null),
jUserName = System.getProperty("j_user_name", null),
jPassword = System.getProperty("j_password", null);
}
| true |
7d7485294ad6eb78117dc4ee6ab25741668c975c | Java | apereo-tesuto/tesuto | /tesuto-reports-services/tesuto-reports-microservice/src/main/java/org/cccnext/tesuto/reports/web/controller/PoggioReportsEndpoint.java | UTF-8 | 5,655 | 1.734375 | 2 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"EPL-1.0"
] | permissive | /*******************************************************************************
* Copyright © 2019 by California Community Colleges Chancellor's Office
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package org.cccnext.tesuto.reports.web.controller;
import java.io.IOException;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.cccnext.tesuto.reports.service.ResultsSearchParameters;
import org.cccnext.tesuto.springboot.web.BaseController;
import org.cccnext.tesuto.reports.controller.PoggioReportsController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping(value = "/service/v1/pg/reports")
public class PoggioReportsEndpoint extends BaseController {
@Autowired
PoggioReportsController controller;
// Will be shut off for production
@PreAuthorize("hasAuthority('DOWNLOAD_RESPONSE_REPORT')")
@RequestMapping(value = "download/{daysBefore}", method = RequestMethod.GET)
public void doDownloadReportZip(HttpServletRequest request, HttpServletResponse response,
@PathVariable("daysBefore") Integer daysBefore) throws IOException {
controller.doDownloadReportZip(request, response, daysBefore);
}
// Will be shut off for production
@PreAuthorize("hasAuthority('DOWNLOAD_STATIC_REPORT')")
@RequestMapping(value = "download/static/{competencyMapDiscipline}/{identifierRegEx}", method = RequestMethod.GET)
public void doDownloadStaticReportZip(HttpServletRequest request, HttpServletResponse response,
@PathVariable("competencyMapDiscipline") String competencyMapDiscipline,
@PathVariable("identifierRegEx") String identifierRegEx) throws IOException {
controller.doDownloadStaticReportZip(request, response, competencyMapDiscipline, identifierRegEx);
}
@PreAuthorize("hasAuthority('STORE_STATIC_REPORT')")
@RequestMapping(value = "s3/static/{competencyMapDiscipline}/{identifierRegEx}", method = RequestMethod.GET)
public void doStoreStaticReportZip(HttpServletRequest request, HttpServletResponse response,
@PathVariable("competencyMapDiscipline") String competencyMapDiscipline,
@PathVariable("identifierRegEx") String identifierRegEx) throws IOException {
controller.doStoreStaticReportZip(request, response, competencyMapDiscipline, identifierRegEx);
}
@PreAuthorize("hasAuthority('STORE_RESPONSE_REPORT')")
@RequestMapping(value = "s3/{daysBefore}", method = RequestMethod.GET)
public void storeReportToS3(HttpServletRequest request, HttpServletResponse response,
@PathVariable("daysBefore") Integer daysBefore) throws IOException {
controller.storeReportToS3(request, response, daysBefore);
}
@PreAuthorize("hasAuthority('STORE_RESPONSE_REPORT')")
@RequestMapping(value = "s3/{competencyMapDiscipline}/{startDate}/{endDate}/{identifierRegEx}", method = RequestMethod.GET)
public void storeReportToS3DateRange(HttpServletRequest request, HttpServletResponse response,
@PathVariable("competencyMapDiscipline") String competencyMapDiscipline,
@PathVariable("startDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
@PathVariable("endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
@PathVariable("identifierRegEx") String identifierRegEx,
@RequestParam(value = "search", required = false) ResultsSearchParameters.SearchSet searchSet,
@RequestParam(value = "includeUnaffiliatedItems", required = false) Boolean includeUnaffiliatedItems)
throws IOException {
controller.storeReportToS3DateRange(request, response, competencyMapDiscipline, startDate, endDate, identifierRegEx, searchSet, includeUnaffiliatedItems);
}
@PreAuthorize("hasAuthority('DOWNLOAD_RESPONSE_REPORT')")
@RequestMapping(value = "download/{competencyMapDiscipline}/{startDate}/{endDate}/{identifierRegEx}", method = RequestMethod.GET)
public void downloadReportByDateRange(HttpServletRequest request, HttpServletResponse response,
@PathVariable("competencyMapDiscipline") String competencyMapDiscipline,
@PathVariable("identifierRegEx") String identifierRegEx,
@PathVariable("startDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
@PathVariable("endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
@RequestParam(value = "search", required = false) ResultsSearchParameters.SearchSet searchSet,
@RequestParam(value = "includeUnaffiliatedItems", required = false) Boolean includeUnaffiliatedItems)
throws IOException {
controller.downloadReportByDateRange(request, response, competencyMapDiscipline, identifierRegEx, startDate, endDate, searchSet, includeUnaffiliatedItems);
}
}
| true |
bf3e2c2745d51000587fcb42eb42058e0348ba01 | Java | lilihong571/Search | /app/src/main/java/com/llh/searchview/SearchActivity.java | UTF-8 | 4,016 | 2.21875 | 2 | [] | no_license | package com.llh.searchview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.http.VolleyError;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import scut.carson_ho.searchview.ICallBack;
import scut.carson_ho.searchview.SearchView;
import scut.carson_ho.searchview.bCallBack;
public class SearchActivity extends AppCompatActivity {
private SearchView searchView;
private List<BookListData> mList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
initView();
}
private void initView() {
searchView = findViewById(R.id.search_view);
//点击搜索按钮
searchView.setOnClickSearch(new ICallBack() {
@Override //搜索框的内容
public void SearchAciton(String string) {
//Log.d("llhData", "SearchAciton: "+string);
//搜索框内容
if(string.equals("")){
Toast.makeText(SearchActivity.this,"输入框不能为空",Toast.LENGTH_SHORT).show();
}else {
int catalog_id = Integer.parseInt(string);
String url = "http://apis.juhe.cn/goodbook/query?key=0095c828443aeb604ca2511b97202c57&catalog_id="+catalog_id+"&rn=10&rn=10";
RxVolley.get(url, new HttpCallback() {
@Override
public void onSuccess(String t) {
//Log.d("llhData",t);
parsingJson(t);
//页面跳转
Intent intent = new Intent(SearchActivity.this,DisplayActivity.class);
intent.putExtra("listObj",(Serializable)mList);
// Log.d("llhData", "SearchAciton: "+mList);
// Log.d("llhData", "SearchAciton: "+mList.size());
startActivity(intent);
}
@Override
public void onFailure(VolleyError error) {
Log.d("llhData","请求失败");
}
});
}
}
});
//设置返回事件
searchView.setOnClickBack(new bCallBack() {
@Override
public void BackAciton() {
finish();
}
});
}
//解析json
private void parsingJson(String t) {
mList.clear();
//Log.d("llhData", "t: "+t);
try {
JSONObject jsonObject = new JSONObject(t);
JSONObject jsonResult = jsonObject.getJSONObject("result");
JSONArray jsonArray = jsonResult.getJSONArray("data");
for (int i=0; i<jsonArray.length(); i++){
JSONObject json = (JSONObject) jsonArray.get(i);
//获取当前数据
String imageUrl = json.getString("img");
//Log.d("llhData", "imageUrl: "+imageUrl);
String title = json.getString("title");
String catalog = json.getString("catalog");
//创建对象
BookListData data = new BookListData();
data.setTitle(title);
data.setCatalog(catalog);
data.setImageUrl(imageUrl);
mList.add(data);
}
// Log.d("llhData", "SearchAciton: "+mList);
// Log.d("llhData", "SearchAciton: "+mList.size());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
| true |
231aac2f32861bc616df6434df8274fc922f3d91 | Java | xpenxpen/gamecheat | /src/main/java/org/xpen/ubisoft/dunia2/fileformat/xbg/chunk/BoundingSphereChunk.java | UTF-8 | 438 | 2.171875 | 2 | [] | no_license | package org.xpen.ubisoft.dunia2.fileformat.xbg.chunk;
import java.nio.ByteBuffer;
public class BoundingSphereChunk extends AbstractChunk {
public float x;
public float y;
public float z;
public float w;
@Override
public void decode(ByteBuffer buffer) {
this.x = buffer.getFloat();
this.y = buffer.getFloat();
this.z = buffer.getFloat();
this.w = buffer.getFloat();
}
}
| true |
f100f48b6789fea31fc0253d76972a699d4cef7a | Java | Rampage-w/Dtwb | /app/src/main/java/com/sdhmw/dtwb/main/Fragment1.java | UTF-8 | 2,729 | 2.21875 | 2 | [] | no_license | package com.sdhmw.dtwb.main;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.sdhmw.dtwb.utils.TabAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Carson_Ho on 16/5/23.
*/
public class Fragment1 extends Fragment{
private View rootView;
private TabLayout tab;
private ViewPager viewpager;
private TabAdapter adapter;
public static final String[] tabTitle = new String[]{"维保电梯数", "维保及时率", "电梯故障率"};
private Fragment_sy_wbdtsl f1 = new Fragment_sy_wbdtsl();
private Fragment_sy_wbjsl f2 = new Fragment_sy_wbjsl();
private Fragment_sy_dtgzl f3 = new Fragment_sy_dtgzl();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
System.out.println("onCreateView--------->");
rootView = inflater.inflate(R.layout.fragment1,container,false);
// if (null == rootView) {
// }
// ViewGroup parent = (ViewGroup) rootView.getParent();
// if (parent != null) {
// parent.removeView(rootView);
// }
initviews(rootView);
return rootView;
}
private void initviews(View rootView) {
tab = (TabLayout) rootView.findViewById(R.id.tab);
viewpager = (ViewPager) rootView.findViewById(R.id.viewpager);
viewpager.setOffscreenPageLimit(3); //设置缓存页面的个数
List<Fragment> fragments = new ArrayList<>();
System.out.println("fragments:"+fragments);
fragments.add(0,f1);
fragments.add(1,f2);
fragments.add(2,f3);
// for (int i = 0; i < tabTitle.length; i++) {
// fragments.add(TabLayoutFragment.newInstance(i + 1)); //一个fragment多用
// }
// adapter = new TabAdapter(getFragmentManager(), fragments);
adapter = new TabAdapter(getChildFragmentManager(), fragments); //fragment嵌套时需要用到getChildFragmentManager
//给ViewPager设置适配器
viewpager.setAdapter(adapter);
//将TabLayout和ViewPager关联起来。
tab.setupWithViewPager(viewpager);
//设置可以滑动
// tab.setTabMode(TabLayout.MODE_SCROLLABLE);
}
@Override
public void onDestroyView() {
super.onDestroyView();
// System.out.println("f1:"+f1);
// System.out.println("f2:"+f2);
// System.out.println("f3:"+f3);
System.out.println("onDestroyView Fragment1");
}
}
| true |
4b671ee5436d541cd357fbc4d4ebfdb8473c7efd | Java | sashok644/asambeauty | /java/tests/CheckThatOrderConfirmationWasReceived.java | UTF-8 | 488 | 1.890625 | 2 | [] | no_license | package tests;
import org.junit.Test;
import tests.pages.MailPage;
public class CheckThatOrderConfirmationWasReceived extends BaseTest {
MailPage gMailPage = new MailPage();
@Test
public void testConfirmationEmail() {
//To run it with the normal WebDriver you need to comment @Before tag and setUp method in the BaseTest
gMailPage.openInbox();
gMailPage.openConfirmationLetter();
gMailPage.assertThatConfirmationTextIsPresent();
}
}
| true |
b7364c024a1b9ea5d0efd44c113976f4a81d4d64 | Java | Talend/apache-camel | /components/camel-salesforce/camel-salesforce-maven-plugin/src/test/resources/generated/Case_PickListAccentMarkEnum.java | UTF-8 | 1,031 | 2.140625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Salesforce DTO generated by camel-salesforce-maven-plugin
*/
package $packageName;
import javax.annotation.processing.Generated;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
/**
* Salesforce Enumeration DTO for picklist PickListAccentMark
*/
@Generated("org.apache.camel.maven.CamelSalesforceMojo")
public enum Case_PickListAccentMarkEnum {
// Audiencia de Conciliación
AUDIENCIA_DE_CONCILIACIÓN("Audiencia de Conciliaci\u00F3n");
final String value;
private Case_PickListAccentMarkEnum(String value) {
this.value = value;
}
@JsonValue
public String value() {
return this.value;
}
@JsonCreator
public static Case_PickListAccentMarkEnum fromValue(String value) {
for (Case_PickListAccentMarkEnum e : Case_PickListAccentMarkEnum.values()) {
if (e.value.equals(value)) {
return e;
}
}
throw new IllegalArgumentException(value);
}
}
| true |
7bd441c35b023fe769f4cc8b0a1b75ac725da556 | Java | olejardamir/LearningSparkExamplesJAVA | /JavaSparkExamples/src/main/java/BasicAvg/CalculateResult.java | UTF-8 | 1,939 | 3.171875 | 3 | [] | no_license | /*
* Refactored Java Spark examples for easer understanding, to accompany "Learning spark lightning-fast big data analytics - O'Reilly Media"
* @author: Damir Olejar, on March 02 2015.
*/
package BasicAvg;
import java.io.Serializable;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.Function2;
/**
* The purpose of this class is to calculate the result using the Spark's parallel computing
*
*/
public class CalculateResult implements Serializable{
/**
* Gets the result as a AvgCount object
* @param rdd
* @return
*/
public AvgCount getResult(JavaRDD<Integer> rdd){
Function2<AvgCount, Integer, AvgCount> addAndCount = getAddAndCount();
Function2<AvgCount, AvgCount, AvgCount> combine = getCombine();
AvgCount initial = new AvgCount(0, 0);
AvgCount result = rdd.aggregate(initial, addAndCount, combine);
return result;
}
/**
* A Spark Function class meant for incrementing the total_ and a num_
* It accepts the AvgCount and Integer and returns the AvgCount
* @return
*/
private Function2<AvgCount, Integer, AvgCount> getAddAndCount(){
Function2<AvgCount, Integer, AvgCount> addAndCount = new Function2<AvgCount, Integer, AvgCount>() {
public AvgCount call(AvgCount a, Integer x) {
a.incrementTotal(x);
a.incrementNum(1);
return a;
}
};
return addAndCount;
}
/**
* A Spark Function class meant for incrementing the split AvgCounts
* It accepts the two AvgCounts and returns a combined(incremented) AvgCount
* @return
*/
private Function2<AvgCount, AvgCount, AvgCount> getCombine(){
Function2<AvgCount, AvgCount, AvgCount> combine = new Function2<AvgCount, AvgCount, AvgCount>() {
public AvgCount call(AvgCount a, AvgCount b) {
a.incrementTotal(b.getTotal());
a.incrementNum(b.getNum());
return a;
}
};
return combine;
}
}
| true |
9044d24bd38068edffaac4ba2ba280eb3857bb07 | Java | AndideBob/LWJGL-Adapter | /src/main/java/lwjgladapter/logging/Logger.java | UTF-8 | 1,760 | 3.015625 | 3 | [] | no_license | package lwjgladapter.logging;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class Logger {
private static final String PREFIX_ERROR = "ERROR: ";
private static final String PREFIX_GAME = "GAME_: ";
private static final String PREFIX_DEBUG = "DEBUG: ";
private static BufferedWriter fileWriter;
private static boolean logFileInitialized = false;
public static void initializeLogFile(File file) throws FileNotFoundException{
fileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
logFileInitialized = true;
}
public static void free() {
if(logFileInitialized){
logFileInitialized = false;
try{
fileWriter.close();
}
catch(IOException e){
logError(e);
}
}
}
public static void logError(String message){
logInternal(PREFIX_ERROR + message);
}
public static void logError(Exception e){
Throwable throwable = e.getCause();
String text = e.getClass().getName() + ":";
text += (throwable != null ? throwable.toString() : "") + e.getMessage();
for(StackTraceElement element : e.getStackTrace()){
text += "\n" + element.toString();
}
logInternal(PREFIX_ERROR + text);
}
public static void log(String message){
logInternal(PREFIX_GAME + message);
}
public static void logDebug(String message){
logInternal(PREFIX_DEBUG + message);
}
private static void logInternal(String message){
if(logFileInitialized && fileWriter != null){
try {
fileWriter.write(message + "\n");
} catch (IOException e) {
logFileInitialized = false;
logError(e);
}
}
System.out.println(message);
}
}
| true |
945aaf40caf57424410822162829a184d12e0ead | Java | chengyan0079/cy-ruoyi | /ruoyi-admin/ruoyi-activiti/src/main/java/com/cy/ruoyi/admin/activiti/controller/BizNodeController.java | UTF-8 | 3,328 | 2.0625 | 2 | [] | no_license | package com.cy.ruoyi.admin.activiti.controller;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.cy.ruoyi.admin.activiti.VO.ProcessNodeVo;
import com.cy.ruoyi.admin.activiti.consts.ActivitiConstant;
import com.cy.ruoyi.admin.activiti.service.IBizNodeService;
import com.cy.ruoyi.common.core.basic.controller.BaseController;
import com.cy.ruoyi.common.utils.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.bpmn.model.*;
import org.activiti.engine.RepositoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
*/
@RestController
@RequestMapping("node")
@Api(value = "BizNodeController",description = "")
public class BizNodeController extends BaseController
{
private static final Log log = LogFactory.get();
@Autowired
private RepositoryService repositoryService;
@Autowired
private IBizNodeService bizNodeService;
/**
* 获取节点列表
*/
@GetMapping("list/{proDefId}")
@ApiOperation(value = "获取节点列表")
@SentinelResource("remove")
public R list(@PathVariable String proDefId)
{
List<ProcessNodeVo> list = new ArrayList<>();
BpmnModel model = repositoryService.getBpmnModel(proDefId);
if (model != null)
{
Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
for (FlowElement element : flowElements)
{
ProcessNodeVo node = new ProcessNodeVo();
node.setNodeId(element.getId());
node.setName(element.getName());
if (element instanceof StartEvent)
{
// 开始节点
node.setType(ActivitiConstant.NODE_TYPE_START);
}
else if (element instanceof UserTask)
{
// 用户任务
node.setType(ActivitiConstant.NODE_TYPE_TASK);
}
else if (element instanceof EndEvent)
{
// 结束
node.setType(ActivitiConstant.NODE_TYPE_END);
}
else
{
// 排除其他连线或节点
continue;
}
list.add(node);
}
}
return result(list);
}
/**
* 获取节点属性
*/
@GetMapping("get/{nodeId}")
@ApiOperation(value = "获取节点属性")
@SentinelResource("remove")
public R get(@PathVariable String nodeId)
{
ProcessNodeVo node = new ProcessNodeVo();
node.setNodeId(nodeId);
// 设置关联角色,用户,负责人
node = bizNodeService.setAuditors(node);
return R.ok(node);
}
/**
* 修改节点属性
*/
@PostMapping("update")
@ApiOperation(value = "修改节点属性")
@SentinelResource("update")
public R update(@RequestBody ProcessNodeVo node)
{
bizNodeService.updateBizNode(node);
return R.ok();
}
}
| true |
f71b21efff065d8ade225c00d16ef0b7a5b92398 | Java | MoxieRayling/Dissertation-Project-2018 | /SuperShapes/src/controller/Controller.java | UTF-8 | 1,344 | 2.5 | 2 | [] | no_license | package controller;
import model.EditorModel;
import model.GameModel;
import model.Model;
import views.View;
public class Controller implements Constants {
private View v;
private Model m;
public Controller(View v, Model m) {
this.m = m;
this.v = v;
}
public View GetV() {
return v;
}
public void Input(int i) {
m.input(i);
}
public void newGame() {
m = new GameModel(v);
m.eraseSaveData();
}
public void restart() {
m.resetRoom();
}
public void loadGame() {
m = new GameModel(v);
m.loadGame();
}
public void notifyObservers() {
m.notifyAllObservers();
}
public void addToRoom(String[] lines, int x, int y) {
((EditorModel) m).addToRoom(lines, x, y);
}
public void setMode(String mode) {
m.setMode(mode);
}
public void changeRoom(int x, int y) {
m.changeRoom(x + "," + y, false);
}
public void changeRoom(String id) {
if (id != null)
m.changeRoom(id, false);
}
public void runEditor() {
m = new EditorModel(v);
}
public String[] getRooms() {
return ((EditorModel) m).getRoomIds();
}
public void addRoom() {
((EditorModel) m).addRoom();
}
public void export() {
((EditorModel) m).exportRooms();
}
public String[][] getMap(int x, int y) {
return m.getMap(x,y);
}
public int getX() {
return m.getX();
}
public int getY() {
return m.getY();
}
}
| true |
2efd451e73533c856f399e6543c5c07bc65396e6 | Java | liudih/tt-54-spring | /management/management/src/main/java/com/tomtop/management/ebean/homepage/model/FeaturedCategoryBanner.java | UTF-8 | 2,246 | 1.96875 | 2 | [] | no_license | package com.tomtop.management.ebean.homepage.model;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.tomtop.management.ebean.manage.model.ManageModel;
/**
*
* @ClassName: FeaturedCategoryBanner
* @Description: TODO(首页特别类目广告)
* @author Administrator
* @date 2015年12月30日
*
*/
@Entity
@Table(name = "home_featured_category_banner")
public class FeaturedCategoryBanner extends ManageModel {
private static final long serialVersionUID = -1313164964744452388L;
private Integer client_id;
private Integer language_id;
private Integer featured_category_id;
private Integer position_id;
private String url;
private String img_url;
private String title;
private Integer sort;
private Integer is_deleted;
private Integer is_enabled;
public Integer getClient_id() {
return client_id;
}
public void setClient_id(Integer client_id) {
this.client_id = client_id;
}
public Integer getLanguage_id() {
return language_id;
}
public void setLanguage_id(Integer language_id) {
this.language_id = language_id;
}
public Integer getPosition_id() {
return position_id;
}
public void setPosition_id(Integer position_id) {
this.position_id = position_id;
}
public String getImg_url() {
return img_url;
}
public void setImg_url(String img_url) {
this.img_url = img_url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Integer getFeatured_category_id() {
return featured_category_id;
}
public void setFeatured_category_id(Integer featured_category_id) {
this.featured_category_id = featured_category_id;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Integer getIs_deleted() {
return is_deleted;
}
public void setIs_deleted(Integer is_deleted) {
this.is_deleted = is_deleted;
}
public Integer getIs_enabled() {
return is_enabled;
}
public void setIs_enabled(Integer is_enabled) {
this.is_enabled = is_enabled;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
| true |
60254c0c907c22ddf853ae6990f5377ad1c88f26 | Java | insearching/EasyEnglish | /EasyEnglish/src/com/tntu/easyenglish/entity/DictionaryWord.java | UTF-8 | 1,076 | 2.578125 | 3 | [] | no_license | package com.tntu.easyenglish.entity;
public class DictionaryWord {
private int dictionaryId;
private int wordId;
private String word;
private String[] translations;
private String[] contexts;
private String[] images;
private String sound;
private String date;
public DictionaryWord(int dictionaryId, int wordId, String word,
String[] translations, String[] contexts, String[] images,
String sound, String date) {
super();
this.dictionaryId = dictionaryId;
this.wordId = wordId;
this.word = word;
this.translations = translations;
this.contexts = contexts;
this.images = images;
this.sound = sound;
this.date = date;
}
public int getDictionaryId() {
return dictionaryId;
}
public int getWordId() {
return wordId;
}
public String getWord() {
return word;
}
public String[] getTranslations() {
return translations;
}
public String[] getContexts() {
return contexts;
}
public String[] getImages() {
return images;
}
public String getSound() {
return sound;
}
public String getDate() {
return date;
}
}
| true |
9421c5cf071d4155dfc830ea09000b18cda57f18 | Java | afmartin/CMPT305---SteamWeb | /src/cmpt305/lab3/gui/controllers/CompareGraphController.java | UTF-8 | 4,166 | 2.484375 | 2 | [] | no_license | /*
* 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 cmpt305.lab3.gui.controllers;
import cmpt305.lab3.structure.Genre;
import cmpt305.lab3.structure.User;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javafx.collections.ListChangeListener;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
/**
*
* @author MrMagaw <MrMagaw@gmail.com>
*/
public class CompareGraphController implements ListChangeListener<User>{
private final ChartPanel VIEW;
private final List<User> COMPARE = new ArrayList<>();
private List<Genre> genre_list = new ArrayList<>();
private User main;
private final DefaultCategoryDataset BAR_GRAPH, COMPARE_GRAPH;
public void addUser(User u){
if(main == null){
main = u;
addData(u);
return;
}
if(u == null || COMPARE.contains(u) || main.equals(u)){
return;
}
COMPARE.add(u);
addData(u);
}
public void removeUser(User u){
if(u == null || (!main.equals(u) && !COMPARE.contains(u))){
return;
}
if(main.equals(u)){
main = COMPARE.remove(0);
removeData(u, true);
}else{
COMPARE.remove(u);
removeData(u, false);
}
}
private void addData(User u){
if(u == null){
return;
}
genre_list.stream().forEach(g -> BAR_GRAPH.addValue(u.getGameRatio(g), g.name, u.getName()));
setSize();
addCompareData(u);
}
private void addCompareData(User u){
if(u == null){
return;
}
COMPARE_GRAPH.addValue(u.getCompatabilityWith(main).getKey(), "Compatability", u.getName());
}
private void setSize(){
VIEW.setPreferredSize(new Dimension(VIEW.getMaximumDrawWidth(), VIEW.getMaximumDrawHeight()));
VIEW.revalidate();
}
public void updateGenres(List<Object> genres){
genre_list = new ArrayList<>();
genres.stream().forEach((g) -> genre_list.add(Genre.getGenre((String) g)));
BAR_GRAPH.clear();
if(main != null){
addData(main);
}
COMPARE.stream().forEach((u) -> {
addData(u);
});
}
private void removeData(User u, boolean resetCompareData){
final String uName = u.getName();
if(resetCompareData){
System.out.println(main);
COMPARE_GRAPH.clear();
addCompareData(main);
COMPARE.stream().forEach(this::addCompareData);
}else{
COMPARE_GRAPH.removeColumn(uName);
}
BAR_GRAPH.removeColumn(uName);
}
private void clearData(){
BAR_GRAPH.clear();
COMPARE_GRAPH.clear();
COMPARE.clear();
main = null;
}
public void updateUsers(List<User> users){
clearData();
users.stream().forEach((u) -> addUser(u));
}
public JPanel getView(){
return this.VIEW;
}
public CompareGraphController(User main, Set<User> users){
this(main, (User[]) users.toArray(new User[users.size()]));
}
public CompareGraphController(User main, User... users){
this.main = main;
BAR_GRAPH = new DefaultCategoryDataset();
COMPARE_GRAPH = new DefaultCategoryDataset();
JFreeChart t = ChartFactory.createBarChart("SteamWeb", "User", "Time Spent in Each Genre", BAR_GRAPH);
addData(main);
if(users != null && users.length > 0){
Arrays.asList(users).stream().filter(u -> !u.equals(main)).distinct().forEach(u -> {
addData(u);
COMPARE.add(u);
});
}
CategoryPlot plot = t.getCategoryPlot();
plot.setDataset(1, COMPARE_GRAPH);
plot.mapDatasetToRangeAxis(1, 1);
plot.setRangeAxis(1, new NumberAxis("Compatability"));
LineAndShapeRenderer rend = new LineAndShapeRenderer();
rend.setBaseToolTipGenerator((cd, x, y) -> String.format("%s: %f", cd.getColumnKey(y), cd.getValue(x, y)));
rend.setSeriesVisibleInLegend(0, false);
plot.setRenderer(1, rend);
VIEW = new ChartPanel(t);
setSize();
}
@Override
public void onChanged(Change<? extends User> c){
updateUsers(new ArrayList(c.getList()));
}
}
| true |
762e3d817315b3aef09bc8c4d6deef0f0a7c8853 | Java | k1995/mjsipME | /src/org/mjsip/sip/dialog/ExtendedInviteDialog.java | UTF-8 | 13,648 | 1.742188 | 2 | [] | no_license | /*
* Copyright (C) 2012 Luca Veltri - University of Parma - Italy
*
* This file is part of MjSip (http://www.mjsip.org)
*
* MjSip is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MjSip is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MjSip; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author(s):
* Luca Veltri (luca.veltri@unipr.it)
*/
package org.mjsip.sip.dialog;
import java.util.Hashtable;
import org.mjsip.sip.address.NameAddress;
import org.mjsip.sip.authentication.DigestAuthentication;
import org.mjsip.sip.header.AuthorizationHeader;
import org.mjsip.sip.header.CSeqHeader;
import org.mjsip.sip.header.ReplacesHeader;
import org.mjsip.sip.header.RequestLine;
import org.mjsip.sip.header.StatusLine;
import org.mjsip.sip.header.ViaHeader;
import org.mjsip.sip.header.WwwAuthenticateHeader;
import org.mjsip.sip.message.SipMessage;
import org.mjsip.sip.message.SipMessageFactory;
import org.mjsip.sip.message.SipMethods;
import org.mjsip.sip.provider.SipProvider;
import org.mjsip.sip.provider.TransactionServerId;
import org.mjsip.sip.transaction.InviteTransactionClient;
import org.mjsip.sip.transaction.TransactionClient;
import org.mjsip.sip.transaction.TransactionServer;
import org.zoolu.util.LogLevel;
/** Class ExtendedInviteDialog can be used to manage extended invite dialogs.
* <p>
* ExtendedInviteDialog extends the basic InviteDialog in order to:
* <br>- support UAS and proxy authentication,
* <br>- handle REFER/NOTIFY methods,
* <br>- capture all methods within the dialog.
*/
public class ExtendedInviteDialog extends org.mjsip.sip.dialog.InviteDialog {
/** Max number of registration attempts. */
static final int MAX_ATTEMPTS=3;
/** ExtendedInviteDialog listener. */
ExtendedInviteDialogListener ext_listener;
/** Acive transactions. */
Hashtable transactions;
/** User name. */
String username;
/** User name. */
String realm;
/** User's passwd. */
String passwd;
/** Nonce for the next authentication. */
String next_nonce;
/** Qop for the next authentication. */
String qop;
/** Number of authentication attempts. */
int attempts;
/** Creates a new ReliableInviteDialog.
* @param sip_provider the SIP provider
* @param listener invite dialog listener */
public ExtendedInviteDialog(SipProvider sip_provider, ExtendedInviteDialogListener listener) {
super(sip_provider,listener);
init(listener);
}
/** Creates a new ReliableInviteDialog for an already received INVITE request.
* @param sip_provider the SIP provider
* @param invite the already received INVITE message that creates this dialog
* @param listener invite dialog listener */
public ExtendedInviteDialog(SipProvider sip_provider, SipMessage invite, ExtendedInviteDialogListener listener) {
super(sip_provider,listener);
init(listener);
//changeStatus(D_INVITED);
//invite_req=invite;
//update(false,invite_req);
//invite_ts=new InviteTransactionServer(sip_provider,invite_req,this);
onReceivedMessage(sip_provider,invite);
}
/** Creates a new ReliableInviteDialog.
* @param sip_provider the SIP provider
* @param username the user name for server or proxy authentication
* @param realm the realm for server or proxy authentication
* @param passwd for server or proxy authentication
* @param listener invite dialog listener */
public ExtendedInviteDialog(SipProvider sip_provider, String username, String realm, String passwd, ExtendedInviteDialogListener listener) {
super(sip_provider,listener);
init(listener);
this.username=username;
this.realm=realm;
this.passwd=passwd;
}
/** Creates a new ReliableInviteDialog for an already received INVITE request.
* @param sip_provider the SIP provider
* @param invite the already received INVITE message that creates this dialog
* @param username the user name for server or proxy authentication
* @param realm the realm for server or proxy authentication
* @param passwd for server or proxy authentication
* @param listener invite dialog listener */
public ExtendedInviteDialog(SipProvider sip_provider, SipMessage invite, String username, String realm, String passwd, ExtendedInviteDialogListener listener) {
super(sip_provider,listener);
init(listener);
this.username=username;
this.realm=realm;
this.passwd=passwd;
//changeStatus(D_INVITED);
//invite_req=invite;
//update(false,invite_req);
//invite_ts=new InviteTransactionServer(sip_provider,invite_req,this);
onReceivedMessage(sip_provider,invite);
}
/** Inits the ExtendedInviteDialog. */
private void init(ExtendedInviteDialogListener listener) {
this.ext_listener=listener;
this.transactions=new Hashtable();
this.username=null;
this.realm=null;
this.passwd=null;
this.next_nonce=null;
this.qop=null;
this.attempts=0;
}
/** Sends a new request within the dialog */
public void request(SipMessage req) {
TransactionClient t=new TransactionClient(sip_provider,req,this);
transactions.put(t.getTransactionId(),t);
t.request();
}
/** Sends a new REFER within the dialog */
public void refer(NameAddress refer_to) {
refer(refer_to,null);
}
/** Sends a new REFER within the dialog */
public void refer(NameAddress refer_to, NameAddress referred_by) {
SipMessage req=SipMessageFactory.createReferRequest(this,refer_to,referred_by);
request(req);
}
/** Sends a new REFER within the dialog */
public void refer(NameAddress refer_to, NameAddress referred_by, Dialog replaced_dialog) {
SipMessage req=SipMessageFactory.createReferRequest(this,refer_to,referred_by);
req.setReplacesHeader(new ReplacesHeader(replaced_dialog.getCallID(),replaced_dialog.getRemoteTag(),replaced_dialog.getLocalTag()));
request(req);
}
/** Sends a new NOTIFY within the dialog */
public void notify(int code, String reason) {
notify((new StatusLine(code,reason)).toString());
}
/** Sends a new NOTIFY within the dialog */
public void notify(String sipfragment) {
SipMessage req=SipMessageFactory.createNotifyRequest(this,"refer",null,sipfragment);
request(req);
}
/** Responds with <i>resp</i> */
public void respond(SipMessage resp) {
log(LogLevel.DEBUG,"inside x-respond(resp)");
String method=resp.getCSeqHeader().getMethod();
if (method.equals(SipMethods.INVITE) || method.equals(SipMethods.CANCEL) || method.equals(SipMethods.BYE)) {
super.respond(resp);
}
else {
TransactionServerId transaction_id=new TransactionServerId(resp);
log(LogLevel.DEBUG,"transaction-id="+transaction_id);
if (transactions.containsKey(transaction_id)) {
log(LogLevel.TRACE,"responding");
TransactionServer t=(TransactionServer)transactions.get(transaction_id);
t.respondWith(resp);
}
else {
log(LogLevel.DEBUG,"transaction server not found; message discarded");
}
}
}
/** Accepts a REFER request. */
public void acceptRefer(SipMessage req) {
log(LogLevel.DEBUG,"inside acceptRefer(refer)");
SipMessage resp=SipMessageFactory.createResponse(req,202,null,null);
respond(resp);
}
/** Refuses a REFER request. */
public void refuseRefer(SipMessage req) {
log(LogLevel.DEBUG,"inside refuseRefer(refer)");
SipMessage resp=SipMessageFactory.createResponse(req,603,null,null);
respond(resp);
}
/** Inherited from class SipProviderListener. */
public void onReceivedMessage(SipProvider provider, SipMessage msg) {
log(LogLevel.TRACE,"onReceivedMessage(): "+msg.getFirstLine().substring(0,msg.toString().indexOf('\r')));
if (msg.isResponse()) {
super.onReceivedMessage(provider,msg);
}
else
if (msg.isInvite() || msg.isAck() || msg.isCancel() || msg.isBye() || msg.isInfo() || msg.isPrack()) {
super.onReceivedMessage(provider,msg);
}
else {
TransactionServer t=new TransactionServer(sip_provider,msg,this);
transactions.put(t.getTransactionId(),t);
if (msg.isRefer()) {
//SipMessage resp=SipMessageFactory.createResponse(msg,202,null,null,null);
//respond(resp);
NameAddress refer_to=msg.getReferToHeader().getNameAddress();
NameAddress referred_by=null;
if (msg.hasReferredByHeader()) referred_by=msg.getReferredByHeader().getNameAddress();
if (ext_listener!=null) ext_listener.onDlgRefer(this,refer_to,referred_by,msg);
}
else
if (msg.isNotify()) {
SipMessage resp=SipMessageFactory.createResponse(msg,200,null,null);
respond(resp);
String event=msg.getEventHeader().getValue();
String sipfragment=msg.getStringBody();
if (ext_listener!=null) ext_listener.onDlgNotify(this,event,sipfragment,msg);
}
else {
log(LogLevel.DEBUG,"Received alternative request "+msg.getRequestLine().getMethod());
if (ext_listener!=null) ext_listener.onDlgAltRequest(this,msg.getRequestLine().getMethod(),msg.getStringBody(),msg);
}
}
}
/** Inherited from TransactionClientListener.
* When the TransactionClientListener goes into the "Completed" state, receiving a failure response */
public void onTransFailureResponse(TransactionClient tc, SipMessage msg) {
log(LogLevel.TRACE,"inside onTransFailureResponse("+tc.getTransactionId()+",msg)");
String method=tc.getTransactionMethod();
StatusLine status_line=msg.getStatusLine();
int code=status_line.getCode();
String reason=status_line.getReason();
// AUTHENTICATION-BEGIN
if ((code==401 && attempts<MAX_ATTEMPTS && msg.hasWwwAuthenticateHeader() && msg.getWwwAuthenticateHeader().getRealmParam().equalsIgnoreCase(realm))
|| (code==407 && attempts<MAX_ATTEMPTS && msg.hasProxyAuthenticateHeader() && msg.getProxyAuthenticateHeader().getRealmParam().equalsIgnoreCase(realm))) {
attempts++;
SipMessage req=tc.getRequestMessage();
CSeqHeader csh=req.getCSeqHeader().incSequenceNumber();
req.setCSeqHeader(csh);
ViaHeader vh=req.getViaHeader();
req.removeViaHeader();
vh.setBranch(SipProvider.pickBranch());
req.addViaHeader(vh);
WwwAuthenticateHeader wah;
if (code==401) wah=msg.getWwwAuthenticateHeader();
else wah=msg.getProxyAuthenticateHeader();
String qop_options=wah.getQopOptionsParam();
qop=(qop_options!=null)? "auth" : null;
RequestLine rl=req.getRequestLine();
DigestAuthentication digest=new DigestAuthentication(rl.getMethod(),rl.getAddress().toString(),wah,qop,null,0,null,username,passwd);
AuthorizationHeader ah;
if (code==401) ah=digest.getAuthorizationHeader();
else ah=digest.getProxyAuthorizationHeader();
req.setAuthorizationHeader(ah);
transactions.remove(tc.getTransactionId());
if (req.isInvite()) tc=new InviteTransactionClient(sip_provider,req,this);
else tc=new TransactionClient(sip_provider,req,this);
transactions.put(tc.getTransactionId(),tc);
tc.request();
}
else
// AUTHENTICATION-END
if (method.equals(SipMethods.INVITE) || method.equals(SipMethods.CANCEL) || method.equals(SipMethods.BYE)) {
super.onTransFailureResponse(tc,msg);
}
else
if (tc.getTransactionMethod().equals(SipMethods.REFER)) {
transactions.remove(tc.getTransactionId());
if (ext_listener!=null) ext_listener.onDlgReferResponse(this,code,reason,msg);
}
else {
String body=msg.getStringBody();
transactions.remove(tc.getTransactionId());
if (ext_listener!=null) ext_listener.onDlgAltResponse(this,method,code,reason,body,msg);
}
}
/** Inherited from TransactionClientListener.
* When an TransactionClientListener goes into the "Terminated" state, receiving a 2xx response */
public void onTransSuccessResponse(TransactionClient t, SipMessage msg) {
log(LogLevel.TRACE,"inside onTransSuccessResponse("+t.getTransactionId()+",msg)");
attempts=0;
String method=t.getTransactionMethod();
StatusLine status_line=msg.getStatusLine();
int code=status_line.getCode();
String reason=status_line.getReason();
if (method.equals(SipMethods.INVITE) || method.equals(SipMethods.CANCEL) || method.equals(SipMethods.BYE)) {
super.onTransSuccessResponse(t,msg);
}
else
if (t.getTransactionMethod().equals(SipMethods.REFER)) {
transactions.remove(t.getTransactionId());
if (ext_listener!=null) ext_listener.onDlgReferResponse(this,code,reason,msg);
}
else {
String body=msg.getStringBody();
transactions.remove(t.getTransactionId());
if (ext_listener!=null) ext_listener.onDlgAltResponse(this,method,code,reason,body,msg);
}
}
/** Inherited from TransactionClientListener.
* When the TransactionClient goes into the "Terminated" state, caused by transaction timeout */
public void onTransTimeout(TransactionClient t) {
log(LogLevel.TRACE,"inside onTransTimeout("+t.getTransactionId()+",msg)");
String method=t.getTransactionMethod();
if (method.equals(SipMethods.INVITE) || method.equals(SipMethods.BYE)) {
super.onTransTimeout(t);
}
else {
// do something..
transactions.remove(t.getTransactionId());
}
}
//**************************** Logs ****************************/
/** Adds a new string to the default log. */
protected void log(LogLevel level, String str) {
if (logger!=null) logger.log(level,"ExtendedInviteDialog#"+dialog_num+": "+str);
}
}
| true |
06ae2c6a162171da3516d790b9f2ef53207b6267 | Java | chan21252/JavaSE-Learn-Code | /src/work/thread/exercise04/BuyTicketsThread.java | UTF-8 | 861 | 3.796875 | 4 | [] | no_license | package work.thread.exercise04;
/**
* 买票任务类
*/
public class BuyTicketsThread implements Runnable {
private int ticketsNum; //已经买到的票数
public BuyTicketsThread() {
ticketsNum = 0;
}
/**
* 买票
*/
@Override
public void run() {
Thread current = Thread.currentThread(); //获取当前线程
while (true) {
//给当前对象加锁,保证仅有一个线程在修改票数
synchronized (this) {
if (ticketsNum >= 60) break;
System.out.println(current.getName() + " 买到了第 " + (++ticketsNum) + " 张票");
}
//休眠
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| true |
1ea5ca61e4bebfd1381a185283fa6f335288dd47 | Java | Cruizhi/tongcheng_web | /src/main/java/com/crz/entity/Goods.java | UTF-8 | 620 | 1.570313 | 2 | [] | no_license | package com.crz.entity;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
@Data
public class Goods {
@Id
private Integer id;
private String userid;
private String token;
private String type;
private String title;
private String content;
private String price;
private String assortment;
private String linkphone;
private String carriage;
private String comment;
private String city;
private String pic0;
private String pic1;
private String pic2;
private String pic3;
private String pic4;
private String pic5;
private String pic6;
private Boolean status;
}
| true |
a43e464acd7243633531ce544ff6063e78a82209 | Java | jandppw/ppwcode-recovered-from-google-code | /java/vernacular/exception/I/1.n.n/1.0.n/I-1.0.0-2.0/src/java/be/peopleware/exception_I/LocalizedMessageException.java | UTF-8 | 6,405 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | package be.peopleware.exception_I;
import be.peopleware.i18n_I.DefaultResourceBundleLoadStrategy;
import be.peopleware.i18n_I.Properties;
import be.peopleware.i18n_I.ResourceBundleLoadStrategy;
/**
* <p>Support class for localized messages in Exception.</p>
* <p>Since JDK 1.4, throwables have a method that returns a
* localized message. There is however no implemented support for this.
* This class adds such support.</p>
* <p>Localized messages are returned from a resource bundle with
* basename {@link #getLocalizedMessageResourceBundleBasename()}.
* The resource bundle with this base name is recovered using the
* {@link #getLocalizedMessageResourceBundleLoadStrategy() actual resource
* bundle load strategy} (the default is
* {@link DefaultResourceBundleLoadStrategy})
* The localized message that is returned by {@link #getLocalizedMessage()}
* is looked up in this resource bundle using keys
* {@link #getLocalizedMessageKeys()}.
* The keys are tried in order. The first one that gives a result,
* is used.
* If this fails, we try to load the resource bundle with base name
* <code>getClass().getName()</code> with the same load strategy,
* and look up the keys there.
* If this fails, the {@link #getMessage() non-localized message}
* is returned.
* <p>Subclasses provide an actual base name and key.</p>
*
* @invar getLocalizedMessageKeys() != null
* ==> (forall int i; i >= 0
* && i < getLocalizedMessageKeys().length;
* getLocalizedMessageKeys()[i] != null
* && !getLocalizedMessageKeys()[i].equals(""));
*
* @author Jan Dockx
* @author PeopleWare n.v.
*
* @idea (jand): Add functionality to use properties of the exception
* as arguments in the localized message, e.g.,
* <samp>The {origin} had validation errors.</samp>
*/
public abstract class LocalizedMessageException extends Exception {
/*<section name="Meta Information">*/
//------------------------------------------------------------------
/** {@value} */
public static final String CVS_REVISION = "$Revision$"; //$NON-NLS-1$
/** {@value} */
public static final String CVS_DATE = "$Date$"; //$NON-NLS-1$
/** {@value} */
public static final String CVS_STATE = "$State$"; //$NON-NLS-1$
/** {@value} */
public static final String CVS_TAG = "$Name$"; //$NON-NLS-1$
/*</section>*/
/*<construction>*/
//------------------------------------------------------------------
/**
* @param message
* The message that describes the exceptional circumstance.
* @param cause
* The exception that occured, causing this exception to be
* thrown, if that is the case.
*
* @post (message != null) ==> new.getMessage().equals(message);
* @post (message == null) ==> new.getMessage() == null;
* @post new.getCause() == cause;
* @post new.getLocalizedMessageResourceBundleLoadStrategy().getClass()
* == DefaultResourceBundleLoadStrategy.class;
*/
public LocalizedMessageException(final String message,
final Throwable cause) {
super(message, cause);
}
/*</construction>*/
/*<property name="localizedMessageResourceBundleLoadStrategy">*/
//------------------------------------------------------------------
/**
* @basic
*/
public final ResourceBundleLoadStrategy
getLocalizedMessageResourceBundleLoadStrategy() {
return $localizedMessageResourceBundleLoadStrategy;
}
/**
* @param strategy
* The new resource bundle load strategy.
* @post new.getLocalizedMessageResourceBundleLoadStrategy() == strategy;
*/
public final void setLocalizedMessageResourceBundleLoadStrategy(
final ResourceBundleLoadStrategy strategy) {
$localizedMessageResourceBundleLoadStrategy = strategy;
}
ResourceBundleLoadStrategy $localizedMessageResourceBundleLoadStrategy
= new DefaultResourceBundleLoadStrategy();
/*</property>*/
/*<property name="localizedMessageResourceBundleBasename">*/
//------------------------------------------------------------------
/**
* This implementation returns <code>null</code>. As a result, the key is
* looked up in the bundle with base name <code>getClass().getName()</code>.
*
* @basic
*/
public String getLocalizedMessageResourceBundleBasename() {
return null;
}
/*</property>*/
/*<property name="localizedMessageKeys">*/
//------------------------------------------------------------------
/**
* @basic
*/
public abstract String[] getLocalizedMessageKeys();
/*</property>*/
/**
* Return the a label from the
* {@link #getLocalizedMessageResourceBundleBasename()} resource
* bundle with keys {@link #getLocalizedMessageKeys()}, using the
* resoure bundle load strategy
* {@link #getLocalizedMessageResourceBundleLoadStrategy()}.
* The keys are tried in order. The first one that gives a result,
* is used.
* If this fails, we try to load a resource with name
* <code>getClass().getName()</code>, with the same resource
* bundle load strategy and look up the same keys.
* If there is no load strategy, or the bundles could not be found,
* or there is no entry in the bundles with the given keys, the
* non-localized message is returned.
*/
public final String getLocalizedMessage() {
ResourceBundleLoadStrategy strategy
= getLocalizedMessageResourceBundleLoadStrategy();
String[] keys = getLocalizedMessageKeys();
String result;
if ((strategy == null) || (keys == null) || keys.length <= 0) {
result = getMessage();
}
else {
result = Properties.findKeyWithBasename(getLocalizedMessageResourceBundleBasename(),
keys,
getLocalizedMessageResourceBundleLoadStrategy());
if (result == null) {
result = Properties.findKeyWithBasename(getClass().getName(),
keys,
getLocalizedMessageResourceBundleLoadStrategy());
}
if (result == null) {
result = super.getMessage();
}
}
return result;
}
} | true |
2f769fda1ad69495d04f74ee9578946e4f045c46 | Java | songxina/HelloPhone | /src/com/gen/location/ImportDevices.java | GB18030 | 13,353 | 2.1875 | 2 | [] | no_license | package com.gen.location;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import de.fhpotsdam.unfolding.geo.Location;
//ɱSinglePerson
public class ImportDevices {
private static ArrayList<Location> locListWeekdays,locListWeekends;
private static int sizeWeekdays=0,sizeWeekends=0;
private static Map<String,String> map = new HashMap<String,String>();
private static Map<Location,Integer> mapNumberWeekends = new HashMap<Location,Integer>();//¼ÿֵ
private static Map<Location,Integer> mapNumberWeekdays = new HashMap<Location,Integer>();//¼ÿֵ
public static void init(){
locListWeekdays = new ArrayList<Location>();locListWeekends = new ArrayList<Location>();
sizeWeekdays=0;sizeWeekends=0;
map = new HashMap<String,String>();
mapNumberWeekends = new HashMap<Location,Integer>();
mapNumberWeekdays = new HashMap<Location,Integer>();
}
//вֵַͬĴ
public static void calMapNumber(ArrayList<PhoneRecordDAO> all,Map<Location,Integer> m){
ArrayList<Location> list = tranDaoToLoc(all);
for(Location loc:list){
if(m.containsKey(loc)){
int number = m.get(loc);
number++;
// m.remove(loc);
m.put(loc, number);
}
else{
m.put(loc, 1);
}
}
}
//ȡ豸
public static ArrayList<String> getDevices() {
ArrayList<String> devices = new ArrayList<String>();
BufferedReader br = null;
try {
File file = new File("E:/aSmartCity//WuxiSmartCity/devices.txt");
br = new BufferedReader(new InputStreamReader(new FileInputStream(
file), "utf-8"));
String line = "";
int count =0;
while ((line = br.readLine()) != null) {
if (line.length() < 8)
continue;
devices.add(line);
count++;
}
System.out.println(count);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
br = null;
} catch (IOException e) {
e.printStackTrace();
}}}
return devices;
}
//õѴݿе
public static ArrayList<String> getDays(){
ArrayList<String> days = new ArrayList<String>();
BufferedReader br = null;
try {
File file = new File("./data/data/days.txt");
br = new BufferedReader(new InputStreamReader(new FileInputStream(
file), "utf-8"));
String line = "";
while ((line = br.readLine()) != null) {
if (line.length() < 8)
continue;
days.add(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
br = null;
} catch (IOException e) {
e.printStackTrace();
}}}
// System.out.println(days);
return days;
}
public static void getCertainHour(int hour,String device) throws ParseException{
init();
getTransMap() ;
//99885120582072638 //סأ
//99436363125020112
//99694278034672874
//99702514941785022
//99911000285858952
//99911080816054974
//99694274696390598
//99694255103806125 ҹ
// String device = "99694255103806125";
Gson gson = new Gson();
ArrayList<PhoneRecordDAO> rebyhourWeekdays = new ArrayList<PhoneRecordDAO>();
ArrayList<PhoneRecordDAO> rebyhourWeekends = new ArrayList<PhoneRecordDAO>();
// int datehour;
ArrayList<String> days = getDays();
String uriAPI,formatHour="",formatHourPlus="";
if(hour<9){
formatHour ="0"+hour;
formatHourPlus = "0"+(hour+1);
}
else if(hour==9)
{
formatHour ="0"+hour;
formatHourPlus = "10";
}
else{
formatHour = hour+"";
formatHourPlus = ""+(hour+1);
}
for(String d :days){
uriAPI ="http://219.224.169.45:8080/GsmService/phonewuxi.action?type=findById&password=mima&deviceId="+device+"&startTime="+d+formatHour+"0000&&endTime="+d+formatHourPlus+"0000";
String jsonString = HttpUtil.sendPost(uriAPI, "");
CellForm cell = gson.fromJson(jsonString, CellForm.class);
if(isWeekends(d))
rebyhourWeekends.addAll(cell.getPList());
else
rebyhourWeekdays.addAll(cell.getPList());
}
calMapNumber(rebyhourWeekdays,mapNumberWeekdays);calMapNumber(rebyhourWeekends,mapNumberWeekends);
sizeWeekdays = rebyhourWeekdays.size();
sizeWeekends = rebyhourWeekends.size();
System.out.println(hour+":"+sizeWeekends+"/"+sizeWeekdays);
HashSet<PhoneRecordDAO> setWeekdays = new HashSet<PhoneRecordDAO>();
HashSet<PhoneRecordDAO> setWeekends = new HashSet<PhoneRecordDAO>();
setWeekdays.addAll(rebyhourWeekdays);setWeekends.addAll(rebyhourWeekends);
ArrayList<PhoneRecordDAO> weekday = new ArrayList<PhoneRecordDAO>();weekday.addAll(setWeekdays);
ArrayList<PhoneRecordDAO> weekend = new ArrayList<PhoneRecordDAO>();weekend.addAll(setWeekends);
locListWeekdays = tranDaoToLoc(weekday);
locListWeekends = tranDaoToLoc(weekend);
}
public static Map<Location, Integer> getMapNumberWeekends() {
return mapNumberWeekends;
}
public static Map<Location, Integer> getMapNumberWeekdays() {
return mapNumberWeekdays;
}
public static int getWeekdaysSize(){
return sizeWeekdays;
}
public static int getWeekendsSize(){
return sizeWeekends;
}
public static ArrayList<Location> getLocListWeekdays() {
return locListWeekdays;
}
public static ArrayList<Location> getLocListWeekends() {
return locListWeekends;
}
//õPhoneRecordDAOݱΪlocation
public static ArrayList<Location> tranDaoToLoc(ArrayList<PhoneRecordDAO> pdao){
ArrayList<Location> result = new ArrayList<Location>();
ArrayList<String> list = new ArrayList<String>();
for(PhoneRecordDAO p : pdao)
list.add(p.getAreaID()+'_'+p.getCellID());
Gson gson = new Gson();
CellForm c = null ;
ArrayList<String> re = new ArrayList<String>();
for(String s :list)
{
if(s.equals("0_0"))
continue;
String lc =null;
lc= map.get(s);
if(lc!=null)
re.add(lc);
// else{
// String[] temp = s.split("_");
// String uri ="http://219.224.169.45:8080/GsmService/cellwuxi.action?type=addressFLL&password=mima&lac="+temp[0]+"&cell="+temp[1];
// String string = HttpUtil.sendPost(uri, "");
// c = gson.fromJson(string, CellForm.class);
// lc = c.getList().get(0);
// if(lc.equals("0_0"))
// System.out.println("Dont exit:"+s);
// else
// re.add(lc);
// }
}
result = transLocations(re);
return result;
}
//stringתlocation
public static ArrayList<Location> transLocations(ArrayList<String> list){
ArrayList<Location> loc = new ArrayList<Location>();
String temp[];
for(String lc :list){
temp = lc.split("_");
Location a = new Location(Float.parseFloat(temp[0]),Float.parseFloat(temp[1]));
loc.add(a);
}
return loc;
}
public static void exportRes(List<PhoneRecordDAO> result,String name){
File file = new File("E:/aSmartCity//WuxiSmartCity/켣/"+name+".txt");
try {
FileWriter fileWriter = new FileWriter(file);
for(PhoneRecordDAO s:result)
fileWriter.write(s.getAreaID()+'_'+s.getCellID()+"\n");
System.out.println("DONE!");
fileWriter.close(); // ر
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void exportResString(List<String> result,String name){
File file = new File("E:/aSmartCity//WuxiSmartCity/켣/"+name+".txt");
try {
FileWriter fileWriter = new FileWriter(file);
for(String s:result){
String[] temp = s.split("_");
fileWriter.write(temp[0]+'_'+temp[1]+"\n");
}
System.out.println("DONE!");
fileWriter.close(); // ر
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//ȡļȡmapԱ㽫stationIDճ
public static void getTransMap() {
File file = new File("./data/data/base_station_GPS.txt");
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(file), "utf-8")
);
try {
String line = br.readLine();
String[] rs = null;
while((line = br.readLine()) != null) {
rs = line.split("\\|");
map.put(rs[0] +"_"+ rs[1], rs[4]+"_"+rs[5]);
}
// System.out.println(map);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException | FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//жǷĩ
public static boolean isWeekends(String day) throws ParseException{
DateFormat format1 = new SimpleDateFormat("yyyyMMdd");
Date bdate = format1.parse(day);
Calendar cal = Calendar.getInstance();
cal.setTime(bdate);
if(cal.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY||cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY)
return true;
else
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// getDevices();
// getTraceAllDay();
// getTraceNight();
getDays();
}
/* public static ArrayList<Location> getTraceAllDay(){
getTransMap() ;
String device = "99523444613519162";
String uriAPI ="http://219.224.169.45:8080/GsmService/phonewuxi.action?type=findById&password=mima&deviceId="+device+"&startTime=20131111000000&&endTime=20131119000000";
String jsonString = HttpUtil.sendPost(uriAPI, "");
// System.out.println(jsonString);
Gson gson = new Gson();
CellForm cell = gson.fromJson(jsonString, CellForm.class);
ArrayList<String> set = new ArrayList<String>();
for(PhoneRecordDAO p : cell.getPList())
set.add(p.getAreaID()+'_'+p.getCellID());
System.out.println(set.size());
CellForm c = null ;
ArrayList<String> re = new ArrayList<String>();
int count=0;
for(String s :set)
{
count++;
if(count%1000==0)
System.out.println(count);
String lc =null;
lc= map.get(s);
if(lc!=null)
re.add(lc);
else{
String[] temp = s.split("_");
String uri ="http://219.224.169.45:8080/GsmService/cellwuxi.action?type=addressFLL&password=mima&lac="+temp[0]+"&cell="+temp[1];
String string = HttpUtil.sendPost(uri, "");
c = gson.fromJson(string, CellForm.class);
// System.out.println(c.getLacCell().get(0));
lc = c.getList().get(0);
if(lc.equals("0_0"))
System.out.println("Dont exit:"+s);
else
re.add(lc);
}
}
// exportRes(cell.getList(),"99357603871889250");
// exportResString(re,device);
locList = transLocations(re);
System.out.println("INPUT DONE!");
return locList;
}
*/
/*
public static ArrayList<Location> getTraceNight(){
getTransMap() ;
String device = "99357630326031986";
Gson gson = new Gson();
ArrayList<PhoneRecordDAO> rebynight = new ArrayList<PhoneRecordDAO>();
for(int i=1;i<=8;i++){
String uriAPI ="http://219.224.169.45:8080/GsmService/phonewuxi.action?type=findById&password=mima&deviceId="+device+"&startTime=2013111"+i+"190000&&endTime=2013111"+(i+1)+"080000";
// System.out.println(uriAPI);
String jsonString = HttpUtil.sendPost(uriAPI, "");
// System.out.println(jsonString);
CellForm cell = gson.fromJson(jsonString, CellForm.class);
rebynight.addAll(cell.getPList());
}
// HashSet<String> set = new HashSet<String>();
ArrayList<String> set = new ArrayList<String>();
for(PhoneRecordDAO p : rebynight)
set.add(p.getAreaID()+'_'+p.getCellID());
System.out.println(set.size());
CellForm c = null ;
ArrayList<String> re = new ArrayList<String>();
int count=0;
for(String s :set)
{
count++;
if(count%1000==0)
System.out.println(count);
String lc =null;
lc= map.get(s);
if(lc!=null)
re.add(lc);
else{
String[] temp = s.split("_");
// System.out.println(s);
String uri ="http://219.224.169.45:8080/GsmService/cellwuxi.action?type=addressFLL&password=mima&lac="+temp[0]+"&cell="+temp[1];
String string = HttpUtil.sendPost(uri, "");
c = gson.fromJson(string, CellForm.class);
// System.out.println(c.getLacCell().get(0));
lc = c.getList().get(0);
if(lc.equals("0_0"))
System.out.println("Dont exit:"+s);
else
re.add(lc);
}
}
// exportResString(re,device+"N");
locList = transLocations(re);
System.out.println("INPUT DONE!");
return locList;
}
*/
}
| true |
c283c631a6a8e99899686ea86220114a025fc96e | Java | cam-parra/WorkCubed | /app/src/main/java/com/github/workcubed/TaskView.java | UTF-8 | 3,148 | 2.140625 | 2 | [] | no_license | package com.github.workcubed;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
public class TaskView extends AppCompatActivity {
Dbhelper db;
String task_name;
String desc;
Integer status;
Integer hours_estimated;
Integer hours_actual;
Button update;
String project_name;
Integer id;
public final static String EXTRA_MESSAGE = "project name";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_view);
db = new Dbhelper(this);
Intent intent = getIntent();
task_name = intent.getStringExtra(ProjectView.TASK_MESSAGE);
desc = db.getTaskDescByName(task_name);
status = db.getTaskStatusByName(task_name);
hours_estimated = db.getTaskHoursEstimatedByName(task_name);
hours_actual = db.getTaskHoursActualByName(task_name);
project_name = db.getTaskColumnProjectname(task_name);
id = db.getTaskIDByName(task_name);
System.out.println(task_name + " " + desc + " " + status + " " + hours_estimated + " " + hours_actual);
final TextView name_text = (TextView) findViewById(R.id.task_name_text);
name_text.setText(task_name);
final TextView desc_text = (TextView) findViewById(R.id.task_desc_text);
desc_text.setText(desc);
final EditText hours_est = (EditText) findViewById(R.id.est_hours);
hours_est.setText(Integer.toString(hours_estimated));
final EditText hours_act = (EditText) findViewById(R.id.act_hours);
hours_act.setText(Integer.toString(hours_actual));
final CheckBox status_box = (CheckBox) findViewById(R.id.completed_box);
if(status < 1) {
status_box.setChecked(false);
}
else {
status_box.setChecked(true);
}
update = (Button) findViewById(R.id.update_task);
update.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String userName = name_text.getText().toString();
String userDesc = desc_text.getText().toString();
String userEstString = hours_est.getText().toString();
Float userEst= Float.parseFloat(userEstString);
String userActString = hours_act.getText().toString();
Float userAct = Float.parseFloat(userActString);
if (status_box.isChecked())
status = 1;
else
status = 0;
db.updateTask(id, userName, userDesc, userAct, userEst, status, project_name);
projectView(v);
}
});
}
public void projectView (View view) {
Intent intent = new Intent(this, ProjectView.class);
intent.putExtra(EXTRA_MESSAGE, project_name);
startActivity(intent);
}
}
| true |
c473a91a35830ab8dc75d6ee76f27a930bc07965 | Java | abagnari/Lastminute | /src/main/java/org/lastminute/dto/ItemDto.java | UTF-8 | 580 | 2.375 | 2 | [] | no_license | package org.lastminute.dto;
import java.math.BigDecimal;
public class ItemDto
{
private Integer quantity;
private String name;
private BigDecimal priceVatAdded;
public Integer getQuantity()
{
return quantity;
}
public void setQuantity(Integer quantity)
{
this.quantity = quantity;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public BigDecimal getPriceVatAdded()
{
return priceVatAdded;
}
public void setPriceVatAdded(BigDecimal priceVatAdded)
{
this.priceVatAdded = priceVatAdded;
}
}
| true |