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
8b5f35ba75209107dea5b517c1a71a72a8c3fbb9
Java
wuyxhero/dlna-android
/tcl_libiqiyidlna/src/org/cybergarage/upnp/ServiceInterface.java
UTF-8
169
1.804688
2
[]
no_license
package org.cybergarage.upnp; public interface ServiceInterface { /* * 初始化服务,可以通过载入描述文件的形式 */ public void initService(); }
true
dbcea638a7ac5668bc754703646369823afb8958
Java
Arjun491/FlappyBird-2
/core/src/com/naveendidhra/game/sprites/Bird.java
UTF-8
2,121
3
3
[]
no_license
package com.naveendidhra.game.sprites; //needs to know the position of the bird in our game //needs to know the texture to be drawn to the screen //needs to know the velocity and the direction of the bird (up/down/left/right) import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector3; public class Bird { private static final int GRAVITY = -15; // for bird private static final int MOVEMENT =100; private Vector3 position; //holds the x and y axis (because its only a 2-D game) private Vector3 velocity; private Rectangle bounds; private Animation birdAnimation; private Texture texture; private Sound flap; private Texture bird; public Bird(int x,int y){ // for the starting positions position = new Vector3(x,y,0); velocity = new Vector3(0,0,0); // because we are not moving the bird texture = new Texture("birdanimation.png"); birdAnimation = new Animation(new TextureRegion(texture),3,0.5f); bounds = new Rectangle(x,y,texture.getWidth() / 3,texture.getHeight()); flap = Gdx.audio.newSound(Gdx.files.internal("sfx_wing.ogg")); } public void update(float dt){ if (dt >0) { birdAnimation.update(dt); if (position.y > 0) velocity.add(0, GRAVITY, 0); velocity.scl(dt); position.add(MOVEMENT * dt, velocity.y, 0); if (position.y < 0) position.y = 0; velocity.scl(1 / dt); bounds.setPosition(position.x, position.y); } } public Vector3 getPosition() { return position; } public TextureRegion getTexture() { return birdAnimation.getFrame(); } public void jump(){ velocity.y=250; flap.play(); } public Rectangle getBounds(){ return bounds; } public void dispose(){ texture.dispose(); flap.dispose(); } }
true
3f1110fb023a9a1d7c13059add7e13260503fb84
Java
jonghough/ArtisteX
/app/src/main/java/jgh/artistex/engine/visitors/ModeSelectVisitor.java
UTF-8
1,886
3.015625
3
[ "BSD-3-Clause" ]
permissive
package jgh.artistex.engine.visitors; import jgh.artistex.engine.ILayer; import jgh.artistex.engine.Layers.Bitmaps.BaseBitmapLayer; import jgh.artistex.engine.Layers.Bitmaps.TextLayer; import jgh.artistex.engine.Layers.Pens.BasePen; /** * Visitor class for selecting mode of a layer. Used for classes which extend * either <code>BasePen</code> or <code>BasePolygon</code>, mainly. */ public class ModeSelectVisitor implements ILayerVisitor { /** * */ public enum Mode { DRAW, VERTEX, BEZIER, ROTATE, TRANSLATE, SCALE } /** * */ private Mode mMode; /** * */ public ModeSelectVisitor() { } /** * Sets the Mode for <code>ILayer</code> actions. * * @param mode */ public void setMode(Mode mode) { mMode = mode; } @Override public void visit(ILayer layer) { layer.accept(this); } @Override public void visitPen(BasePen basePen) { if (basePen == null) return; switch (mMode) { case DRAW: basePen.setState(BasePen.State.DRAWING); break; case BEZIER: basePen.setState(BasePen.State.BEZIER); break; case VERTEX: basePen.setState(BasePen.State.VERTEX); break; case ROTATE: basePen.setState(BasePen.State.ROTATING); break; case SCALE: basePen.setState(BasePen.State.SCALING); break; case TRANSLATE: basePen.setState(BasePen.State.MOVING); break; default: break; } } @Override public void visitBitmap(BaseBitmapLayer layer) { } @Override public void visitText(TextLayer layer) { } }
true
a5827464406402f0eda0d1c5dcb0d79b5bc73970
Java
Miguel-Fontes/task-flow
/task-flow-grpc/src/main/java/br/com/miguelfontes/taskflow/tasks/grpc/TasksServiceGrpcImpl.java
UTF-8
8,722
2.296875
2
[ "MIT" ]
permissive
package br.com.miguelfontes.taskflow.tasks.grpc; import br.com.miguelfontes.taskflow.ports.tasks.ConcludeTaskRequest; import br.com.miguelfontes.taskflow.ports.tasks.ConcludeTaskResponse; import br.com.miguelfontes.taskflow.ports.tasks.CreateTaskRequest; import br.com.miguelfontes.taskflow.ports.tasks.CreateTaskResponse; import br.com.miguelfontes.taskflow.ports.tasks.DeleteTaskRequest; import br.com.miguelfontes.taskflow.ports.tasks.SearchTasksRequest; import br.com.miguelfontes.taskflow.ports.tasks.SearchTasksResponse; import br.com.miguelfontes.taskflow.ports.tasks.StartTaskRequest; import br.com.miguelfontes.taskflow.ports.tasks.StartTaskResponse; import br.com.miguelfontes.taskflow.ports.tasks.TaskDTO; import br.com.miguelfontes.taskflow.ports.tasks.TaskNotFoundException; import br.com.miguelfontes.taskflow.ports.tasks.TasksAPI; import br.com.miguelfontes.taskflow.ports.tasks.UpdateTaskRequest; import br.com.miguelfontes.taskflow.ports.tasks.UpdateTaskResponse; import io.grpc.Status; import io.grpc.stub.StreamObserver; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Collection; import java.util.List; import java.util.UUID; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; /** * Implements the gRPC Tasks service, exposing the core Task Domain features the external clients * * @author Miguel Fontes */ @Service public class TasksServiceGrpcImpl extends TasksServiceGrpc.TasksServiceImplBase { private final TasksAPI api; @Autowired public TasksServiceGrpcImpl(TasksAPI api) { this.api = api; } static TasksServiceGrpc.TasksServiceImplBase instance(TasksAPI api) { return new TasksServiceGrpcImpl(api); } @Override public void create(TasksServiceOuterClass.CreateTaskRequest request, StreamObserver<TasksServiceOuterClass.CreateTaskResponse> responseObserver) { var response = buildCreateTaskRequest() .andThen(api::execute) .andThen(CreateTaskResponse::getTask) .andThen(this::toOuterTask) .andThen(this::buildTaskResponse) .apply(request); responseObserver.onNext(response); responseObserver.onCompleted(); } private Function<TasksServiceOuterClass.CreateTaskRequest, CreateTaskRequest> buildCreateTaskRequest() { return request -> CreateTaskRequest.of(UUID.fromString(request.getUserId()), request.getTitle()); } private TasksServiceOuterClass.Task toOuterTask(TaskDTO task) { return TasksServiceOuterClass.Task.newBuilder() .setAuthor(task.getAuthor().toString()) .setId(task.getId().toString()) .setTitle(task.getTitle()) .setDescription(task.getDescription()) .setCreatedAt(task.getCreatedAt().toString()) .setUpdatedAt(task.getUpdatedAt().toString()) .setStatus(task.getStatus()) .build(); } private TasksServiceOuterClass.CreateTaskResponse buildTaskResponse(TasksServiceOuterClass.Task grpcTask) { return TasksServiceOuterClass.CreateTaskResponse.newBuilder() .setTask(grpcTask) .build(); } @Override public void search(TasksServiceOuterClass.SearchTasksRequest request, StreamObserver<TasksServiceOuterClass.SearchTasksResponse> responseObserver) { var response = Stream.of(request) .map(this::buildSearchTaskRequest) .map(api::execute) .map(SearchTasksResponse::getTasks) .flatMap(Collection::stream) .map(this::toOuterTask) .collect(Collectors.collectingAndThen( toList(), this::buildSearchTaskResponse )); responseObserver.onNext(response); responseObserver.onCompleted(); } private SearchTasksRequest buildSearchTaskRequest(TasksServiceOuterClass.SearchTasksRequest request) { return SearchTasksRequest.builder() .title(request.getTitle()) .build(); } private TasksServiceOuterClass.SearchTasksResponse buildSearchTaskResponse(List<TasksServiceOuterClass.Task> foundTasks) { return TasksServiceOuterClass.SearchTasksResponse.newBuilder() .addAllTasks(foundTasks) .build(); } @Override public void delete(TasksServiceOuterClass.DeleteTaskRequest request, StreamObserver<TasksServiceOuterClass.DeleteTaskResponse> responseObserver) { Stream.of(request) .map(TasksServiceOuterClass.DeleteTaskRequest::getUuid) .map(UUID::fromString) .map(DeleteTaskRequest::of) .forEach(api::execute); responseObserver.onNext(TasksServiceOuterClass.DeleteTaskResponse.newBuilder().build()); responseObserver.onCompleted(); } @Override public void update(TasksServiceOuterClass.UpdateTaskRequest request, StreamObserver<TasksServiceOuterClass.UpdateTaskResponse> responseObserver) { var response = buildUpdateTaskRequest() .andThen(api::execute) .andThen(UpdateTaskResponse::getTask) .andThen(this::toOuterTask) .andThen(this::buildUpdateTaskResponse) .apply(request); responseObserver.onNext(response); responseObserver.onCompleted(); } private Function<TasksServiceOuterClass.UpdateTaskRequest, UpdateTaskRequest> buildUpdateTaskRequest() { return request -> UpdateTaskRequest.of( UUID.fromString(request.getId()), request.getTitle(), request.getDescription() ); } private TasksServiceOuterClass.UpdateTaskResponse buildUpdateTaskResponse(TasksServiceOuterClass.Task task) { return TasksServiceOuterClass.UpdateTaskResponse.newBuilder() .setTask(task) .build(); } @Override public void conclude(TasksServiceOuterClass.ConcludeTaskRequest request, StreamObserver<TasksServiceOuterClass.ConcludeTaskResponse> responseObserver) { try { final var response = buildConcludeTaskRequest() .andThen(api::execute) .andThen(ConcludeTaskResponse::getTask) .andThen(this::toOuterTask) .andThen(this::buildConcludeTaskResponse) .apply(request); responseObserver.onNext(response); responseObserver.onCompleted(); } catch (TaskNotFoundException e) { responseObserver.onError(Status.NOT_FOUND .withDescription(e.getMessage()) .withCause(e) .asRuntimeException()); } } private Function<TasksServiceOuterClass.ConcludeTaskRequest, ConcludeTaskRequest> buildConcludeTaskRequest() { return request -> ConcludeTaskRequest.of(UUID.fromString(request.getId())); } private TasksServiceOuterClass.ConcludeTaskResponse buildConcludeTaskResponse(TasksServiceOuterClass.Task task) { return TasksServiceOuterClass.ConcludeTaskResponse.newBuilder() .setTask(task) .build(); } @Override public void start(TasksServiceOuterClass.StartTaskRequest request, StreamObserver<TasksServiceOuterClass.StartTaskResponse> responseObserver) { try { var response = buildStartTaskRequest() .andThen(api::execute) .andThen(StartTaskResponse::getTask) .andThen(this::toOuterTask) .andThen(this::buildStartTaskResponse) .apply(request); responseObserver.onNext(response); responseObserver.onCompleted(); } catch (TaskNotFoundException e) { responseObserver.onError(Status.NOT_FOUND .withDescription(e.getMessage()) .withCause(e) .asRuntimeException()); } } private Function<TasksServiceOuterClass.StartTaskRequest, StartTaskRequest> buildStartTaskRequest() { return request -> StartTaskRequest.of(UUID.fromString(request.getId())); } private TasksServiceOuterClass.StartTaskResponse buildStartTaskResponse(TasksServiceOuterClass.Task task) { return TasksServiceOuterClass.StartTaskResponse.newBuilder() .setTask(task) .build(); } }
true
6a110693f92e4869fc8444df9ec996c9cd0ace09
Java
boba-alex/final_project
/src/main/java/org/techforumist/jwt/domain/user/AchievementController.java
UTF-8
1,070
2.140625
2
[]
no_license
package org.techforumist.jwt.domain.user; import org.springframework.stereotype.Controller; import org.techforumist.jwt.repository.AppUserRepository; import java.util.List; public class AchievementController { public void chekAchivements(AppUserRepository appUserRepository, String userName){ System.out.println("userName " + userName); AppUser appUser = appUserRepository.findOne(1L); System.out.println("userName " + appUser.getUsername()); // if (appUser.getInstruction().size() > 0 ){ // Achievement achievement = new Achievement(); // achievement.setUsername(userName); // achievement.setName("Bronze instruction creator"); // achievement.setDescription("For make 0 instruction !!!"); // achievement.setImageLink("http://res.cloudinary.com/demo/image/upload/pg_3/strawberries.png"); // appUser.getAchievements().add(achievement); // appUserRepository.save(appUser); // // System.out.println("chekAchivements.save"); // } } }
true
bb4dc331240ec049b01ce24292a52e21d513113d
Java
ricriospino/ApiFutbol
/src/main/java/com/api/rest/controller/TituloRestController.java
UTF-8
3,426
2.28125
2
[]
no_license
package com.api.rest.controller; import java.util.List; import javax.validation.Valid; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.api.model.entity.TituloModel; import com.api.service.impl.TituloServiceImpl; @RestController @RequestMapping("/apiFutbol") public class TituloRestController { private static final Logger log = LogManager.getLogger(TituloRestController.class); @Autowired @Qualifier("tituloServiceImpl") private TituloServiceImpl tituloServiceImpl; // http://localhost:8090/apiFutbol/titulo //PUT @PutMapping("/titulo") public ResponseEntity<?> agregarTitulo (@Valid @RequestBody TituloModel titulo) { log.info("ini: agregarTitulo()"); log.debug("datos titulos:" + titulo.toString()); boolean flag = tituloServiceImpl.insertar(titulo); if(flag) return new ResponseEntity<>(HttpStatus.OK); else return new ResponseEntity<>(false,HttpStatus.CONFLICT); } //------------------------------------------------------------------- // http://localhost:8090/apiFutbol/titulo //POST @PostMapping("/titulo") public ResponseEntity<?> actualizarTitulo (@Valid @RequestBody TituloModel titulo) { log.info("ini: actualizarTitulo()"); log.debug("datos titulos:" + titulo.toString()); boolean flag = tituloServiceImpl.actualizar(titulo); if(flag) return new ResponseEntity<>(HttpStatus.OK); else return new ResponseEntity<>(false,HttpStatus.CONFLICT); } //-------------------------------------------------------------------------- //DELETE //http://localhost:8090/apiFutbol/borrarTitulo/1 @DeleteMapping ("/borrarTitulo/{idTitulo}") public ResponseEntity<?> borrarTitulo (@PathVariable("idTitulo") int id ) { log.info("ini: borrarTitulo()"); log.debug("id:" + id ); boolean flag = tituloServiceImpl.borrar(id); if(flag) return new ResponseEntity<>(HttpStatus.OK); else return new ResponseEntity<>(false,HttpStatus.CONFLICT); } // -------------------------------------------------------------------------- //GET SIN PARAMETROS SIN PAGINACION // http://localhost:8090/apiFutbol/titulos @GetMapping("/titulos") public List<TituloModel> obtenerTitulos(){ log.info("ini: obtenerTitulos() "); return tituloServiceImpl.obtenerTitulos(); } // ------------------------------------------------------------------- // GET CON PARAMETROS // http://localhost:8090/apiFutbol/idTitulo/ @GetMapping ("/idTitulo/{pid}") public Object obtenerTituloPorId (@PathVariable("pid")int id ) { log.info("ini: obtenerTituloPorId()"); log.debug("id:" + id ); return tituloServiceImpl.obtenerTituloPorId(id); } }
true
7d5a76df2697ce1d16d89b9317bf67d47b7af3a6
Java
changuen/obesity-project
/uDiabetesNoteOri/src/kr/co/imcc/app/uDiabetesNote/Rule1.java
UTF-8
4,115
2.65625
3
[]
no_license
package kr.co.imcc.app.uDiabetesNote; public class Rule1 { static double sex[]= new double[4]; static double age[]= new double[4]; static double total[] = new double[4]; static double sbp[] = new double[4]; static double hdl[] = new double[4]; static double dia[] = new double[4]; static double smo[] = new double[4]; static double Low=0; static double Moderate=0; static double High=0; static double Very_High=0; public static void Rule(){ Fuzzy fz = new Fuzzy(); if(Fuzzy.sex == 1){ sex[3] = 1; sex[2] = 1; //sex[1] += 0.0; //sex[0] += 0.0; age[0] += Fuzzy.Less_Mid_Age; age[1] += Fuzzy.Mid_Age; age[2] += Fuzzy.Very_Mid_Age; age[2] += Fuzzy.Less_Old; age[3] += Fuzzy.Old; total[0] += Fuzzy.total_Very_Low; total[1] += Fuzzy.total_Low; total[2] += Fuzzy.total_Mid; total[2] += Fuzzy.total_High; total[3] += Fuzzy.total_Very_High; sbp[0] += Fuzzy.sbp_Very_Low; sbp[1] += Fuzzy.sbp_Low; sbp[1] += Fuzzy.sbp_Mid; sbp[2] += Fuzzy.sbp_High; sbp[2] += Fuzzy.sbp_Very_High; hdl[0] += Fuzzy.hdl_High; hdl[0] += Fuzzy.hdl_Mid; hdl[1] += Fuzzy.hdl_Low; hdl[2] = 0; hdl[3] = 0; if(Fuzzy.smo == "Y"){ smo[0] = 0.0; smo[1] = 0.0; smo[2] = 0.45; smo[3] = 0.55; } if(Fuzzy.smo == "N"){ smo[0] = 0.6; smo[1] = 0.4; smo[2] = 0; smo[3] = 0; } if(Fuzzy.dia == "N"){ dia[0] = 0.6; dia[1] = 0.4; dia[2] = 0; dia[2] = 0; } if(Fuzzy.dia == "Y"){ dia[0] = 0; dia[1] = 0; dia[2] = 0.45; dia[3] = 0.55; } } if(Fuzzy.sex == 2){ age[0] += Fuzzy.Less_Mid_Age; age[1] += Fuzzy.Mid_Age; age[2] += Fuzzy.Very_Mid_Age; age[2] += Fuzzy.Less_Old; age[2] += Fuzzy.Old; total[0] += Fuzzy.total_Very_Low; total[1] += Fuzzy.total_Low; total[1] += Fuzzy.total_Mid; total[2] += Fuzzy.total_High; total[2] += Fuzzy.total_Very_High; sbp[0] += Fuzzy.sbp_Very_Low; sbp[1] += Fuzzy.sbp_Low; sbp[2] += Fuzzy.sbp_Mid; sbp[2] += Fuzzy.sbp_High; sbp[2] += Fuzzy.sbp_Very_High; //sex[0] = 0.5; //sex[1] = 0.5; //sex[2] = 0.0; //sex[3] = 0.0; hdl[0] += Fuzzy.hdl_High; hdl[0] += Fuzzy.hdl_Mid; hdl[1] += Fuzzy.hdl_Low; hdl[2] = 0; hdl[3] = 0; if(Fuzzy.smo == "Y"){ smo[0] = 0.0; smo[1] = 0.0; smo[2] = 1; smo[3] = 0; } if(Fuzzy.smo == "N"){ smo[0] = 0.7; smo[1] = 0.3; smo[2] = 0; smo[3] = 0; } if(Fuzzy.dia == "N"){ dia[0] = 0.7; dia[1] = 0.3; dia[2] = 0; dia[2] = 0; } if(Fuzzy.dia == "Y"){ dia[0] = 0; dia[1] = 0; dia[2] = 1; dia[3] = 0.0; } } /* for(int i = 0; i<=2; i++){ age2[i] *= 0.4; total2[i] *= 0.1; sbp2[i] *= 0.2; hdl[i] *=0.1; dia2[i] *=0.1; smo2[i] *=0.1; } */ // System.out.println("Rule1 age : "+ age1[0]+" "+age1[1]+" "+age1[2]); // System.out.println("Rule1 total : "+ total1[0]+" "+ total1[1]+" "+total1[2]); // System.out.println("Rule1 dia : "+ dia1[0]+" "+ dia1[1]+" "+ dia1[2]); Low = ( sex[0] + age[0] + total[0] + hdl[0] + sbp[0] + dia[0] + smo[0] )/7; Moderate = ( sex[1] + age[1] + total[1] + hdl[1] + sbp[1] + dia[1] + smo[1] )/7; High = ( sex[2] + age[2] + total[2] + hdl[2] + sbp[2] + dia[2] + smo[2] )/7; Very_High= ( sex[3] + age[3] + total[3] + hdl[3] + sbp[3] + dia[3] + smo[3] )/7; String aa = ""; if(Low > Moderate){ if(Low > High){ if(Low>Very_High){ aa = "Low"; } else{ aa = "Very_High"; } } else{ if(High>Very_High){ aa = "High"; } else{ aa = "Very_High"; } } } else{ if(Moderate>High){ if(Moderate>Very_High){ aa ="Moderate"; } else{ aa ="Very_High"; } } else{ if(High>Very_High){ aa = "High"; } else{ aa = "Very_High"; } } } //System.out.println(aa);//+"\t"+Low+"\t"+Moderate+"\t"+High+"\t"+Very_High+"\t"); } }
true
302422e82f3ea121eb9b49b63a0c726f206e7dbf
Java
midhunchandran/autoscale
/notification-event-service/src/main/java/com/rackspace/notification/event/api/common/Observations.java
UTF-8
773
1.992188
2
[]
no_license
package com.convenetech.notification.event.api.common; public class Observations { private String monitoring_zone_id; private String state; private String status; private long timestamp; public String getMonitoring_zone_id() { return monitoring_zone_id; } public void setMonitoring_zone_id(String monitoring_zone_id) { this.monitoring_zone_id = monitoring_zone_id; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } }
true
cf136026c037341f3f3518b9b3cc4cbfefdcbe01
Java
iagoGB/POO
/src/br/com/poo/smd/lista02/Livro.java
ISO-8859-1
1,435
2.8125
3
[]
no_license
package br.com.poo.smd.lista02; public class Livro { String titulo; String autor; String editora; int anoPublicacao; int numPagina; // Questo 1 item a int edicao; // Questo 1 item a public Livro() { //Questo 1 item b } public Livro(String t,String a,String e, int aP, int nP, int ed) { //Questo 1 item b setTitulo(t); setAutor(a); setEditora(e); setAnoPublicacao(aP); setNumPagina(nP); setEdicao(ed); } public int getEdicao() { return edicao; } public void setEdicao(int edicao) { this.edicao = edicao; } public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public String getAutor() { return autor; } public void setAutor(String autor) { this.autor = autor; } public String getEditora() { return editora; } public void setEditora(String editora) { this.editora = editora; } public int getAnoPublicacao() { return anoPublicacao; } public void setAnoPublicacao(int anoPublicacao) { this.anoPublicacao = anoPublicacao; } public int getNumPagina() { return numPagina; } public void setNumPagina(int numPagina) { this.numPagina = numPagina; } @Override public String toString() { return "Livro [titulo=" + titulo + ", autor=" + autor + ", editora=" + editora + ", anoPublicacao=" + anoPublicacao + ", numPagina=" + numPagina + ", edicao=" + edicao + "]"; } }
true
a0858ea7ad9331ee1b53d0699f503e05d936e4cc
Java
backoffbelief/surf
/surf_netty_4.x/src/main/java/com/kael/surf/muti/PlayerContext.java
UTF-8
2,624
2.21875
2
[]
no_license
package com.kael.surf.muti; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import com.google.protobuf.GeneratedMessage; import com.kael.surf.net.AbstractCommand; import com.kael.surf.net.AppPlayer; import com.kael.surf.net.Cmd; import com.kael.surf.net.Constants; import com.kael.surf.net.ICommand; import com.kael.surf.net.Resp; public class PlayerContext { private static final PlayerContext instance = new PlayerContext(); public static PlayerContext get() { return instance; } private AppExecutors appExecutors; private PlayerContext() { appExecutors = new AppExecutors("net"); } public AppQueue getAppQueue() { return appExecutors.getAppQueue(); } private Map<Short, ICommand> cmdMapper = new HashMap<Short, ICommand>(); private Map<String, Short> respMapper = new HashMap<String, Short>(); public void init(final Set<Class<?>> clazzes) throws Exception{ for (Class<?> c : clazzes) { if (c.isAnnotationPresent(Cmd.class)) { Cmd cmd = c.getAnnotation(Cmd.class); AbstractCommand command = (AbstractCommand) c.newInstance(); GeneratedMessage proto = (GeneratedMessage) Class.forName(cmd.protoName()).getMethod("getDefaultInstance", null) .invoke(null, null); if(proto == null){ throw new RuntimeException("not find class:"+cmd.protoName()); } command.setDefaultInstance(proto); cmdMapper.put(cmd.code(), command); } } Field[] fs = Constants.class.getDeclaredFields(); for (Field field : fs) { if (field.isAnnotationPresent(Resp.class)) { Resp resp = field.getAnnotation(Resp.class); // System.out.println(field.getShort(Constants.constants) + "==" + field.getName() // + "," + resp.protoName()); respMapper.put(resp.protoName(), field.getShort(Constants.constants)); } } } public ICommand getByCode(short code) { return cmdMapper.get(code); } public Short getCodeByProtoName(String protoName) { return respMapper.get(protoName); } private ConcurrentHashMap<Integer, AppPlayer> onlinePlayers = new ConcurrentHashMap<Integer, AppPlayer>(); public boolean addPlayer(AppPlayer appPlayer) { return onlinePlayers.putIfAbsent(appPlayer.getPlayerId(), appPlayer) == null; } public boolean removePlayer(AppPlayer appPlayer) { return onlinePlayers.remove(appPlayer.getPlayerId()) != null; } public ConcurrentHashMap<Integer, AppPlayer> getAllPlayers() { return onlinePlayers; } }
true
a445fbb4ff73e90edb86f526bc9458b0eb004d0d
Java
OpenHDS/openhds-server
/domain/src/main/java/org/openhds/domain/model/FieldWorker.java
UTF-8
2,607
2.40625
2
[ "BSD-2-Clause" ]
permissive
package org.openhds.domain.model; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Transient; import javax.validation.constraints.NotNull; import org.openhds.domain.annotations.Description; import org.openhds.domain.constraint.CheckFieldNotBlank; import org.openhds.domain.constraint.Searchable; @Description(description="A Field Worker represents one who collects the data within " + "the study area. They can be identified by a uniquely generated " + "identifier which the system uses internally. Only the first and last names " + "are recorded.") @Entity @Table(name="fieldworker") public class FieldWorker extends AuditableEntity implements Serializable { private static final long serialVersionUID = 1898036206514199266L; @NotNull @CheckFieldNotBlank @Searchable @Description(description="External Id of the field worker. This id is used internally.") String extId; @CheckFieldNotBlank @Searchable @Description(description="First name of the field worker.") String firstName; @CheckFieldNotBlank @Searchable @Description(description="Last name of the field worker.") String lastName; @Description(description="Password entered for a new field worker.") @Transient String password; @Description(description="Password re-entered for a new field worker.") @Transient String confirmPassword; @NotNull @CheckFieldNotBlank @Description(description="Hashed version of a field worker's password.") String passwordHash; public String getExtId() { return extId; } public void setExtId(String extId) { this.extId = extId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getConfirmPassword() { return confirmPassword; } public void setConfirmPassword(String confirmPassword) { this.confirmPassword = confirmPassword; } public String getPasswordHash() { return passwordHash; } public void setPasswordHash(String passwordHash) { this.passwordHash = passwordHash; } }
true
9f94b83bd8feb8c86dd80f86629de00ab1a9aefd
Java
TechZech/GroceryApp
/UPC_Data/app/src/main/java/com/groceryapp/upcdata/fragments/PostInventoryFragment.java
UTF-8
5,424
2.109375
2
[]
no_license
package com.groceryapp.upcdata.fragments; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.firebase.auth.FirebaseAuth; import com.groceryapp.upcdata.DB.GroceryItem.GroceryItem; import com.groceryapp.upcdata.DB.Group.Group; import com.groceryapp.upcdata.DB.User.User; import com.groceryapp.upcdata.DBHelper; import com.groceryapp.upcdata.R; import com.groceryapp.upcdata.adapters.GroceryItemAdapter; import java.util.ArrayList; import java.util.List; public class PostInventoryFragment extends InventoryFragment { public final String TAG = "InventoryFragment"; private RecyclerView rvInventory; protected GroceryItemAdapter adapter; protected List<GroceryItem> allInventoryItems; private Button createGroupButton; DBHelper dbHelper = new DBHelper(); FirebaseAuth mAuth = FirebaseAuth.getInstance(); com.groceryapp.upcdata.DB.User.User User = new User(mAuth); @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_post_inventory, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()); createGroupButton = view.findViewById(R.id.createGroupButton); GroceryItemAdapter.OnLongClickListener onLongClickListener = new GroceryItemAdapter.OnLongClickListener() { @Override public void onItemLongClicked(int position) { GroceryItem groceryItem = allInventoryItems.get(position); Log.d(TAG, "groceryItem UPC to be removed" + groceryItem.getUpc()); dbHelper.removeInventoryItem(groceryItem); allInventoryItems.remove(position); adapter.notifyItemRemoved(position); } }; createGroupButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { GroceryItem g = new GroceryItem("Test","12345","http:www.google.com/",5,"4.99",true); dbHelper.addInventoryItem(g); } }); GroceryItemAdapter.OnClickListener onClickListener = new GroceryItemAdapter.OnClickListener() { @Override public void onItemClicked(int position) { Log.d(TAG, "ITEM IS " + allInventoryItems.get(position)); goToDetailFragment(position); } }; GroceryItemAdapter.OnClickListenerQuantitySubtract subtractListener = new GroceryItemAdapter.OnClickListenerQuantitySubtract() { @Override public void onSubtractClicked(int position) { GroceryItem groceryItem = allInventoryItems.get(position); groceryItem.setInventory(false); Log.d(TAG, "groceryItem UPC to be removed" + groceryItem.getUpc()); dbHelper.removeInventoryItem(groceryItem); allInventoryItems.remove(position); adapter.notifyItemRemoved(position); dbHelper.addGroceryItem(groceryItem); } }; GroceryItemAdapter.OnClickListenerQuantityAdd addListener = new GroceryItemAdapter.OnClickListenerQuantityAdd() { @Override public void onAddClicked(int position) { } }; rvInventory = view.findViewById(R.id.tvInventory); allInventoryItems = new ArrayList<>(); adapter = new GroceryItemAdapter(getContext(), allInventoryItems, onLongClickListener, onClickListener, subtractListener, addListener); rvInventory.setAdapter(adapter); rvInventory.setLayoutManager(linearLayoutManager); allInventoryItems = dbHelper.queryInventoryItems(allInventoryItems, adapter); } private void goToDetailFragment(int position){ GroceryItem groceryItem = allInventoryItems.get(position); Bundle bundle = new Bundle(); bundle.putString("UPC", groceryItem.getUpc()); bundle.putString("Title", groceryItem.getTitle()); bundle.putString("ImageUrl", groceryItem.getImageUrl()); bundle.putString("Price", groceryItem.getPrice()); bundle.putInt("Quantity", groceryItem.getQuantity()); bundle.putBoolean("fromInventory", true); Fragment fragment = new FeedFragment(); fragment.setArguments(bundle); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction() .replace(R.id.flContainer, fragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } }
true
e3b08ad08647913bd93ff1a3be9917e927f7f52e
Java
dykdykdyk/decompileTools
/android/nut-dex2jar.src/com/facebook/FacebookSdkVersion.java
UTF-8
282
1.507813
2
[]
no_license
package com.facebook; final class FacebookSdkVersion { public static final String BUILD = "3.23.1"; } /* Location: C:\crazyd\work\ustone\odm2016031702\baidu\android\nut-dex2jar.jar * Qualified Name: com.facebook.FacebookSdkVersion * JD-Core Version: 0.6.2 */
true
7b43ca6c1fb2df3a55c3c13da4f273bb58506c0f
Java
nabinn/CS2Lab
/lab8/Exercise19_7.java
UTF-8
1,108
4
4
[]
no_license
//package lab8; /* * 19.7-(Generic binary search) Implement the following method using binary search. * public static <E extends Comparable<E>>int binarySearch(E[] list, E key). */ public class Exercise19_7 { /* * linear search: returns index of key if key is present * otherwise returns -1. * Note: the list is assumed to be sorted */ public static <E extends Comparable<E>>int binarySearch(E[] list, E key){ int low = 0; int high = list.length -1 ; while (low <= high) { int mid = (low+high)/2; if (list[mid].compareTo(key) == 0 ) return mid; else if (list[mid].compareTo(key) < 0) low = mid + 1; else high = mid - 1; } return -1; } public static void main(String[] args) { Integer[] intArray = {-3,1,2,4,6,10}; System.out.println(binarySearch(intArray, 5)); System.out.println(binarySearch(intArray, 6)); String[] strArray = {"aaa", "ddd", "qq", "tt", "yyyy"}; System.out.println(binarySearch(strArray, new String("tt"))); System.out.println(binarySearch(strArray, new String("asdf"))); } }
true
e8069ad2f310395ebb0481add4dc76c3f0177ad6
Java
OpenGamma/Strata
/modules/math/src/main/java/com/opengamma/strata/math/impl/rootfinding/newton/NewtonDefaultVectorRootFinder.java
UTF-8
1,869
2.453125
2
[ "Apache-2.0", "LicenseRef-scancode-mit-old-style" ]
permissive
/* * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.math.impl.rootfinding.newton; import com.opengamma.strata.math.impl.linearalgebra.LUDecompositionCommons; import com.opengamma.strata.math.linearalgebra.Decomposition; /** * A root finder that attempts find the multi-dimensional root of a series of N equations with N variables (a square problem). * If the analytic Jacobian is not known, it will be calculated using central difference */ public class NewtonDefaultVectorRootFinder extends BaseNewtonVectorRootFinder { /** * The default tolerance. */ private static final double DEF_TOL = 1e-7; /** * The default maximum number of steps. */ private static final int MAX_STEPS = 100; /** * Creates an instance. */ public NewtonDefaultVectorRootFinder() { this(DEF_TOL, DEF_TOL, MAX_STEPS); } /** * Creates an instance. * * @param absoluteTol the absolute tolerance * @param relativeTol the relative tolerance * @param maxSteps the maximum steps */ public NewtonDefaultVectorRootFinder(double absoluteTol, double relativeTol, int maxSteps) { this(absoluteTol, relativeTol, maxSteps, new LUDecompositionCommons()); } /** * Creates an instance. * * @param absoluteTol the absolute tolerance * @param relativeTol the relative tolerance * @param maxSteps the maximum steps * @param decomp the decomposition */ public NewtonDefaultVectorRootFinder(double absoluteTol, double relativeTol, int maxSteps, Decomposition<?> decomp) { super( absoluteTol, relativeTol, maxSteps, new JacobianDirectionFunction(decomp), new JacobianEstimateInitializationFunction(), new NewtonDefaultUpdateFunction()); } }
true
274bf81ee29ad8d0fad798fee1fbb816691b5a35
Java
webeder/POO_JAVA
/POO_JAVA/src/br/com/webeder/aula10/model/Marca.java
UTF-8
1,283
3.546875
4
[]
no_license
package br.com.webeder.aula10.model; public class Marca { private String nome; private String fabricante; public Marca() { // TODO Auto-generated constructor stub } /** * @param nome * @param fabricante */ public Marca(String nome, String fabricante) { /* O super é utilizado para acessar o construtor da classe pai. Se vc tem uma classe "Carro" por exemplo, que herda da classe "Veiculo", e quer acessar o construtor da classe Veiculo dentro da classe Carro, vc usa o super(); (Obrigatóriamente a classe Veiculo deve ter um construtor sem argumentos, caso não, deve-se passar super(arg1, arg2,..., argN)*/ super(); this.nome = nome; this.fabricante = fabricante; } /** * @return the nome */ public String getNome() { return nome; } /** * @param nome * the nome to set */ public void setNome(String nome) { this.nome = nome; } /** * @return the fabricante */ public String getFabricante() { return fabricante; } /** * @param fabricante * the fabricante to set */ public void setFabricante(String fabricante) { this.fabricante = fabricante; } }
true
d7f7e4ec7c22c13803dec604fd3070ad947a2c5d
Java
glf2046/java-test
/java8-test/src/main/java/function/MethodClassOne.java
UTF-8
178
1.976563
2
[]
no_license
package function; /** * @author guff * @since 2019-06-9:06 PM */ public class MethodClassOne { public static Integer a(Integer input){ return input + 1; } }
true
5b9fdd75a8decdc396a5bfcf1a2ee542b05e3eea
Java
lavish10/Moods
/app/src/main/java/com/moods_final/moods/moods/MainActivity.java
UTF-8
14,873
1.765625
2
[]
no_license
package com.moods_final.moods.moods; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.facebook.AccessToken; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.appevents.AppEventsLogger; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FacebookAuthProvider; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity implements View.OnClickListener,GoogleApiClient.OnConnectionFailedListener { private LoginButton loginButton; private FirebaseAuth firebaseAuth; private Button buttonRegister; private EditText editTextEmail; private EditText editTextPassword; private TextView textViewSignin; private CallbackManager callbackManager; private ProgressDialog progressDialog; private FirebaseAuth.AuthStateListener mAuthListener; private DatabaseReference mDatabase; private static final String TAG = "FacebookLogin"; private static final String TAG1 = "GoogleActivity"; private static final int RC_SIGN_IN = 9001; private GoogleApiClient mGoogleApiClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(getApplicationContext()); AppEventsLogger.activateApp(this); setContentView(R.layout.activity_main); progressDialog = new ProgressDialog(this); callbackManager=CallbackManager.Factory.create(); firebaseAuth=FirebaseAuth.getInstance(); mDatabase = FirebaseDatabase.getInstance().getReference(); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this /* FragmentActivity */, MainActivity.this /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in //Toast.makeText(getApplicationContext(),"Already signed in",Toast.LENGTH_SHORT).show(); Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid()); startActivity(new Intent(getApplicationContext(), RecognizeActivity.class)); } else { // User is signed out // Toast.makeText(getApplicationContext(),"Signed out!",Toast.LENGTH_SHORT).show(); Log.d(TAG, "onAuthStateChanged:signed_out"); } // ... } }; if(firebaseAuth.getCurrentUser()!=null){ //profile activity here startActivity(new Intent(getApplicationContext(), RecognizeActivity.class)); } buttonRegister=(Button)findViewById(R.id.buttonRegister); editTextEmail=(AutoCompleteTextView) findViewById(R.id.editTextEmail); editTextPassword=(EditText) findViewById(R.id.editTextPassword); textViewSignin= (TextView) findViewById(R.id.textViewSignin); loginButton=(LoginButton)findViewById(R.id.login_button1); findViewById(R.id.googlebtn).setOnClickListener(this); findViewById(R.id.sign_out_and_disconnect).setOnClickListener(this); buttonRegister.setOnClickListener(this); textViewSignin.setOnClickListener(this); loginButton.setReadPermissions("email","public_profile"); loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { Log.d(TAG, "facebook:onSuccess:" + loginResult); handleFacebookAccessToken(loginResult.getAccessToken()); goMainScreen(); } @Override public void onCancel() { Toast.makeText(getApplicationContext(),"Cancelled",Toast.LENGTH_SHORT).show(); Log.d(TAG, "facebook:onCancel"); } @Override public void onError(FacebookException error) { Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_SHORT).show(); Log.d(TAG, "facebook:onError", error); } }); } @Override public void onStart() { super.onStart(); firebaseAuth.addAuthStateListener(mAuthListener); } @Override public void onStop() { super.onStop(); if (mAuthListener != null) { firebaseAuth.removeAuthStateListener(mAuthListener); } } private void goMainScreen() { Intent intent = new Intent(this, RecognizeActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } @Override protected void onActivityResult(int requestCode,int resultCode,Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); if (!result.isSuccess()) { // Google Sign In failed, update UI appropriately // [START_EXCLUDE] Log.d(TAG1, "google sign in failure:" + result); Toast.makeText(getApplicationContext(),"google signin failed",Toast.LENGTH_LONG).show(); // [END_EXCLUDE] } else { // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = result.getSignInAccount(); firebaseAuthWithGoogle(account); Toast.makeText(getApplicationContext(),"google signin success",Toast.LENGTH_LONG).show(); goMainScreen(); finish(); } } else { callbackManager.onActivityResult(requestCode, resultCode, data); } } // [START auth_with_facebook] private void handleFacebookAccessToken(AccessToken token) { Log.d(TAG, "handleFacebookAccessToken:" + token); AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken()); firebaseAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { Log.w(TAG, "signInWithCredential", task.getException()); Toast.makeText(MainActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } } }); } // [END auth_with_facebook] private void registerUser(){ final String email=editTextEmail.getText().toString().trim(); final String password =editTextPassword.getText().toString().trim(); if(TextUtils.isEmpty(email)){ //email is Empty Toast.makeText(this,"Please enter email",Toast.LENGTH_SHORT).show(); //stopping the function execution further return; } if(TextUtils.isEmpty(password)) { //password is Empty Toast.makeText(this,"Please enter password",Toast.LENGTH_SHORT).show(); //stopping the function execution further return; } // If validations are ok //we will first show progress bar progressDialog.setMessage("Requesting User..."); progressDialog.show(); firebaseAuth.createUserWithEmailAndPassword(email,password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ //user is successfully registered and logged in // we will start the profile activity here //right now lets display a toast only Toast.makeText(MainActivity.this,"Registered Successfully",Toast.LENGTH_SHORT).show(); String key = mDatabase.child("posts").push().getKey(); Post post = new Post(email,password); Map<String, Object> postValues = post.toMap(); Map<String, Object> childUpdates = new HashMap<>(); childUpdates.put("/posts/" + key, postValues); //childUpdates.put("/user-email/" + , postValues); mDatabase.updateChildren(childUpdates); finish(); startActivity(new Intent(getApplicationContext(), RecognizeActivity.class)); } else { Toast.makeText(MainActivity.this,"Couldn't register. Please try again",Toast.LENGTH_SHORT).show(); } progressDialog.dismiss(); } }); } // [END onactivityresult] // [START auth_with_google] private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId()); // [START_EXCLUDE silent] //showProgressDialog(); // [END_EXCLUDE] AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); firebaseAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { Log.w(TAG, "signInWithCredential", task.getException()); Toast.makeText(MainActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } // [START_EXCLUDE] // hideProgressDialog(); // [END_EXCLUDE] } }); } // [END auth_with_google] // [START signin] private void signIn() { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } // [END signin] @Override public void onBackPressed() { // Do Here what ever you want do on back press; } private void signOut() { // Firebase sign out firebaseAuth.signOut(); // Google sign out Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(@NonNull Status status) { // updateUI(null); } }); } private void revokeAccess() { // Firebase sign out firebaseAuth.signOut(); // Google revoke access Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(@NonNull Status status) { // updateUI(null); } }); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { // An unresolvable error has occurred and Google APIs (including Sign-In) will not // be available. Log.d(TAG, "onConnectionFailed:" + connectionResult); Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show(); } @Override public void onClick(View view) { if (view.getId() == R.id.googlebtn) { signIn(); } else if (view.getId() == R.id.sign_out_and_disconnect) { signOut(); revokeAccess(); } if(view == buttonRegister) { registerUser(); } if(view == textViewSignin){ //will open login activity here startActivity(new Intent(this, LoginActivity.class)); } } }
true
955b67f2413abaf1322caab2b511f379ad3c0acc
Java
MahmoudYahia/ToDoList
/app/src/main/java/com/project/todolist/datamodel/Item.java
UTF-8
1,305
2.421875
2
[]
no_license
package com.project.todolist.datamodel; /** * Created by mah_y on 8/28/2017. */ public class Item { private String itemId; private String itemOwnerId; private String itemTitle; private String itemDesc; public Item() { } public Item(String itemId, String itemOwnerId, String itemTitle, String itemDesc) { this.itemId = itemId; this.itemOwnerId = itemOwnerId; this.itemTitle = itemTitle; this.itemDesc = itemDesc; } public Item(String itemOwnerId, String itemTitle, String itemDesc) { this.itemOwnerId = itemOwnerId; this.itemTitle = itemTitle; this.itemDesc = itemDesc; } public String getItemId() { return itemId; } public void setItemId(String itemId) { this.itemId = itemId; } public String getItemOwnerId() { return itemOwnerId; } public void setItemOwnerId(String itemOwnerId) { this.itemOwnerId = itemOwnerId; } public String getItemTitle() { return itemTitle; } public void setItemTitle(String itemTitle) { this.itemTitle = itemTitle; } public String getItemDesc() { return itemDesc; } public void setItemDesc(String itemDesc) { this.itemDesc = itemDesc; } }
true
c6eae98ea7fe4b708296dd694135d57c0ad8c8b1
Java
hugokallstrom/Disassembler
/src/main/Printer.java
UTF-8
764
3.453125
3
[]
no_license
package main; /** * Prints the parsed data contained * in different ArrayLists. * * @author oi11hkm * */ public class Printer { /** * Constructor. */ public Printer() { } /** * Prints the data. */ public void printData(InstructionInfo insInfo) { int i = 0; System.out.printf("%-2s%12s%9s%5s%25s%35s\n" , "Nr", "From file", "Format", "Dec", "Hex", "Mnemonic"); while(i < insInfo.getSize()) { System.out.format("#%-4d", i); System.out.format("%-12s", insInfo.getCode(i)); System.out.printf("%-8c", insInfo.getFormat(i)); System.out.printf("%-25s", insInfo.getDecompDec(i)); System.out.printf("%-30s", insInfo.getDecompHex(i)); System.out.printf("%s", insInfo.getMnemonic(i)); System.out.print("\n"); i++; } } }
true
f3ffe76b866b3b3321857ccd9d9c95ec96210010
Java
boodoopl/karaf-wine-cellar
/bundles/model/src/main/java/org/karaf/winecellar/model/Image.java
UTF-8
635
2.28125
2
[]
no_license
package org.karaf.winecellar.model; import javax.persistence.Entity; import javax.persistence.Lob; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; @Entity @NamedQueries({ @NamedQuery(name="Image.GET_ALL", query="SELECT i FROM Image i"), @NamedQuery(name="Image.GET_COUNT", query="SELECT COUNT(i) FROM Image i"), }) public class Image extends EntityWithId { @Lob private byte[] data; public Image(byte[] data) { this.data = data; } public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } }
true
24ed6aa3d194a5f16a4abadbc70d2e299f11cf54
Java
a2dm/agn-web
/agn-ngc/src/main/java/br/com/a2dm/ngc/entity/Clinica.java
UTF-8
5,801
1.859375
2
[]
no_license
package br.com.a2dm.ngc.entity; import java.io.Serializable; import java.math.BigInteger; import java.util.Date; import java.util.HashMap; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import org.hibernate.annotations.Proxy; import br.com.a2dm.cmn.entity.Usuario; /** * @author Carlos Diego * @since 24/06/2016 */ @Entity @Table(name = "tb_clinica", schema="agn") @SequenceGenerator(name = "SQ_CLINICA", sequenceName = "SQ_CLINICA", allocationSize = 1) @Proxy(lazy = true) public class Clinica implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SQ_CLINICA") @Column(name = "id_clinica") private BigInteger idClinica; @Column(name = "id_usuario") private BigInteger idUsuario; @Column(name = "des_clinica") private String desClinica; @Column(name = "num_cnpj_clinica") private String numCnpjClinica; @Column(name = "tlf_clinica") private String tlfClinica; @Column(name = "cep_clinica") private String cepClinica; @Column(name = "lgd_clinica") private String lgdClinica; @Column(name = "num_end_clinica") private BigInteger numEndClinica; @Column(name = "bro_clinica") private String broClinica; @Column(name = "cid_clinica") private String cidClinica; @Column(name = "id_estado") private BigInteger idEstado; @Column(name = "cmp_clinica") private String cmpClinica; @Column(name = "flg_ativo") private String flgAtivo; @Temporal(TemporalType.TIMESTAMP) @Column(name = "dat_cadastro") private Date datCadastro; @Column(name = "id_usuario_cad") private BigInteger idUsuarioCad; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_usuario_cad", insertable = false, updatable = false) private Usuario usuarioCad; @Temporal(TemporalType.TIMESTAMP) @Column(name = "dat_alteracao") private Date datAlteracao; @Column(name = "id_usuario_alt") private BigInteger idUsuarioAlt; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_usuario_alt", insertable = false, updatable = false) private Usuario usuarioAlt; @Transient private HashMap<String, Object> filtroMap; public BigInteger getIdClinica() { return idClinica; } public void setIdClinica(BigInteger idClinica) { this.idClinica = idClinica; } public BigInteger getIdUsuario() { return idUsuario; } public void setIdUsuario(BigInteger idUsuario) { this.idUsuario = idUsuario; } public String getDesClinica() { return desClinica; } public void setDesClinica(String desClinica) { this.desClinica = desClinica; } public String getNumCnpjClinica() { return numCnpjClinica; } public void setNumCnpjClinica(String numCnpjClinica) { this.numCnpjClinica = numCnpjClinica; } public String getTlfClinica() { return tlfClinica; } public void setTlfClinica(String tlfClinica) { this.tlfClinica = tlfClinica; } public String getCepClinica() { return cepClinica; } public void setCepClinica(String cepClinica) { this.cepClinica = cepClinica; } public String getLgdClinica() { return lgdClinica; } public void setLgdClinica(String lgdClinica) { this.lgdClinica = lgdClinica; } public BigInteger getNumEndClinica() { return numEndClinica; } public void setNumEndClinica(BigInteger numEndClinica) { this.numEndClinica = numEndClinica; } public String getBroClinica() { return broClinica; } public void setBroClinica(String broClinica) { this.broClinica = broClinica; } public String getCidClinica() { return cidClinica; } public void setCidClinica(String cidClinica) { this.cidClinica = cidClinica; } public BigInteger getIdEstado() { return idEstado; } public void setIdEstado(BigInteger idEstado) { this.idEstado = idEstado; } public String getCmpClinica() { return cmpClinica; } public void setCmpClinica(String cmpClinica) { this.cmpClinica = cmpClinica; } public String getFlgAtivo() { return flgAtivo; } public void setFlgAtivo(String flgAtivo) { this.flgAtivo = flgAtivo; } public Date getDatCadastro() { return datCadastro; } public void setDatCadastro(Date datCadastro) { this.datCadastro = datCadastro; } public BigInteger getIdUsuarioCad() { return idUsuarioCad; } public void setIdUsuarioCad(BigInteger idUsuarioCad) { this.idUsuarioCad = idUsuarioCad; } public Usuario getUsuarioCad() { return usuarioCad; } public void setUsuarioCad(Usuario usuarioCad) { this.usuarioCad = usuarioCad; } public Date getDatAlteracao() { return datAlteracao; } public void setDatAlteracao(Date datAlteracao) { this.datAlteracao = datAlteracao; } public BigInteger getIdUsuarioAlt() { return idUsuarioAlt; } public void setIdUsuarioAlt(BigInteger idUsuarioAlt) { this.idUsuarioAlt = idUsuarioAlt; } public Usuario getUsuarioAlt() { return usuarioAlt; } public void setUsuarioAlt(Usuario usuarioAlt) { this.usuarioAlt = usuarioAlt; } public HashMap<String, Object> getFiltroMap() { return filtroMap; } public void setFiltroMap(HashMap<String, Object> filtroMap) { this.filtroMap = filtroMap; } }
true
f6c0201d34d20522e966be8316403f7eb4b8d114
Java
bcarrascoi/Carrasco_Deleg_SistemaBancario
/transaccional/src/main/java/ec/ups/edu/proyecto/g1/transaccional/dao/UsuarioDAO.java
UTF-8
975
2.46875
2
[]
no_license
package ec.ups.edu.proyecto.g1.transaccional.dao; import java.sql.SQLException; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import ec.ups.edu.proyecto.g1.transaccional.modelo.Usuario; @Stateless public class UsuarioDAO { @PersistenceContext EntityManager em; public UsuarioDAO() { // TODO Auto-generated constructor stub } public boolean insert(Usuario usuario) throws SQLException { em.persist(usuario); return true; } /** public boolean insert(Usuario usuario) throws SQLException { String sql = "INSERT INTO Usuario (id, correo, clave, rol)"+ "VALUES (?, ?, ?, ?)"; PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, usuario.getId()); ps.setString(2, usuario.getCorreo()); ps.setString(3, usuario.getClave()); ps.setString(4, usuario.getRol()); ps.executeUpdate(); ps.close(); return true; } */ }
true
2b93f1975eefc671e67c5d8253c15ad2dfdec329
Java
soluvas/soluvas-buzz
/app/src/main/java/org/soluvas/buzz/app/BuzzApplication.java
UTF-8
7,129
1.695313
2
[ "CC-BY-3.0" ]
permissive
package org.soluvas.buzz.app; import org.apache.wicket.Page; import org.apache.wicket.request.resource.caching.FilenameWithVersionResourceCachingStrategy; import org.apache.wicket.request.resource.caching.version.MessageDigestResourceVersion; import org.apache.wicket.serialize.java.DeflatedJavaSerializer; import org.apache.wicket.spring.injection.annot.SpringComponentInjector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.soluvas.web.site.AtmosphereApplication; import com.google.javascript.jscomp.CompilationLevel; import de.agilecoders.wicket.core.Bootstrap; import de.agilecoders.wicket.core.markup.html.RenderJavaScriptToFooterHeaderResponseDecorator; import de.agilecoders.wicket.core.settings.BootstrapSettings; import de.agilecoders.wicket.core.settings.DefaultThemeProvider; import de.agilecoders.wicket.core.settings.ThemeProvider; import de.agilecoders.wicket.extensions.javascript.GoogleClosureJavaScriptCompressor; import de.agilecoders.wicket.extensions.javascript.YuiCssCompressor; /** * @author ceefour * */ public class BuzzApplication extends AtmosphereApplication { private static final Logger log = LoggerFactory .getLogger(BuzzApplication.class); @Override public Class<? extends Page> getHomePage() { return HomePage.class; } @Override protected void init() { super.init(); getDebugSettings().setAjaxDebugModeEnabled(false); getComponentInstantiationListeners().add( new SpringComponentInjector(this)); configureBootstrap(); optimizeForWebPerformance(); // X-Forwarded-Proto support, see http://apropos0.blogspot.com/2013/05/wicket-ssl-nginx.html // getFilterFactoryManager().addXForwardedRequestWrapperFactory(null); // notice that in most cases this should be done as the // last mounting-related operation because it replaces the root mapper // Seems that HttpsMapper is the culprit. Without HttpsMapper I never see this error. // https://issues.apache.org/jira/browse/WICKET-5282 // setRootRequestMapper(new HttpsMapper(getRootRequestMapper(), new HttpsConfig()) { // @Override // protected Scheme getSchemeOf(Request request) { // final HttpServletRequest req = (HttpServletRequest) request.getContainerRequest(); // log.trace("Scheme for request {} is {}", req, req.getScheme()); // // if ("https".equalsIgnoreCase(req.getScheme())) // { // return Scheme.HTTPS; // } // else if ("http".equalsIgnoreCase(req.getScheme())) // { // return Scheme.HTTP; // } // else if ("WebSocket".equalsIgnoreCase(req.getScheme())) // { // return Scheme.ANY; // } // else // { // throw new IllegalStateException("Could not resolve protocol for request: " + req // + ", unrecognized scheme: " + req.getScheme()); // } // } // }); // setRootRequestMapper(new HttpsMapper(getRootRequestMapper(), new HttpsConfig()) { // @Override // protected Scheme getDesiredSchemeFor( // Class<? extends IRequestablePage> pageClass) { // final HttpServletRequest servletRequest = (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest(); // return servletRequest.isSecure() || super.getDesiredSchemeFor(pageClass) == Scheme.HTTPS ? Scheme.HTTPS : Scheme.ANY; // } // // @Override // protected Scheme getDesiredSchemeFor(IRequestHandler handler) { // final HttpServletRequest servletRequest = (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest(); // return servletRequest.isSecure() ? Scheme.HTTPS : Scheme.ANY; // } // }); mountPages(); } private void mountPages() { /* Atmosphere bug: Any URI with first path segment containing '_' will throw: * org.atmosphere.cpr.AtmosphereMappingException: No AtmosphereHandler maps request for /_ * org.atmosphere.cpr.AsynchronousProcessor.map(AsynchronousProcessor.java:400) * org.atmosphere.cpr.AsynchronousProcessor.action(AsynchronousProcessor.java:204) * org.atmosphere.cpr.AsynchronousProcessor.suspended(AsynchronousProcessor.java:166) * org.atmosphere.container.Tomcat7CometSupport.service(Tomcat7CometSupport.java:88) * org.atmosphere.container.Tomcat7AsyncSupportWithWebSocket.doService(Tomcat7AsyncSupportWithWebSocket.java:63) * org.atmosphere.container.TomcatWebSocketUtil.doService(TomcatWebSocketUtil.java:87) * org.atmosphere.container.Tomcat7AsyncSupportWithWebSocket.service(Tomcat7AsyncSupportWithWebSocket.java:59) * org.atmosphere.cpr.AtmosphereFramework.doCometSupport(AtmosphereFramework.java:1441) * org.atmosphere.cpr.AtmosphereServlet.event(AtmosphereServlet.java:361) * org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) * org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) * org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) * org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) * org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) * org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) * org.apache.tomcat.util.net.AprEndpoint$SocketWithOptionsProcessor.run(AprEndpoint.java:1810) * java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) * java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) * java.lang.Thread.run(Thread.java:724) */ mountPage("tenantsettings", TenantSettingsPage.class); } /** * configures wicket-bootstrap and installs the settings. */ private void configureBootstrap() { final ThemeProvider themeProvider = new DefaultThemeProvider() {{ // addDefaultTheme(new QuikdoTheme()); }}; final BootstrapSettings settings = new BootstrapSettings(); settings.setJsResourceFilterName("footer-container"); settings.setThemeProvider(themeProvider); Bootstrap.install(this, settings); // final IBootstrapLessCompilerSettings lessCompilerSettings = new BootstrapLessCompilerSettings(); // lessCompilerSettings.setUseLessCompiler(usesDevelopmentConfig()) // .setLessCompiler(new Less4JCompiler()); // BootstrapLess.install(this, lessCompilerSettings); } /** * optimize wicket for a better web performance */ private void optimizeForWebPerformance() { if (usesDeploymentConfig()) { getResourceSettings().setCachingStrategy(new FilenameWithVersionResourceCachingStrategy( new MessageDigestResourceVersion() )); getResourceSettings().setJavaScriptCompressor(new GoogleClosureJavaScriptCompressor(CompilationLevel.SIMPLE_OPTIMIZATIONS)); getResourceSettings().setCssCompressor(new YuiCssCompressor()); getFrameworkSettings().setSerializer(new DeflatedJavaSerializer(getApplicationKey())); } setHeaderResponseDecorator(new RenderJavaScriptToFooterHeaderResponseDecorator()); } }
true
719cf0eac6264530f149c3dd531d12f7f3057c4a
Java
davideag81/Operative-System
/Operative System/it.dping.src/semaphoreDef/Semaforo.java
UTF-8
1,185
3.3125
3
[]
no_license
package semaphoreDef; import java.util.concurrent.Semaphore; public class Semaforo { /* Contatore del semaforo */ private int contatore; /* Numero di processi sospesi sul semaforo */ private int contatoreProcessiInAttesa; /** * Crea un nuovo semaforo con il contatore interno inizializzato al valore * specificato da <CODE>contatore</CODE>. */ public Semaforo(int contatore) throws InterruptedException { if ( contatore < 0 ) throw new InterruptedException("Semaforo inizializzato con un valore negativo" ); this.contatore = contatore; } /** * Se <CODE>contatore=0</CODE> si sospende sul semaforo il thread * invocante la <CODE>wwait</CODE>, altrimenti <CODE>contatore--</CODE>. */ public synchronized void wwait() throws InterruptedException { if ( contatore == 0 ) { contatoreProcessiInAttesa++; wait(); contatoreProcessiInAttesa--; } else contatore--; } /** * Se esistono thread sospesi sul semaforo se ne risveglia uno, altrimenti * <CODE>contatore++</CODE>. */ public synchronized void ssignal() { if ( contatoreProcessiInAttesa > 0 ) notify(); else contatore++; } }
true
4b48c9363ef6d657a9aa318b0a6cd734a38a73f1
Java
yiding-he/hydrogen-file-storage
/src/test/java/com/hyd/filestorage/GitStorageTest.java
UTF-8
595
2.53125
3
[ "Apache-2.0" ]
permissive
package com.hyd.filestorage; import com.hyd.filestorage.git.GitStorage; import java.net.URI; import java.nio.charset.StandardCharsets; import org.junit.Test; public class GitStorageTest { @Test public void readFile() throws Exception { String uri = "https://github.com/yiding-he/hydrogen-file-storage.git"; String path = "README.md"; Storage storage = new GitStorage(new URI(uri)); Content content = storage.getContent(path); byte[] bytes = content.getContent(); System.out.println(new String(bytes, StandardCharsets.UTF_8)); } }
true
aa78af3340faf98349b607867a7f20c2dfe56328
Java
ESVitor/College-work-
/JavaProject_AutomatedCommercialTrading/src/company/abstractFactoryPattern/CompanyFactory.java
UTF-8
1,006
3.78125
4
[]
no_license
package company.abstractFactoryPattern; /** * Factory class that produce companies, this class implements * CompanyAbstractFactory. * * @author Ennio * @author Thieres * @author Fernanda * @version 1.0, 22 April 2018 */ public class CompanyFactory implements CompanyAbstractFactory { String name; /** * Constructor for the class CompanyFactory that initialize the name of the company. * *@param name the only value that has to pass. * * @since version 1.00 */ public CompanyFactory(String name) { // Set the name of the new company. this.name = name; } /** * Method to produce a company object * *@return name the only value that has to pass. * * @since version 1.00 */ @Override public Company createCompany() { // Returns the name of the new company to the Company class. return new Company (name); } }
true
62434101872e83b1fd57ba1e7f7fc861100930de
Java
rifkifikri/multiple-inheritance
/MejaSantai.java
UTF-8
178
2.203125
2
[]
no_license
public class MejaSantai extends MejaParents {//sub class atau inherit dari meja parents public void mejaSantai() { System.out.println("Meja Santai anak dari Big meja"); } }
true
670a9ab6ccc2ef27ad3c35bebda15cfd4ca96f55
Java
877867559/elasticsearch06
/src/main/java/org/elasticsearch/http/HttpServer.java
UTF-8
6,279
1.773438
2
[]
no_license
/* * Licensed to Elastic Search and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Elastic Search 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.elasticsearch.http; import com.google.inject.Inject; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.action.admin.cluster.node.info.TransportNodesInfo; import org.elasticsearch.rest.JsonThrowableRestResponse; import org.elasticsearch.rest.RestController; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.util.component.AbstractLifecycleComponent; import org.elasticsearch.util.path.PathTrie; import org.elasticsearch.util.settings.Settings; import java.io.IOException; /** * @author kimchy (shay.banon) */ public class HttpServer extends AbstractLifecycleComponent<HttpServer> { private final HttpServerTransport transport; private final ThreadPool threadPool; private final RestController restController; private final TransportNodesInfo nodesInfo; private final PathTrie<HttpServerHandler> getHandlers; private final PathTrie<HttpServerHandler> postHandlers; private final PathTrie<HttpServerHandler> putHandlers; private final PathTrie<HttpServerHandler> deleteHandlers; @Inject public HttpServer(Settings settings, HttpServerTransport transport, ThreadPool threadPool, RestController restController, TransportNodesInfo nodesInfo) { super(settings); this.transport = transport; this.threadPool = threadPool; this.restController = restController; this.nodesInfo = nodesInfo; getHandlers = new PathTrie<HttpServerHandler>(); postHandlers = new PathTrie<HttpServerHandler>(); putHandlers = new PathTrie<HttpServerHandler>(); deleteHandlers = new PathTrie<HttpServerHandler>(); transport.httpServerAdapter(new HttpServerAdapter() { @Override public void dispatchRequest(HttpRequest request, HttpChannel channel) { internalDispatchRequest(request, channel); } }); } public void registerHandler(HttpRequest.Method method, String path, HttpServerHandler handler) { if (method == HttpRequest.Method.GET) { getHandlers.insert(path, handler); } else if (method == HttpRequest.Method.POST) { postHandlers.insert(path, handler); } else if (method == HttpRequest.Method.PUT) { putHandlers.insert(path, handler); } else if (method == HttpRequest.Method.DELETE) { deleteHandlers.insert(path, handler); } } @Override protected void doStart() throws ElasticSearchException { transport.start(); if (logger.isInfoEnabled()) { logger.info("{}", transport.boundAddress()); } nodesInfo.putNodeAttribute("http_address", transport.boundAddress().publishAddress().toString()); } @Override protected void doStop() throws ElasticSearchException { nodesInfo.removeNodeAttribute("http_address"); transport.stop(); } @Override protected void doClose() throws ElasticSearchException { transport.close(); } private void internalDispatchRequest(final HttpRequest request, final HttpChannel channel) { final HttpServerHandler httpHandler = getHandler(request); if (httpHandler == null) { restController.dispatchRequest(request, channel); } else { if (httpHandler.spawn()) { threadPool.execute(new Runnable() { @Override public void run() { try { httpHandler.handleRequest(request, channel); } catch (Exception e) { try { channel.sendResponse(new JsonThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response for uri [" + request.uri() + "]", e1); } } } }); } else { try { httpHandler.handleRequest(request, channel); } catch (Exception e) { try { channel.sendResponse(new JsonThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response for uri [" + request.uri() + "]", e1); } } } } } private HttpServerHandler getHandler(HttpRequest request) { String path = getPath(request); HttpRequest.Method method = request.method(); if (method == HttpRequest.Method.GET) { return getHandlers.retrieve(path, request.params()); } else if (method == HttpRequest.Method.POST) { return postHandlers.retrieve(path, request.params()); } else if (method == HttpRequest.Method.PUT) { return putHandlers.retrieve(path, request.params()); } else if (method == HttpRequest.Method.DELETE) { return deleteHandlers.retrieve(path, request.params()); } else { return null; } } private String getPath(HttpRequest request) { String uri = request.uri(); int questionMarkIndex = uri.indexOf('?'); if (questionMarkIndex == -1) { return uri; } return uri.substring(0, questionMarkIndex); } }
true
afdac584177e5a18a68dde2fb6cd06e1df5b3ebf
Java
AliMa3s/Java-Projects
/Logging/src/opgaven/TestFile.java
UTF-8
1,272
2.875
3
[]
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 opgaven; import java.io.File; import java.net.URISyntaxException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; public class TestFile { public static void main(String[] args) { try { //First make the url then check the null point, after it rest URL url = TestFile.class.getResource("/opgaven/Woensdag.txt"); if(url != null){ File bestand = new File(url.toURI()); if(bestand.exists()){ System.out.println("aantal bytes : " + bestand.length()); }else{ System.out.println("Bestaat niet "); } }} catch (URISyntaxException ex ) { Logger.getLogger(TestFile.class.getName()).log(Level.SEVERE, null, ex); //ZELFDE RESULTAAT ALS ER BOVEN // ex.printStackTrace(); }catch(Exception ex){ Logger.getLogger(TestFile.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Einde"); } }
true
ba508df087db759323bb1b508d29a3611390e857
Java
jecky100000/wineryManagement
/model/src/com/dw/servlet/UserServlet.java
UTF-8
30,290
1.992188
2
[]
no_license
package com.dw.servlet; import java.io.IOException; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dw.domain.Level; import com.dw.domain.Page; import com.dw.domain.Promotion; import com.dw.domain.Settlement; import com.dw.domain.ShopCart; import com.dw.domain.User; import com.dw.domain.WineInfo; import com.dw.dao.CheckDao; import com.dw.domain.Card; import com.dw.domain.Check; import com.dw.service.BonusService; import com.dw.service.CheckService; import com.dw.service.LevelService; import com.dw.service.PromotionService; import com.dw.service.SettlementService; import com.dw.service.ShopCartService; import com.dw.service.UserService; import com.dw.service.WineInfoService; @WebServlet("/userServlet") public class UserServlet extends HttpServlet { public UserServlet() { super(); } private static final long serialVersionUID = 1L; private static String ChangedFID = ""; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * 注册页面跳转 * @author jingluo * @param request * @param response * @throws IOException * @throws ServletException */ protected void zhuceye(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String userId = (String) request.getSession().getAttribute("userID"); request.setAttribute("userID", userId); request.getRequestDispatcher("/WEB-INF/page/register.jsp").forward(request, response); return; } /** * 登出功能 * @param request * @param response * @throws IOException * @throws ServletException */ protected void logout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Enumeration em = request.getSession().getAttributeNames(); while(em.hasMoreElements()){ request.getSession().removeAttribute(em.nextElement().toString()); } request.getRequestDispatcher("/WEB-INF/page/login.jsp").forward(request, response); return; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String methodName = request.getParameter("method"); try { Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); // 获取私有成员变量 //System.out.println("method方法:" + method); method.setAccessible(true); method.invoke(this, request, response); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } UserService userService = new UserService(); SettlementService settlementService = new SettlementService(); PromotionService promotionService = new PromotionService(); ShopCartService shopCartService = new ShopCartService(); WineInfoService wineInfoService = new WineInfoService(); LevelService levelService = new LevelService(); BonusService bonusService = new BonusService(); CheckService checkService = new CheckService(); /** * 检查手机号是否重复注册 * @param request * @param response * @throws IOException * @throws ServletException */ protected void checkPhone(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException { String phone = request.getParameter("phone"); String Msg = ""; if(!userService.checkPhone(phone)){ Msg = "true"; }else{ Msg = "false"; } response.setCharacterEncoding("UTF-8"); response.setContentType("text/javascript"); response.getWriter().print(Msg); return; } /** * 检查是否为左右分支 * @param request * @param response * @throws IOException * @throws ServletException */ protected void checkNID(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String userID = request.getParameter("userID"); //System.out.println("****userID:" + userID); String msg = ""; if(levelService.checkNID(userID)){ msg = "true"; }else{ msg = "false"; } response.setCharacterEncoding("UTF-8"); response.setContentType("text/javascript"); response.getWriter().print(msg); return; } /** * * 改变分支 * @param request * @param response * @throws IOException * @throws ServletException * protected void exchangeFID(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String userID = request.getParameter("userId"); String d = request.getParameter("d"); String organID = request.getParameter("organID"); //System.out.println("****userID:" + userID); String msg = ""; if(levelService.exchangeFID(userID,d,organID)){ msg = "true"; }else{ msg = "false"; } response.setCharacterEncoding("UTF-8"); response.setContentType("text/javascript"); response.getWriter().print(msg); return; } */ /** * 检查是否存在该身份证号 * @param request * @param response * @throws IOException * @throws ServletException */ protected void checkID(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String ID = request.getParameter("ID"); //System.out.println("test......................."); String msg = ""; if(userService.checkID(ID)){ msg = "false"; }else{ msg = "true"; } //System.out.println(msg); response.setCharacterEncoding("UTF-8"); response.setContentType("text/javascript"); response.getWriter().print(msg); return; } /** * 注册功能 * @author jingluo * @param request * @param response * @throws IOException * @throws ServletException */ protected void zhuce(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { SimpleDateFormat df = new SimpleDateFormat("yyy-MM-dd");//设置日期格式 // 获取用户输入的值 String userFID = (String) request.getSession().getAttribute("userID"); Integer nextAmount = levelService.getNextAmount(userFID); //System.out.println("这个父级目前有" + nextAmount + "个下级"); if(nextAmount == 0) { userFID = userFID + "&L"; }else if(nextAmount == 1) { userFID = userFID + "&R"; }else if(nextAmount >= 2){ userFID = userFID + "&O"; } String userName = request.getParameter("regigterUsername"); String userLevel = new String(request.getParameter("regigterLevel")); String userSex=new String(request.getParameter("regigterSex")); //String userSex = request.getParameter("regigterSex"); String userAdress = new String(request.getParameter("regigterAdress")); String userPhone = request.getParameter("regigterPhone"); String userID = request.getParameter("regigteruserID"); String userPassword = request.getParameter("regigterPassword"); if(userName != ""&&userSex != ""&&userPassword != ""){ Level level = new Level(null, null, request.getParameter("regigterPhone"), userFID, null,null); levelService.insertRecord(level); User user = new User(); user.setuName(userName); user.setuPhone(userPhone); user.setuPassword("123456"); user.setuSex(userSex); user.setuID(userID); user.setuLevel(userLevel); user.setuAdress(userAdress); user.setuRegistTime(df.format(new Date())); //System.out.println(user); userService.insertUser(user,userFID); userCount(request,response); //request.getRequestDispatcher("/WEB-INF/page/login.jsp").forward(request, response); } } /** * 跳转到主页 */ protected void zhuye(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { List<WineInfo> wineInfos = wineInfoService.getWineInfoAll(); request.setAttribute("wineInfos", wineInfos); request.getRequestDispatcher("/WEB-INF/page/content.jsp").forward(request, response); return; } /** * 验证用户登录 * @author jingluo * @param request * @param response * @throws IOException * @throws ServletException */ protected void denglu(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Integer i = null; String userID = ""; String userStatus = ""; String userphone = request.getParameter("username"); String userPassword = request.getParameter("password").trim(); String selectWay = request.getParameter("selectWay"); if("".equals(userphone.trim()) || "".equals(userPassword.trim())){ request.getRequestDispatcher("/WEB-INF/page/login.jsp").forward(request, response); } if("手机号".equals(selectWay)){ userID = (String) userService.selectUserID(userphone); List<User> userInfo = userService.getUserAll(userphone,userID); if(!userInfo.isEmpty()){ userStatus = userInfo.get(0).getuStatus(); } if("1".equals(userStatus)){ User user = new User(); user.setuPhone(userphone); user.setuID(userPassword); i = userService.login(user); } } if("身份证".equals(selectWay)){ userID = userphone; List<User> userInfo = userService.getUserAll(userphone,userID); if(!userInfo.isEmpty()){ userStatus = userInfo.get(0).getuStatus(); } if("1".equals(userStatus)){ User user = new User(); user.setuID(userID); user.setuPassword(userPassword); userphone = userInfo.get(0).getuPhone(); i = userService.logins(user); } } if (i != null) { if (null == String.valueOf(userphone) || "".equals(userPassword.trim())) { request.getRequestDispatcher("/WEB-INF/page/login.jsp").forward(request, response); return; } List<WineInfo> wineInfos = wineInfoService.getWineInfoAll(); request.setAttribute("wineInfos", wineInfos); int goodAmount = shopCartService.getGoodAmount(userID); String level = (String) userService.selectUserInforLevel(userphone); request.getSession().setAttribute("level", level); request.getSession().setAttribute("goodAmount", goodAmount); request.getSession().setAttribute("userName", userService.selectUserInfor(userphone)); // 登陆成功后将用户名保存到session中,在整个会话期间都可以访问到 request.getSession().setAttribute("userID", userID); request.getSession().setAttribute("userphone", userphone); List<Settlement> list = settlementService.getSettleInfoAll("", "", "", userID, ""); double deposit = 0; if(list.size()>0) { deposit = list.get(0).getS_deposit(); } request.getSession().setAttribute("deposit", deposit); if("18315969275".equals(userphone)){ String currPage = request.getParameter("currPage"); //获取总数量 int pageCount = userService.getUserCount(""); int pagesize=10; // 当前页变量 Integer iCurrPage = null; if (currPage != null) { iCurrPage = Integer.parseInt(currPage); } else { iCurrPage = 1; // 没有指定显示哪页时,默认显示第1页 } Page page=new Page(pageCount, iCurrPage, pagesize); List<User> users = userService.getUserInfoAll("1",page); //System.out.println(users); request.setAttribute("page", page); request.setAttribute("users", users); request.getRequestDispatcher("/WEB-INF/admin/massage.jsp").forward(request, response); }else{ request.getRequestDispatcher("/WEB-INF/page/content.jsp").forward(request, response); } return; } request.setAttribute("error", "请检查账号是否正确,或者是否激活"); request.getRequestDispatcher("/WEB-INF/page/login.jsp").forward(request, response); return; } /** * 跳转到账户页面 * @author jingluo * @param request * @param response * @throws IOException * @throws ServletException */ protected void userCount(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String next1 = ""; String next2 =""; // 得到该用户的账户id String userphone = (String) request.getSession().getAttribute("userphone"); String userId = (String) request.getSession().getAttribute("userID"); //获得下级数量 Integer nextAmount = levelService.getNextAmount(userId); //获得上级的身份证号 String preUserID = levelService.getPreUserID(userId); if("".equals(preUserID)){ preUserID="无"; } if(nextAmount != 0){ //获取下级身份证号 List<String> nextID = levelService.getNextIds(userId); if(!nextID.isEmpty()){ request.setAttribute("nextIds", nextID); request.setAttribute("nName1", userService.selectUserInfors(nextID.get(0))); } else request.setAttribute("nextIds", "无"); //获取下下级身份证 if(nextID != null && nextID.size() >= 2){ next1 = nextID.get(0); next2 = nextID.get(1); } //第一个下级用户的下级 List<String> nnextID1 = levelService.getNextIds(next1); request.setAttribute("nnextID1", nnextID1); if(!nnextID1.isEmpty()){ request.setAttribute("nnextID1", nnextID1); } else request.setAttribute("nnextID1", "无"); //第二个下级用户的下级 List<String> nnextID2 = levelService.getNextIds(next2); if(!nnextID2.isEmpty()){ request.setAttribute("nnextID2", nnextID2); } else request.setAttribute("nnextID2", "无"); }else { request.setAttribute("nextIds", "无"); request.setAttribute("nnextID1", "无"); request.setAttribute("nnextID2", "无"); } // 查询该用户的账户余额 List<Settlement> acounts = settlementService.acounts(userId); //System.out.println(userId + "........" + acounts); // // 将查询结果显示在前端页面 request.getSession().setAttribute("userName", userService.selectUserInfor(userphone)); request.setAttribute("userTime", userService.selectUserTime(userphone)); //System.out.println(userService.selectUserTime(userphone)); for(Settlement acount:acounts){ request.setAttribute("acount", acount); } // 转发到我的账户页面 request.setAttribute("preUserID", preUserID); request.setAttribute("nextAmount", nextAmount); request.getRequestDispatcher("/WEB-INF/page/userAcount.jsp").forward(request, response); } /** * 跳转到金额明细 */ protected void showAcount(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String userId = (String) request.getSession().getAttribute("userID"); List<Settlement> acounts = settlementService.acounts(userId); for(Settlement acount:acounts){ request.setAttribute("acount", acount); } request.getRequestDispatcher("/WEB-INF/page/showAcount.jsp").forward(request, response); return; } /** * 跳转到等级页面 */ protected void showLevel(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String userId = (String) request.getSession().getAttribute("userID"); String userName = (String) userService.selectUserInfors(userId); request.setAttribute("username", userName); request.setAttribute("userID", userId); Integer lNumber = 0; Integer rNumber = 0; float lAccount = 0; float rAccount = 0; //获取一级下级 List<String> nextID = levelService.getNextIds(userId); //System.out.println("test........" + nextID.get(0)); if(nextID.size() > 0 && (nextID.get(0) != null)){ //lNumber += 1; lNumber = selectChildAmount(nextID.get(0)); lAccount = selectChildAccount(nextID.get(0)); request.setAttribute("nextID1", nextID.get(0)); request.setAttribute("nName1", userService.selectUserInfors(nextID.get(0))); // //二级左侧 List<String> nnextIDl = levelService.getNextIds(nextID.get(0)); if(nnextIDl != null && nnextIDl.size() != 0){ //lNumber += nnextIDl.size(); for(String lID:nnextIDl){ List<String> lIDl = levelService.getNextIds(lID); if(lIDl.size() != 0 && lIDl != null){ //lNumber += lIDl.size(); /** * 递归算法 */ } } if(nnextIDl.size() > 0&&nnextIDl.get(0) != null){ request.setAttribute("nnextID1", nnextIDl.get(0)); request.setAttribute("nnName1", userService.selectUserInfors(nnextIDl.get(0))); } else{ request.setAttribute("nnextID1", "无"); request.setAttribute("nnName1", "无"); } if(nnextIDl.size() > 1) { if(nnextIDl.get(1) != null){ request.setAttribute("nnextID2", nnextIDl.get(1)); request.setAttribute("nnName2", userService.selectUserInfors(nnextIDl.get(1))); } else{ request.setAttribute("nnextID2", "无"); request.setAttribute("nnName2", "无"); } } } else{ request.setAttribute("nnextID1", "无"); request.setAttribute("nnName1", "无"); request.setAttribute("nnextID2", "无"); request.setAttribute("nnName2", "无"); } } else{ request.setAttribute("nextID1", "无"); request.setAttribute("nName1", "无"); } if(nextID.size() > 1 && nextID.get(1) != null){ //rNumber += 1; rNumber = selectChildAmount(nextID.get(nextID.size()-1)); rAccount = selectChildAccount(nextID.get(nextID.size()-1)); request.setAttribute("nextID2", nextID.get(nextID.size()-1)); request.setAttribute("nName2", userService.selectUserInfors(nextID.get(nextID.size()-1))); //获取二级下级右 List<String> nnextIDr = levelService.getNextIds(nextID.get(nextID.size()-1)); if(nnextIDr.size() != 0){ //rNumber += nnextIDr.size(); for(String lID:nnextIDr){ List<String> lIDl = levelService.getNextIds(lID); if(lIDl.size() != 0 && lIDl != null){ //rNumber += lIDl.size(); } } if(nextID.get(0) != null){ request.setAttribute("nnextID3", nnextIDr.get(0)); request.setAttribute("nnName3", userService.selectUserInfors(nnextIDr.get(0))); } else{ request.setAttribute("nnextID3", "无"); request.setAttribute("nnName3", "无"); } if(nnextIDr.size() > 1) { if(nextID.get(1) != null){ request.setAttribute("nnextID4", nnextIDr.get(nnextIDr.size()-1)); request.setAttribute("nnName4", userService.selectUserInfors(nnextIDr.get(nnextIDr.size()-1))); } else{ request.setAttribute("nnextID4", "无"); request.setAttribute("nnName4", "无"); } } } else{ request.setAttribute("nnextID3", "无"); request.setAttribute("nnName3", "无"); request.setAttribute("nnextID4", "无"); request.setAttribute("nnName4", "无"); } } else{ request.setAttribute("nextID2", "无"); request.setAttribute("nName2", "无"); } List<User> nextIDAlls = levelService.getNextIdAll(userId); request.setAttribute("nextIDAlls", nextIDAlls); request.setAttribute("lNumber", lNumber); request.setAttribute("rNumber", rNumber); request.setAttribute("lAccount", lAccount); request.setAttribute("rAccount", rAccount); request.getRequestDispatcher("/WEB-INF/page/showLevel.jsp").forward(request, response); return; } //递归找到孩子数量 public Integer selectChildAmount(String userId){ Integer amount = f(userId); return amount; } public Integer f(String userId){ if(userId == null || (userId.trim().equals(""))){ return 0; } Integer l = f(levelService.getNextLeftId(userId)); Integer r = f(levelService.getNextRightId(userId)); return l+r+1; } //递归查询孩子等级 public float selectChildAccount(String userId){ float account = findAcount(userId); return account; } public float findAcount(String userId){ if(userId == null || (userId.trim().equals(""))){ return 0; } float account = 0; String level = levelService.getLevelById(userId); account = AccountLevel(level); float l = findAcount(levelService.getNextLeftId(userId)); float r = findAcount(levelService.getNextRightId(userId)); return l+r+account; } public float AccountLevel(String userLevel){ float a=0; if(userLevel=="业务员"||"业务员".equals(userLevel)){ a =2000; } if(userLevel=="代理商"||"代理商".equals(userLevel)){ a =10000; } if(userLevel=="销售经理"||"销售经理".equals(userLevel)){ a =30000; } if(userLevel=="销售总监"||"销售总监".equals(userLevel)){ a =50000; } return a; } //递归找到下级 public Integer checkALIDs(String userId,String ChangeID){ ChangedFID = ChangeID; Integer amount = checkIDs(userId); return amount; } private static Integer i = 0; public Integer checkIDs(String userId){ if(userId == null || (userId.trim().equals(""))){ return 0; } checkIDs(levelService.getNextLeftId(userId)); checkIDs(levelService.getNextRightId(userId)); if(ChangedFID.equals(userId)||ChangedFID == userId){ i=1; } return i; } /** * 查询是否属于本人下级 */ protected void checkALID(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException { String userId = (String) request.getSession().getAttribute("userID"); String ChangeID = request.getParameter("ChangeFID"); String msg = "false"; if(!"".equals(userId)&&!"".equals(ChangeID)){ if(checkALIDs(userId,ChangeID)!=0){ msg="true"; } } response.setCharacterEncoding("UTF-8"); response.setContentType("text/javascript"); response.getWriter().print(msg); return; } /** * 更改父级 */ protected void updateFID(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException { String userID = request.getParameter("userID"); String ChargefID = request.getParameter("ChangeFID"); String ChargeFID = null; String msg = "false"; Check check = new Check(); check.setFID(ChargefID); Integer i = checkService.check(check); if(i==0&&(ChargefID!=null||!"".equals(ChargefID))){ if("".equals(levelService.getNextLeftId(ChargefID))||levelService.getNextLeftId(ChargefID)==null){ msg="true"; ChargeFID = ChargefID + "&L"; } else if("".equals(levelService.getNextRightId(ChargefID))||levelService.getNextRightId(ChargefID)==null){ msg="true"; ChargeFID = ChargefID + "&R"; } if("true".equals(msg)){ checkService.insertCheck(check); bonusService.updateRecord(userID, ChargefID); levelService.updateNID(ChargeFID, userID); } } response.setCharacterEncoding("UTF-8"); response.setContentType("text/javascript"); response.getWriter().print(msg); return; } /** * 实现晋级功能 * @author jingluo * @param request * @param response * @throws IOException * @throws ServletException */ public void promotion(String userId){ SimpleDateFormat df = new SimpleDateFormat("yyy-MM-dd");//设置日期格式 // 得到该用户的账户id String level = ""; // 查询该用户的账户余额 List<Settlement> acounts = settlementService.acounts(userId); for(Settlement acount:acounts){ boolean i =false; Promotion promotion = new Promotion(); level = acount.getS_level(); if("业务员".equals(acount.getS_level()) && acount.getS_balance() >= 40000 ) { System.out.println("晋级成功,您已成功晋级代理商"); level = "代理商"; i = true; } else if("代理商".equals(acount.getS_level()) && acount.getS_balance() >= 120000.0) { System.out.println("晋级成功,您已成功晋级销售经理"); level = "销售经理"; i = true; } else if("销售经理".equals(acount.getS_level()) && acount.getS_balance() >= 200000.0) { System.out.println("晋级成功,您已成功晋级销售总监"); level = "销售总监"; i = true; } else if("销售总监".equals(acount.getS_level())){ System.out.println("您已为最高级别"); } else{ //System.out.println(acount.getS_level()+" "+acount.getS_total()+" "+acount.getS_Winconsume()+" "+acount.getS_Deconsume()); System.out.println("晋级条件不符合!!!"); } if(i){ promotion.setP_ID(userId); promotion.setP_level(level); promotion.setP_olevel(acount.getS_level()); promotion.setP_date(df.format(new Date())); promotionService.update(promotion); settlementService.UpdateLevel(level, userId); } } } /** * 实现更新身份证功能 * @author jingluo * @param request * @param response * @throws IOException * @throws ServletException */ // protected void updateID(HttpServletRequest request, HttpServletResponse response) // throws IOException, ServletException { // // 得到该用户的账户id // String userphone = (String) request.getSession().getAttribute("userphone"); // String userID = request.getParameter("acountUserID"); // String userLevel = request.getParameter("acountLevel"); // System.out.println("级别" + userLevel); // if(userID==null){ // System.out.println(request.getParameter("acountUserID")); // } // else{ // boolean i = userService.updateID(userphone,userID,userLevel,userID); // if(i){ // System.out.println(request.getParameter("acountUserID")); // request.getSession().setAttribute("userID", userID); // List<WineInfo> wineInfos = wineInfoService.getWineInfoAll(); // request.setAttribute("wineInfos", wineInfos); // request.getRequestDispatcher("/WEB-INF/page/content.jsp").forward(request, response); // } // } // } /** * 我的购物车跳转方法,跳转到购物车页面 * @param request * @param response * @throws ServletException * @throws IOException */ protected void myShopCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int goodAmount = shopCartService.getGoodAmount((String)request.getSession().getAttribute("userID")); request.getSession().setAttribute("goodAmount", goodAmount); List<ShopCart> list = shopCartService.getMyShopCart((String)request.getSession().getAttribute("userID")); request.setAttribute("list", list); request.getRequestDispatcher("WEB-INF/page/shopCart.jsp").forward(request, response); } /** * 跳转到添加银行卡页面 */ protected void addCard(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userId = (String) request.getSession().getAttribute("userID"); Card card = null; if((card = userService.selectCard(userId)) != null){ request.setAttribute("cardNumber", card.getCard_number()); request.setAttribute("cardAddress", card.getCard_address()); } request.getRequestDispatcher("WEB-INF/page/addCard.jsp").forward(request, response); } /** * 更新用户密码 */ protected void updatePassword(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException { String userId = (String) request.getSession().getAttribute("userID"); String newPassword = request.getParameter("newPassword"); //更新密码 userService.updatePassword(userId,newPassword); response.setCharacterEncoding("UTF-8"); response.setContentType("text/javascript"); response.getWriter().print(""); return; } /** * 充值 */ protected void Recharge(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException { String userId = (String) request.getSession().getAttribute("userID"); String userName = (String) request.getSession().getAttribute("userName"); String Recharge = request.getParameter("Recharge"); String Ordernumber = request.getParameter("Ordernumber"); String msg = "false"; if(!"".equals(Recharge)&&!"".equals(userId)&&!"".equals(userName)&&!"".equals(Ordernumber)){ userService.Recharge(userId,Recharge,userName,"",Ordernumber); msg = "true"; } else msg = "false"; response.setCharacterEncoding("UTF-8"); response.setContentType("text/javascript"); response.getWriter().print(msg); return; } /** * 添加或更新银行卡号 */ protected void updateCard(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException { String userId = (String) request.getSession().getAttribute("userID"); String cardNumber = request.getParameter("cardNumber"); String cardAddress = new String(request.getParameter("cardAddress")); Card card = new Card(userId, cardNumber, cardAddress); if(userService.selectCard(userId) == null){ //没有记录,插入 userService.insertCard(card); }else{ //更新 userService.updateCard(card); } request.setAttribute("cardNumber", cardNumber); request.setAttribute("cardAddress", cardAddress); request.getRequestDispatcher("WEB-INF/page/addCard.jsp").forward(request, response); } /** * 提现 * @param request * @param response * @throws ServletException * @throws IOException */ protected void myCash(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { double useracount = 0.0; double limit = 0.0; double deconsume = 0.0; String userId = (String) request.getSession().getAttribute("userID"); String userName = (String) request.getSession().getAttribute("userName"); Card card = userService.selectCard(userId); String Msg = ""; if(card != null){ try { String level = (String) request.getSession().getAttribute("level"); //判断提现限制 switch(level){ case "业务员": limit = 30000; case "代理商": limit = 70000; } List<Settlement> acounts = settlementService.acounts(userId); for(Settlement acount:acounts){ useracount = acount.getS_total(); deconsume = acount.getS_Deconsume(); } double cash = Integer.valueOf(request.getParameter("userCash")) ; if(useracount > cash){ userService.insertCash(card,cash,userName); settlementService.updatecash(userId, useracount,cash); Msg = "true"; } else Msg = "false"; } catch (Exception e) { e.printStackTrace(); } }else{ Msg = "false"; } // List<WineInfo> wineInfos = wineInfoService.getWineInfoAll(); // request.setAttribute("wineInfos", wineInfos); response.setCharacterEncoding("UTF-8"); response.setContentType("text/javascript"); response.getWriter().print(Msg); return; } }
true
c95f4c62c703db87a8bdeddaabb9af51afdc03b3
Java
luozhanming/DesignPatternSampleDemo
/app/src/main/java/luozm/designpatternsampledemo/chainofresponsibility/PanLoader.java
UTF-8
1,131
2.984375
3
[]
no_license
package luozm.designpatternsampledemo.chainofresponsibility; /** * Created by cdc4512 on 2018/2/6. */ public abstract class PanLoader { protected PanLoader nextPanLoader; protected String name; protected int responsiblity; public static final int COACH = 1; public static final int SCORE = 2; public static final int DEFENSE = 3; public PanLoader(int responsiblity) { this.responsiblity = responsiblity; } public void setNextPanLoader(PanLoader loader) { this.nextPanLoader = loader; } public abstract String getName(); public String findRealPanLoader(int responsiblity) { if (this.responsiblity == responsiblity) { return loadPan(); } else { if (nextPanLoader != null) { return throwPan()+nextPanLoader.findRealPanLoader(responsiblity); }else{ return throwPan()+"没人肯背锅!!!"; } } } private String loadPan(){ return getName()+"背锅!!!\n"; } private String throwPan(){ return getName()+"甩锅!!\n"; } }
true
a090185876d9660de3dd09bc1c0a5d57ab33ee53
Java
HarisDelalic/design_patterns
/src/main/java/behavioral/mediator/Commandable.java
UTF-8
331
2.40625
2
[]
no_license
package main.java.behavioral.mediator; import main.java.behavioral.mediator.models.ArmedUnit; public interface Commandable { void addArmedUnit(ArmedUnit armedUnit); boolean getCanAttack(); void setCanAttack(boolean canAttack); void startAttack(ArmedUnit armedUnit); void ceaseAttack(ArmedUnit armedUnit); }
true
5a901111c95c30f4fc94a63ba533434429c19f3c
Java
adrianmircor/Prenda-Imagen-Rest
/src/main/java/com/Cloudinary_Rest/repository/BoletaRepository.java
UTF-8
284
1.664063
2
[]
no_license
package com.Cloudinary_Rest.repository; import com.Cloudinary_Rest.entity.Boleta; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface BoletaRepository extends JpaRepository<Boleta,Integer> { }
true
8df1bc29085ce02f39fd49235156910a07600ab2
Java
shuaidd/amazon-partner-api
/aspi-spring-boot-model/src/main/java/com/github/shuaidd/aspi/model/apluscontent/StandardThreeImageTextModule.java
UTF-8
3,989
2.484375
2
[ "MIT" ]
permissive
/* * Selling Partner API for A+ Content Management * With the A+ Content API, you can build applications that help selling partners add rich marketing content to their Amazon product detail pages. A+ content helps selling partners share their brand and product story, which helps buyers make informed purchasing decisions. Selling partners assemble content by choosing from content modules and adding images and text. * * OpenAPI spec version: 2020-11-01 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package com.github.shuaidd.aspi.model.apluscontent; import com.google.gson.annotations.SerializedName; import java.util.Objects; /** * Three standard images with text, presented across a single row. */ public class StandardThreeImageTextModule { @SerializedName("headline") private TextComponent headline = null; @SerializedName("block1") private StandardImageTextBlock block1 = null; @SerializedName("block2") private StandardImageTextBlock block2 = null; @SerializedName("block3") private StandardImageTextBlock block3 = null; public StandardThreeImageTextModule headline(TextComponent headline) { this.headline = headline; return this; } /** * Get headline * @return headline **/ public TextComponent getHeadline() { return headline; } public void setHeadline(TextComponent headline) { this.headline = headline; } public StandardThreeImageTextModule block1(StandardImageTextBlock block1) { this.block1 = block1; return this; } /** * Get block1 * @return block1 **/ public StandardImageTextBlock getBlock1() { return block1; } public void setBlock1(StandardImageTextBlock block1) { this.block1 = block1; } public StandardThreeImageTextModule block2(StandardImageTextBlock block2) { this.block2 = block2; return this; } /** * Get block2 * @return block2 **/ public StandardImageTextBlock getBlock2() { return block2; } public void setBlock2(StandardImageTextBlock block2) { this.block2 = block2; } public StandardThreeImageTextModule block3(StandardImageTextBlock block3) { this.block3 = block3; return this; } /** * Get block3 * @return block3 **/ public StandardImageTextBlock getBlock3() { return block3; } public void setBlock3(StandardImageTextBlock block3) { this.block3 = block3; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } StandardThreeImageTextModule standardThreeImageTextModule = (StandardThreeImageTextModule) o; return Objects.equals(this.headline, standardThreeImageTextModule.headline) && Objects.equals(this.block1, standardThreeImageTextModule.block1) && Objects.equals(this.block2, standardThreeImageTextModule.block2) && Objects.equals(this.block3, standardThreeImageTextModule.block3); } @Override public int hashCode() { return Objects.hash(headline, block1, block2, block3); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class StandardThreeImageTextModule {\n"); sb.append(" headline: ").append(toIndentedString(headline)).append("\n"); sb.append(" block1: ").append(toIndentedString(block1)).append("\n"); sb.append(" block2: ").append(toIndentedString(block2)).append("\n"); sb.append(" block3: ").append(toIndentedString(block3)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
true
1f7073bd8e353f0dfcf7471111e8214c88e349e9
Java
OnlineCodex/OnlineCodex
/src/main/java/oc/wh40k/units/or/ORKillTank.java
UTF-8
1,596
1.992188
2
[]
no_license
package oc.wh40k.units.or; import oc.Eintrag; import oc.OptionsGruppeEintrag; import oc.OptionsUpgradeGruppe; import oc.OptionsZaehlerGruppe; public class ORKillTank extends Eintrag { private final OptionsUpgradeGruppe tech, o1; public ORKillTank() { grundkosten = getPts("Kill Tank"); power = 15; name = "Kill Tank"; add(ico = new oc.Picture("oc/wh40k/images/Pikk-Up.gif")); seperator(); ogE.addElement(new OptionsGruppeEintrag("Twin big shoota", getPts("Twin big shoota"))); add(o1 = new OptionsUpgradeGruppe(ID, randAbstand, cnt, "", ogE, 1)); seperator(); ogE.addElement(new OptionsGruppeEintrag("Bursta kannon", getPts("Bursta kannon"))); ogE.addElement(new OptionsGruppeEintrag("Giga shoota", getPts("Giga shoota"))); add(tech = new OptionsUpgradeGruppe(ID, randAbstand, cnt, "", ogE, 1)); seperator(); ogE.addElement(new OptionsGruppeEintrag("Big shoota", getPts("Big shoota"))); ogE.addElement(new OptionsGruppeEintrag("Skorcha", getPts("Skorcha"))); ogE.addElement(new OptionsGruppeEintrag("Rokkit launcha", getPts("Rokkit launcha"))); ogE.addElement(new OptionsGruppeEintrag("Twin big shoota", getPts("Twin big shoota"))); ogE.addElement(new OptionsGruppeEintrag("Rack of rokkits", getPts("Rack of rokkits"))); add(new OptionsZaehlerGruppe(ID, randAbstand, cnt, "", ogE, 2)); complete(); } // @OVERRIDE @Override public void refreshen() { tech.alwaysSelected(); o1.alwaysSelected(); } }
true
7e6b274069a4540a935184d406d279eb08ffa22e
Java
zhaochong87/spring-data-jdbc-demo-1
/spring-data-jdbc-demo/src/main/java/com/example/demo/AuthorRef.java
UTF-8
385
2.203125
2
[]
no_license
package com.example.demo; import lombok.EqualsAndHashCode; import lombok.ToString; import org.springframework.data.relational.core.mapping.Table; @EqualsAndHashCode @ToString @Table("Book_Author") public class AuthorRef { private Long author; public AuthorRef(Long author) { this.author = author; } public Long getAuthor() { return author; } }
true
eac72132d9c4e2ee5108c3f6de149dde6d436eeb
Java
saaserp/Zichanguanliu-Client
/src/com/qufei/model/ProductModel.java
UTF-8
903
2.203125
2
[]
no_license
package com.qufei.model; import com.qufei.tools.Model; public class ProductModel extends Model { String pTypeID; public ProductModel(String pTypeID, String attribute, String typeName, String father) { super(); this.pTypeID = pTypeID; this.attribute = attribute; this.typeName = typeName; this.father = father; } public String getpTypeID() { return pTypeID; } public void setpTypeID(String pTypeID) { this.pTypeID = pTypeID; } public String getAttribute() { return attribute; } public void setAttribute(String attribute) { this.attribute = attribute; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public String getFather() { return father; } public void setFather(String father) { this.father = father; } String attribute; String typeName; String father; }
true
32f5cc49756818d5e601471e6d19289b3f9dad1e
Java
xxsheng/spring-source-analysis
/src/main/java/nio1/Client.java
UTF-8
2,345
2.859375
3
[]
no_license
package nio1; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.nio.charset.StandardCharsets; import java.util.Iterator; import java.util.Set; public class Client { public static void main(String[] args) throws IOException { InetSocketAddress inetSocketAddress = new InetSocketAddress(InetAddress.getLocalHost(), 9092); SocketChannel socketChannel = SocketChannel.open(); Selector selector = Selector.open(); socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT); socketChannel.connect(inetSocketAddress); while (true) { while (selector.select() >0) { Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = selectionKeys.iterator(); while (iterator.hasNext()) { SelectionKey selectionKey = iterator.next(); iterator.remove(); if (selectionKey.isConnectable()) { SocketChannel channel = (SocketChannel) selectionKey.channel(); channel.finishConnect(); selectionKey.interestOps(SelectionKey.OP_READ); System.out.println("connectd"); } else if (selectionKey.isReadable()) { SocketChannel channel = (SocketChannel) selectionKey.channel(); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); channel.read(byteBuffer); byteBuffer.flip(); String receiveData = StandardCharsets.UTF_8.decode(byteBuffer).toString(); System.out.println("client" + receiveData); ByteBuffer byteBuffer1 = ByteBuffer.allocate(60); byteBuffer1.put("data Received".getBytes()); byteBuffer1.flip(); channel.write(byteBuffer1); } } } } } }
true
f8a5b07902e391443c8d567e8ed4ee4fe5ea2a76
Java
Tsaplin/2020-11-otus-spring-Tsaplin
/2020-11/spring-13/spring-13-exercise/src/main/java/ru/otus/spring/dao/BookDao.java
UTF-8
537
2.03125
2
[]
no_license
package ru.otus.spring.dao; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.transaction.annotation.Transactional; import ru.otus.spring.domain.Book; import java.util.List; import java.util.Optional; public interface BookDao extends MongoRepository<Book, String>, BookDaoCustom { @Transactional(readOnly = true) Optional<Book> findFirstByNameEquals(String bookName); @Transactional(readOnly = true) List<Book> findBooksByAuthorNotNullAndGenreNotNull(); }
true
6a7584f22377efad2824956fff62b1eb47834e31
Java
andykeem/spring-mvc-demo
/src/loc/example/springdemo/mvc/StudentController.java
UTF-8
2,494
2.546875
3
[]
no_license
package loc.example.springdemo.mvc; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.validation.Valid; import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import loc.example.springdemo.mvc.model.Country; import loc.example.springdemo.mvc.model.Log; import loc.example.springdemo.mvc.model.Student; @Controller @RequestMapping(path = "/student") public class StudentController { @InitBinder public void initBinder(WebDataBinder binder) { StringTrimmerEditor editor = new StringTrimmerEditor(true); binder.registerCustomEditor(String.class, editor); } @RequestMapping(path = "show-form") public String showForm(Model model) { Student stud = new Student(); model.addAttribute("student", stud); List<Country> countryList = getCountryList(); model.addAttribute("countryList", countryList); Map<String, String> languages = getProgLanguages(); model.addAttribute("languages", languages); List<String> osList = getOperatingSystems(); model.addAttribute("osList", osList); return "student/show-form"; } @RequestMapping(path = "process-form", method = RequestMethod.POST) public String processForm(@Valid @ModelAttribute("student") Student student, BindingResult result) { Log.d("student processForm() method called.."); Log.d("student: " + student); if (result.hasErrors()) { return "student/show-form"; } return "student/process-form"; } private List<Country> getCountryList() { return List.of( new Country("Brazil", "Brazil"), new Country("England", "England"), new Country("France", "France"), new Country("Germany", "Germany") ); } @ModelAttribute("languages") private Map<String, String> getProgLanguages() { Map<String, String> map = new HashMap<>(); map.put("C#", "C#"); map.put("Java", "Java"); map.put("Python", "Python"); map.put("Ruby", "Ruby"); return map; } @ModelAttribute("osList") private List<String> getOperatingSystems() { return List.of("Linux", "Mac OS", "MS Windows"); } }
true
a1b3283353be09e327ebcdbd17e63a4c2efc7f87
Java
YeonjungJo/baekjoon
/src/baekjoon/solve/basic/DynamicProgramming.java
UTF-8
1,260
3.4375
3
[]
no_license
package baekjoon.solve.basic; import java.util.Scanner; public class DynamicProgramming { private static final Scanner sc = new Scanner(System.in); private static final int R = 0; private static final int G = 1; private static final int B = 2; private void solve() { int n = sc.nextInt(); int[][] rgb = new int[n][3]; for (int i = 0; i < n; i++) { for (int j = 0; j < 3; j++) { rgb[i][j] = sc.nextInt(); } } int[][] d = new int[n][3]; int min = Integer.MAX_VALUE; for (int i = 0; i < 3; i++) { int tmp = getRGB(rgb, d, 0, i); min = tmp > min ? min : tmp; } System.out.println(min); } private int getRGB(int[][] rgb, int[][] d, int i, int color) { if (i == d.length - 1) return rgb[i][color]; if (color == R) return d[i][R] = rgb[i][R] + min(getRGB(rgb, d, i + 1, G), getRGB(rgb, d, i + 1, B)); if (color == G) return d[i][G] = rgb[i][G] + min(getRGB(rgb, d, i + 1, R), getRGB(rgb, d, i + 1, B)); if (color == B) return d[i][B] = rgb[i][B] + min(getRGB(rgb, d, i + 1, R), getRGB(rgb, d, i + 1, G)); return 0; } private int min(int i, int j) { return i > j ? j : i; } public static void main(String[] args) { new DynamicProgramming().solve(); } }
true
907932dfcb8202754b70402e7d626a18cfcfe7a6
Java
ajithcpas/note-it
/src/main/java/com/noteit/auth/authorization/PasswordTokenRepository.java
UTF-8
323
1.90625
2
[ "Apache-2.0" ]
permissive
package com.noteit.auth.authorization; import com.noteit.auth.Users; import org.springframework.data.repository.CrudRepository; public interface PasswordTokenRepository extends CrudRepository<PasswordResetToken, Long> { PasswordResetToken findByToken(String token); PasswordResetToken findByUser(Users user); }
true
43b1a877b4b06401384056d32237a94637566653
Java
CodeKarRohan/coding-practice
/src/main/java/com/rnl/prc/array/BubbleSort.java
UTF-8
1,520
2.96875
3
[]
no_license
package com.rnl.prc.array; import org.omg.Messaging.SYNC_WITH_TRANSPORT; public class BubbleSort { public static void main(String[] args){ int[] a = {12,22,25,11,64,0}; bubbleSort(a); ArrayCoding.printArray(a); } public static void printSom(int n){ if (n <= 1 ){ System.out.print(n+" "); return; } printSom(n-1); printSom(n-1); System.out.print(n+" "); } public static int[] bubbleSort(int[] a){ printSom(5); boolean swap = false; int[] lis = new int[a.length]; for (int i =0; i < lis.length ; i++) lis[i] = 1; for (int i =1 ; i<a.length;i++){ for (int j =0 ; j < i ; j++){ if (a[i] > a[j] && lis[i] < lis[j]+1){ lis[i] = lis[j] +1; } } } int max = lis[0]; for(int i =0; i < lis.length; i++){ if (lis[i] > max){ max = lis[i]; } } System.out.println(max); for (int i = 0 ; i < a.length -1; i++) { swap = false; for (int j = 0; j < a.length - i - 1; j++){ System.out.println("i : "+i+" j: "+j); if (a[j] > a[j+1]){ int temp = a[j] ; a[j] = a[j+1]; a[j+1] = temp; swap = true; } } if (!swap) return a; } return a; } }
true
42b585dc870e4e7a25354320f90d194275145142
Java
xZise/Voteik
/src/main/java/de/xzise/bukkit/voteik/commands/VoteListCommand.java
UTF-8
2,746
2.828125
3
[]
no_license
package de.xzise.bukkit.voteik.commands; import java.util.Arrays; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import de.xzise.MinecraftUtil; import de.xzise.bukkit.voteik.Vote; import de.xzise.bukkit.voteik.VoteManager; import de.xzise.commands.CommonHelpableSubCommand; public class VoteListCommand extends CommonHelpableSubCommand { private final VoteManager manager; public VoteListCommand(VoteManager manager) { super("list", "ls"); this.manager = manager; } public String[] getFullHelpText() { return new String[] { "List the votes." }; } public String getSmallHelpText() { return "List votes"; } public String getCommand() { return "vote list [#page]"; } private static String truncate(String string, int charCount, String truncAppendix) { if (string.length() <= charCount) { return string; } else { int truncLength = truncAppendix.length(); return string.substring(0, charCount - truncLength) + truncAppendix; } } public boolean execute(CommandSender sender, String[] parameters) { Integer page = null; if (parameters.length == 2) { page = MinecraftUtil.tryAndGetInteger(parameters[1]); } if (parameters.length == 1 || page != null) { page = page == null ? 1 : page; int maxiumumLines = MinecraftUtil.getMaximumLines(sender) - 1; List<Vote> votes = this.manager.getSortedVotes((page - 1) * maxiumumLines, maxiumumLines); if (votes.size() == 0) { sender.sendMessage(ChatColor.RED + "No votes to list."); } else { int idWith = -1; for (Vote vote : votes) { idWith = Math.max(MinecraftUtil.getWidth(vote.getId(), 10), idWith); } // 40 is width ingame, subtract 1 for the # and 1 for the space // #<id>␣<question> int questionWidth = 40 - idWith - 1 - 1; sender.sendMessage("Votes:"); for (Vote vote : votes) { String question = truncate(vote.getQuestion(), questionWidth, "..."); char[] zeros = new char[idWith - MinecraftUtil.getWidth(vote.getId(), 10)]; Arrays.fill(zeros, '0'); sender.sendMessage("#" + new String(zeros) + vote.getId() + " " + question); } } return true; } else { return false; } } }
true
fe58a15cca8bd7f30cee255883039f88099d0580
Java
Neithenn/Java-Reportes
/Reportes/src/SERVLET/servlet_paneles.java
UTF-8
1,522
2.265625
2
[]
no_license
package SERVLET; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; import DAO.dao_login; /** * Servlet implementation class servlet_paneles */ @WebServlet("/servlet_paneles") public class servlet_paneles extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public servlet_paneles() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int id_user = Integer.parseInt(request.getParameter("user")); if (id_user != 0){ dao_login odao = new dao_login(); JSONObject ojson = new JSONObject(); ojson = odao.getCsids(id_user); if (ojson != null){ response.setContentType("application/json"); System.out.println(ojson.toString()); response.getWriter().write(ojson.toString()); } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
true
7e6477d03da66adab7c8d7261f3c8950f389999d
Java
kemalyayil/TestProject.java
/src/Day7/JavaArrays/Task1.java
UTF-8
308
2.71875
3
[]
no_license
package Day7.JavaArrays; import java.util.Arrays; public class Task1 { public static void main(String[] args) { byte[] byteArray = new byte[3]; byteArray[0] = 30; byteArray[1] = 20; byteArray[2] = 1; System.out.println(Arrays.toString(byteArray)); } }
true
56a3a2f798aef7163092d75026f25ca4d4fd8824
Java
VirunaD/Shradha
/ThreadConcept/src/com/csi/thread/ThreadPriorityConcept.java
UTF-8
583
3.140625
3
[]
no_license
package com.csi.thread; public class ThreadPriorityConcept extends Thread{ public void run() { System.out.println("running Thread name is: "+Thread.currentThread().getName()); System.out.println("running thread priority is: "+Thread.currentThread().getPriority()); } public static void main(String[] args) { // TODO Auto-generated method stub ThreadPriorityConcept tp=new ThreadPriorityConcept(); ThreadPriorityConcept tp1=new ThreadPriorityConcept(); tp.setPriority(Thread.MAX_PRIORITY); tp1.setPriority(Thread.MIN_PRIORITY); tp.start(); tp1.start(); } }
true
bd03dfbc2dfca735ffc795134017041ddb644eb9
Java
SEALABQualityGroup/E-Shopper
/items/src/main/java/it/univaq/ing/items/controller/ItemsController.java
UTF-8
6,760
2.328125
2
[]
no_license
package it.univaq.ing.items.controller; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import io.netty.handler.codec.http.HttpResponseStatus; import it.univaq.ing.items.ItemException; import it.univaq.ing.items.domain.Item; import it.univaq.ing.items.repository.ItemRepository; /** * * @author LC */ @RestController public class ItemsController { protected Logger logger = Logger.getLogger(ItemsController.class.getName()); protected ItemRepository itemRepository; @Autowired public ItemsController(ItemRepository itemRepository) { this.itemRepository = itemRepository; } @RequestMapping("/findItems/{idProduct}") public List<Item> getItemsByIdProduct(@PathVariable(value="idProduct") Long idProduct) { logger.info("START ItemsController --> getItemsByIdProduct"); List<Item> items = new ArrayList<Item>(); try{ items = itemRepository.getItemsByIdProduct(idProduct); }catch(DataAccessException e){ logger.info("ERROR ItemsController--> getItemsByIdProduct: "+ e.getMessage()); throw new ItemException("find item (where product) error", HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); } logger.info("END ItemsController --> getItemsByIdProduct"); return items; } @RequestMapping("/findItemsByIdCategory/{idCategory}") public List<Item> getItemsByIdCategory(@PathVariable(value="idCategory") Long idCategory) { logger.info("START ItemsController --> getItemsByIdCategory"); List<Item> items = new ArrayList<Item>(); try{ items = itemRepository.getItemsByIdCategory(idCategory); }catch(DataAccessException e){ logger.info("ERROR ItemsController--> getItemsByIdCategory: "+ e.getMessage()); throw new ItemException("find item (where category) error", HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); } logger.info("END ItemsController --> getItemsByIdCategory"); return items; } @RequestMapping("/findItemsRandomByProductId/{idProduct}") public List<Item> findItemsRandomByIdProduct(@PathVariable(value="idProduct") Long idProduct) { logger.info("START ItemsController --> findItemsRandomByIdProduct"); List<Item> items = new ArrayList<Item>(); try{ items = itemRepository.findItemsRandomByIdProduct(idProduct); }catch(DataAccessException e){ logger.info("ERROR ItemsController--> findItemsRandomByIdProduct: "+ e.getMessage()); throw new ItemException("find item random error", HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); } logger.info("END ItemsController --> findItemsRandomByIdProduct"); return items; } @RequestMapping("/findItem/{idItem}") public Item getItemById(@PathVariable(value="idItem") Long idItem) { logger.info("START ItemsController --> getItemById"); Item item = new Item(); try{ item = itemRepository.getItemById(idItem); }catch(DataAccessException e){ logger.info("ERROR ItemsController--> getItemById: "+ e.getMessage()); throw new ItemException("find item (where id) error", HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); } logger.info("END ItemsController --> getItemById"); return item; } @RequestMapping("/findItemByProductFilter/{idProduct}/{priceMin}/{priceMax}") public List<Item> findItemByProductFilter(@PathVariable(value="idProduct") Long idProduct, @PathVariable(value="priceMin") Long priceMin, @PathVariable(value="priceMax") Long priceMax) { logger.info("START ItemsController --> findItemByProductFilter"); List<Item> items = new ArrayList<Item>(); try{ items = itemRepository.findItemByProductFilter(idProduct, priceMin, priceMax); }catch(DataAccessException e){ logger.info("ERROR ItemsController --> findItemByProductFilter: "+ e.getMessage()); throw new ItemException("find item (where filter) error", HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); } logger.info("END ItemsController --> findItemByProductFilter"); return items; } @RequestMapping("/findItemByCategoryFilter/{idCategory}/{priceMin}/{priceMax}") public List<Item> findItemByCategoryFilter(@PathVariable(value="idCategory") Long idCategory, @PathVariable(value="priceMin") Long priceMin, @PathVariable(value="priceMax") Long priceMax) { logger.info("START ItemsController --> findItemByCategoryFilter"); List<Item> items = new ArrayList<Item>(); try{ items = itemRepository.findItemByCategoryFilter(idCategory, priceMin, priceMax); }catch(DataAccessException e){ logger.info("ERROR ItemsController --> findItemByCategoryFilter: "+ e.getMessage()); throw new ItemException("find item (where filter) error", HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); } logger.info("END ItemsController --> findItemByCategoryFilter"); return items; } @RequestMapping("/findItemsRandom") public List<Item> findItemRandom() { logger.info("START ItemsController --> findItemRandom"); List<Item> items = new ArrayList<Item>(); try{ items = itemRepository.findItemRandom(); }catch(DataAccessException e){ logger.info("ERROR ItemsController --> findItemRandom: "+ e.getMessage()); throw new ItemException("find item (radom item) error", HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); } logger.info("END ItemsController --> findItemRandom"); return items; } @RequestMapping("/findFeaturesItemRandom") public List<Item> findFeaturesItemRandom() { logger.info("START ItemsController --> findFeaturesItemRandom"); List<Item> items = new ArrayList<Item>(); try{ items = itemRepository.findFeaturesItemRandom(); }catch(DataAccessException e){ logger.info("ERROR ItemsController --> findFeaturesItemRandom: "+ e.getMessage()); throw new ItemException("find item features item random error", HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); } logger.info("END ItemsController --> findFeaturesItemRandom"); return items; } @RequestMapping(value="/updateItem", method = RequestMethod.POST) public Item updateItem(@RequestBody Item item){ logger.info("START ItemsController --> updateItem"); try{ logger.info("END ItemsController --> updateItem"); return itemRepository.save(item); }catch(DataAccessException e){ logger.info("ERROR ItemsController --> updateItem"+ e.getMessage()); throw new ItemException("updare item error", HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); } } }
true
f7e06ca32f636c29531446720c4b60cb1f353f1b
Java
firatkaya1/blog.kayafirat.com-Android-App
/app/src/main/java/com/kayafirat/blogkayafirat/ui/comment/CustomAdapter.java
UTF-8
1,572
2.25
2
[]
no_license
package com.kayafirat.blogkayafirat.ui.comment; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.kayafirat.blogkayafirat.R; import com.kayafirat.blogkayafirat.model.Comment; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class CustomAdapter extends BaseAdapter { LayoutInflater inflter; ArrayList<Comment> comments; public CustomAdapter(Context applicationContext, ArrayList<Comment> comments) { this.comments = comments; inflter = (LayoutInflater.from(applicationContext)); } @Override public int getCount() { return comments.size(); } @Override public Object getItem(int i) { return comments.get(i); } @Override public long getItemId(int i) { return Long.valueOf(comments.get(i).getCommentId()); } @Override public View getView(int i, View view, ViewGroup viewGroup) { view = inflter.inflate(R.layout.item_comment, null); TextView commentDetail = view.findViewById(R.id.commentDetail); TextView commentDate = view.findViewById(R.id.commentDate); TextView commentUsername = view.findViewById(R.id.commentUsername); commentDetail.setText(comments.get(i).getCommentBody()); commentDate.setText(comments.get(i).getCommentDate()); commentUsername.setText(comments.get(i).getUserName()); return view; } }
true
29de38256b1808ddbdb1e2c843d635af505c02d5
Java
Aruuke460/groupProject
/src/AAObjectClassPractice/Mysyk.java
UTF-8
219
2.53125
3
[]
no_license
package AAObjectClassPractice; public class Mysyk { String name; int age; String color; int weight; String breed; public void play(){ System.out.println("Mysyk is playing"); } }
true
a6f25906c2a192fa636d3c42b80cff787672f0ca
Java
hjnlxuexi/action4java
/Concurrent/src/main/java/hj/action/concurrent/JMM/DCL/Singleton.java
UTF-8
2,049
3.703125
4
[ "MIT" ]
permissive
package hj.action.concurrent.JMM.DCL; /** * <p>Title : JMM的双检查锁</p> * <p>Description : * 1、基于volatile的双检查锁单例模式,见:hj.action.concurrent.Volatile.DoubleCheckSingleton。 * 所采用的解决办法是:不允许初始化阶段步骤对象实例化时发生重排序 * * 2、另一种解决办法: * 允许初始化阶段步骤对象实例化时发生重排序,但是不允许其他线程“看到”这个重排序。 * * 利用classloder的机制来保证初始化instance时只有一个线程。JVM在类初始化阶段会获取一个锁,这个锁可以同步多个线程对同一个类的初始化。 * Java语言规定,对于每一个类或者接口C,都有一个唯一的初始化锁LC与之相对应。从C到LC的映射,由JVM的具体实现去自由实现。 * JVM在类初始化阶段期间会获取这个初始化锁,并且每一个线程至少获取一次锁来确保这个类已经被初始化过了。 * * * </p> * <p>Date : 2018/12/26 </p> * * @author : hejie */ public class Singleton { private Singleton(){ System.out.println("init"); } /** * 通过内部类 * 优点:只有主动调用内部类是才会被初始化,规避饿汉模式的空间浪费 */ private static class SingletonHolder{ SingletonHolder(){ System.out.println("init->inner"); } public static Singleton singleton = new Singleton(); } public static Singleton getInstance(){ return SingletonHolder.singleton; } /** * 通过私有的静态成员实现,叫做:饿汉模式 * 缺点:无论有没有被调用,都会初始化 */ private static Singleton singleton = new Singleton(); public static Singleton getInstance2(){ return Singleton.singleton; } public static void main(String[] args) { System.out.println("main....."); Singleton.getInstance();//此时初始化内部类 Singleton.getInstance(); } }
true
85b47cc775f13e0e6b19e9301f8e7d49d84c527d
Java
LDAforVisProject/VKPSA
/src/view/components/settingsPopup/SettingsPanel.java
UTF-8
15,653
2.015625
2
[ "MIT" ]
permissive
package view.components.settingsPopup; import java.net.URL; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.chart.NumberAxis; import javafx.scene.control.Accordion; import javafx.scene.control.CheckBox; import javafx.scene.control.ColorPicker; import javafx.scene.control.Slider; import javafx.scene.control.TextField; import javafx.scene.control.TitledPane; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.util.Pair; import view.components.DatapointIDMode; import view.components.VisualizationComponent; public class SettingsPanel extends VisualizationComponent { // ----------------------------------------------------------- // Properties // ----------------------------------------------------------- /* * Accordion and other elements for options section. */ /** * Accordion. */ private @FXML Accordion accordion_options; // Panes in accordion. /** * Accordion pane for global scatterchart and distance evaluation. */ private @FXML TitledPane mdsDistEval_titledPane; /** * Accordion pane for local scope visualization. */ private @FXML TitledPane localScope_titledPane; /** * Accordion pane for parameter space scatterchart. */ private @FXML TitledPane paramSpace_titledPane; /* * Controls for density heatmap in global scatterchart. */ /** * Checkbox for heatmap. */ private @FXML CheckBox globalScatterchartDHM_granularity_checkbox; /** * Slider specifying MDS heatmap granularity. */ private @FXML Slider globalScatterchartDHM_granularity_slider; /** * Specifies whether or not the MDS heatmap is to be shown. */ private @FXML CheckBox globalScatterplot_DHM_visibility_checkbox; /** * Color chooser for lower end of heatmap values. */ private @FXML ColorPicker mdsHeatmap_dhmColor_min_colChooser; /** * Color chooser for upper end of heatmap values. */ private @FXML ColorPicker mdsHeatmap_dhmColor_max_colChooser; /* * Constrols for distances barchart. */ /** * Indicates whether logarithmic axis should be used. */ private @FXML CheckBox distanceBarchart_logarithmicScaling_checkbox; /* * Controls for density heatmap in parameter space scatterchart. */ // ...for granularity. private @FXML CheckBox paramSpace_dhmGranularity_checkbox; private @FXML CheckBox paramSpace_dhmVisibility_checkbox; private @FXML Slider paramSpace_dhmGranularity_slider; // ...for category selection. private @FXML CheckBox paramSpace_dhmCategories_active_checkbox; private @FXML CheckBox paramSpace_dhmCategories_inactive_checkbox; private @FXML CheckBox paramSpace_dhmCategories_discarded_checkbox; // ...for color spectrum. /** * Color chooser for lower end of heatmap values. */ private @FXML ColorPicker paramSpace_dhmColor_min_colChooser; /** * Color chooser for upper end of heatmap values. */ private @FXML ColorPicker paramSpace_dhmColor_max_colChooser; /* * Controls for topic model comparison heatmap. */ /** * Color chooser for lower end of heatmap values. */ private @FXML ColorPicker tmc_color_min_colChooser; /** * Color chooser for lower end of heatmap values. */ private @FXML ColorPicker tmc_color_max_colChooser; /* * Options for local scope visualization. */ /** * Denotes number of keywords to show in visualization - in slider. */ private @FXML Slider slider_localScope_numKeywordsToUse; /** * Denotes number of keywords to show in visualization - in textfield. */ private @FXML TextField textfield_localScope_numKeywordsToUse; /* * Options for highlighting. */ private @FXML Slider defaultOpacity_slider; // ----------------------------------------------------------- // Methods // ----------------------------------------------------------- /** * Initializes settings panel. */ public void init() { // Init color chooser... // ...for param. space scatterchart: paramSpace_dhmColor_min_colChooser.setValue(Color.RED); paramSpace_dhmColor_max_colChooser.setValue(Color.DARKRED); // ...for topic model comparison: tmc_color_min_colChooser.setValue(Color.LIGHTBLUE); tmc_color_max_colChooser.setValue(Color.DARKBLUE); // ...for global scatterchart: mdsHeatmap_dhmColor_min_colChooser.setValue(Color.RED); mdsHeatmap_dhmColor_max_colChooser.setValue(Color.DARKRED); // Set properties for slider. slider_localScope_numKeywordsToUse.setSnapToTicks(true); slider_localScope_numKeywordsToUse.setMin(1); // Init event listener (e.g. for updates after slider changes). initEventListener(); } private void initEventListener() { /* * Event listener for global scatterchart's DHM granularity slider. */ globalScatterchartDHM_granularity_slider.addEventHandler(MouseEvent.MOUSE_RELEASED, new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { analysisController.changeGlobalScatterplotDHMGranularity(globalScatterchartDHM_granularity_checkbox.isSelected(), (int)globalScatterchartDHM_granularity_slider.getValue()); } }); // Add listener to determine position during mouse drag. globalScatterchartDHM_granularity_slider.addEventHandler(MouseEvent.MOUSE_DRAGGED, new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { analysisController.changeGlobalScatterplotDHMGranularity(globalScatterchartDHM_granularity_checkbox.isSelected(), (int)globalScatterchartDHM_granularity_slider.getValue()); }; }); /* * Event listener for parameter space scatterchart's DHM granularity slider. */ // Add listener to determine position during after release. paramSpace_dhmGranularity_slider.addEventHandler(MouseEvent.MOUSE_RELEASED, new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { analysisController.refreshParameterSpaceScatterchart(); } }); // Add listener to determine position during mouse drag. paramSpace_dhmGranularity_slider.addEventHandler(MouseEvent.MOUSE_DRAGGED, new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { analysisController.refreshParameterSpaceScatterchart(); }; }); /* * Event listener for change in number of keywords to consider in PTC component. */ slider_localScope_numKeywordsToUse.addEventHandler(MouseEvent.MOUSE_DRAGGED, new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { // Update textfield content. textfield_localScope_numKeywordsToUse.setText(String.valueOf((int)slider_localScope_numKeywordsToUse.getValue())); // Refresh parallel tag clouds. analysisController.refreshPTC(); }; }); /* * Event listener for default opacity slider (relevant for highlighting). */ defaultOpacity_slider.addEventHandler(MouseEvent.MOUSE_RELEASED, new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { VisualizationComponent.DEFAULT_OPACITY_FACTOR = defaultOpacity_slider.getValue(); // Refresh visualizations. analysisController.refreshVisualizations(false); } }); // Add listener to determine position during mouse drag. defaultOpacity_slider.addEventHandler(MouseEvent.MOUSE_DRAGGED, new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { VisualizationComponent.DEFAULT_OPACITY_FACTOR = defaultOpacity_slider.getValue(); }; }); } @Override public void processSelectionManipulationRequest(double minX, double minY, double maxX, double maxY) { } @Override public void processEndOfSelectionManipulation() { } @Override public Pair<Integer, Integer> provideOffsets() { return null; } @Override public void processKeyPressedEvent(KeyEvent ke) { } @Override public void processKeyReleasedEvent(KeyEvent ke) { } @Override public void initialize(URL arg0, ResourceBundle arg1) { System.out.println("Initializing SettingsPopup."); } @Override public void refresh() { } @Override public void resizeContent(double width, double height) { } @Override protected Map<String, Integer> prepareOptionSet() { return null; } /* * From here: Listener. */ @FXML public void changeDBCScalingType(ActionEvent e) { // @todo Remove GUI option. } /** * Toggles global scatterplot's heatmap visibility. * @param e */ @FXML public void changeGlobalScatterplotDHMVisibility(ActionEvent e) { analysisController.changeGlobalScatterplotDHMVisibility(globalScatterplot_DHM_visibility_checkbox.isSelected()); } /** * Processes new information about granularity of global scatterchart's density heatmap. * @param e */ @FXML public void changeGlobalScatterplotDHMGranularityMode(ActionEvent e) { globalScatterchartDHM_granularity_slider.setDisable(globalScatterchartDHM_granularity_checkbox.isSelected()); analysisController.changeGlobalScatterplotDHMGranularity(globalScatterchartDHM_granularity_checkbox.isSelected(), (int)globalScatterchartDHM_granularity_slider.getValue()); } /** * Update color in global scatterchart density heatmap. * @param e */ @FXML public void updateGlobalScatterchartDHMColorSpectrum(ActionEvent e) { analysisController.updateGlobalScatterchartDHMColorSpectrum(mdsHeatmap_dhmColor_min_colChooser.getValue(), mdsHeatmap_dhmColor_max_colChooser.getValue()); } /** * Processes new information about granularity of parameter space scatterchart heatmap. * @param e */ @FXML public void changePSHeatmapGranularityMode(ActionEvent e) { // @todo Implement settings listener. paramSpace_dhmGranularity_slider.setDisable(paramSpace_dhmGranularity_checkbox.isSelected()); analysisController.refreshParameterSpaceScatterchart(); } /** * Changes visibility of heatmap in parameter space scatterchart. * @param e */ @FXML public void changePSHeatmapVisibility(ActionEvent e) { analysisController.refreshParameterSpaceScatterchart(); } /** * Updates data categories used in parameter space scatterchart. * @param e */ @FXML public void updateParamSpaceDHMCategories(ActionEvent e) { analysisController.refreshParameterSpaceScatterchart(); } /** * Update color in parameter space scatterchart density heatmap. * @param e */ @FXML public void updatePSScatterchartDHMColorSpectrum(ActionEvent e) { analysisController.refreshParameterSpaceScatterchart(); } /** * Update color in TMC heatmap. * @param e */ @FXML public void updateTMCHeatmapColorSpectrum(ActionEvent e) { analysisController.updateTMCHeatmapColorSpectrum(tmc_color_min_colChooser.getValue(), tmc_color_max_colChooser.getValue()); } /** * Called when user opens a settings pane directly. * @param e */ @FXML public void selectSettingsPane(MouseEvent e) { // @todo Implement settings listener. // Reset title styles. resetSettingsPanelsFontStyles(); // Set new font style. ((TitledPane) e.getSource()).lookup(".title").setStyle("-fx-font-weight:bold"); } /** * Opens pane in settings panel. * @param paneID */ public void openSettingsPane(String paneID) { // Reset title styles. resetSettingsPanelsFontStyles(); // Select new pane. switch (paneID) { case "settings_mds_icon": accordion_options.setExpandedPane(mdsDistEval_titledPane); mdsDistEval_titledPane.lookup(".title").setStyle("-fx-font-weight:bold"); break; case "settings_distEval_icon": accordion_options.setExpandedPane(mdsDistEval_titledPane); mdsDistEval_titledPane.lookup(".title").setStyle("-fx-font-weight:bold"); break; case "settings_paramDist_icon": accordion_options.setExpandedPane(paramSpace_titledPane); paramSpace_titledPane.lookup(".title").setStyle("-fx-font-weight:bold"); break; case "settings_paramDistCorr_icon": accordion_options.setExpandedPane(paramSpace_titledPane); paramSpace_titledPane.lookup(".title").setStyle("-fx-font-weight:bold"); break; case "settings_tmc_icon": accordion_options.setExpandedPane(localScope_titledPane); localScope_titledPane.lookup(".title").setStyle("-fx-font-weight:bold"); break; case "settings_ptc_icon": accordion_options.setExpandedPane(localScope_titledPane); localScope_titledPane.lookup(".title").setStyle("-fx-font-weight:bold"); break; } } /** * Reset font styles in setting panel's titles. */ private void resetSettingsPanelsFontStyles() { // Change all font weights back to normal. mdsDistEval_titledPane.lookup(".title").setStyle("-fx-font-weight:normal"); paramSpace_titledPane.lookup(".title").setStyle("-fx-font-weight:normal"); paramSpace_titledPane.lookup(".title").setStyle("-fx-font-weight:normal"); localScope_titledPane.lookup(".title").setStyle("-fx-font-weight:normal"); } /* * Getter and setter. */ /** * Calculate the categories value for parameter space scatterchart's density heatmap. * @return */ public int calculatePSScatterchartCategoriesValue() { int value = 0; value += paramSpace_dhmCategories_active_checkbox.isSelected() ? 1 : 0; value += paramSpace_dhmCategories_inactive_checkbox.isSelected() ? 2 : 0; value += paramSpace_dhmCategories_discarded_checkbox.isSelected() ? 4 : 0; return value; } public boolean isDBCLogarithmicallyScaled() { return distanceBarchart_logarithmicScaling_checkbox.isSelected(); } public boolean isParamSpaceDHMVisible() { return paramSpace_dhmVisibility_checkbox.isSelected(); } public boolean isParamSpaceDHMGranularityDynamic() { return paramSpace_dhmGranularity_checkbox.isSelected(); } public int getParamSpaceDHMGranularityValue() { return (int)paramSpace_dhmGranularity_slider.getValue(); } public Color getParamSpaceDHMMinColor() { return paramSpace_dhmColor_min_colChooser.getValue(); } public Color getParamSpaceDHMMaxColor() { return paramSpace_dhmColor_max_colChooser.getValue(); } public Slider getLocalScopeKeywordNumberSlider() { return slider_localScope_numKeywordsToUse; } public TextField getLocalScopeKeywordNumberTextField() { return textfield_localScope_numKeywordsToUse; } public boolean isGlobalScatterchartDHMGranularityDynamic() { return globalScatterchartDHM_granularity_checkbox.isSelected(); } public CheckBox getGlobalScatterchartDHMGranularityCheckbox() { return globalScatterchartDHM_granularity_checkbox; } public Slider getGlobalScatterchartDHMGranularitySlider() { return globalScatterchartDHM_granularity_slider; } public Color getGlobalScatterchartDHMMinColor() { return mdsHeatmap_dhmColor_min_colChooser.getValue(); } public Color getGlobalScatterchartDHMMaxColor() { return mdsHeatmap_dhmColor_max_colChooser.getValue(); } public Color getTMCMinColor() { return tmc_color_min_colChooser.getValue(); } public Color getTMCMaxColor() { return tmc_color_max_colChooser.getValue(); } @Override public void initHoverEventListeners() { } @Override public void highlightHoveredOverDataPoints(Set<Integer> dataPointIDs, DatapointIDMode idMode) { } @Override public void removeHoverHighlighting() { } }
true
8c97c21a9e9ea4f7c8b0c87f232ebf073184d0a7
Java
wangscript/tvcps
/cms/src/com/j2ee/cms/biz/setupmanager/service/SetupBiz.java
UTF-8
24,614
2.125
2
[]
no_license
/** * project:通用内容管理系统 * Company: */ package com.j2ee.cms.biz.setupmanager.service; import java.io.BufferedReader; 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.InputStreamReader; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import com.j2ee.cms.biz.setupmanager.dao.SetDB; import com.j2ee.cms.biz.setupmanager.domain.RegInfo; import com.j2ee.cms.biz.setupmanager.domain.SysInit; import com.j2ee.cms.biz.setupmanager.domain.SysParam; import com.j2ee.cms.common.core.util.StringUtil; /** * <p> * 标题: 该类设置启动时候,解析和写入文件,以及实现注册码等业务逻辑代码. * </p> * <p> * 描述: —— 负责业务操作 * </p> * <p> * 模块: CPS后台数据启动模块 * </p> * <p> * 版权: Copyright (c) 2009 * </p> * <p> * 网址:http://www.j2ee.cmsweb.com * * @author 曹名科 * @version 1.0 * @since 2009-9-6 下午05:36:48 * @history(历次修订内容、修订人、修订时间等) */ public class SetupBiz { /** 声明日志 . **/ private static final Logger log = Logger.getLogger(SetupBiz.class); /** * 根据用户的设置,更新后台hibernate相关的所有配置文件 . * * @param path * @return 成功返回true,失败返回false */ public String updateDBxml(String path) { String mess = ""; SetDB setDB = new SetDB(); SAXReader saxReader = new SAXReader(); try { // 读取setup.xml文件 InputStream in = new FileInputStream(path + File.separator +"setup"+File.separator +"setup.xml"); Document document = saxReader.read(in); Element el = (Element) document.getRootElement().elementIterator( "sysParamset").next(); Element e2 = (Element) document.getRootElement().elementIterator( "dataInitialize").next(); // 根据用户写入的文件中来获取信息 String dbType = el.elementText("databaseType").toLowerCase(); String dbUser = e2.elementText("dataUserName"); String dbPass = e2.elementText("dataUserPass"); String serverIP = e2.elementText("serverIP"); String dbName = e2.elementText("dataBaseName"); String dbPort = e2.elementText("dataPort"); String url = ""; SetDB st = new SetDB(); log.info("你使用的数据库是:"+dbType); // 根据各种不同的数据库类型来调用不同的创建数据的方法 if (dbType.equals("mysql")) { url = "jdbc:mysql://" + serverIP + ":" + dbPort + "/" + dbName + "?characterEncoding=utf8"; if (!st.isDBexists(path)) {// 先判断数据库是否存在 st.createDB(serverIP, dbPort, dbType, dbName, dbUser, dbPass, dbName); // 调用创建mysql数据库的方法 mess = "数据初始化成功,请重新启动服务"; log.info(mess); } else { mess = "已经使用你原来的数据,请重新启动服务"; log.info(mess); } setDB.mysql(dbUser, dbPass, url, path); // 将文件中的内容跟新为mysql的数据类型 } else if (dbType.equals("oracle")) { url = "jdbc:oracle:thin:@" + serverIP + ":" + dbPort + ":" + dbName; setDB.oracle(dbUser, dbPass, url, path); // 将文件中的内容跟新为oracle的数据类型 mess = "初始化成功,请重新启动服务器"; log.info(mess); } else if (dbType.equals("db2")) { url = "jdbc:db2://" + serverIP + ":" + dbPort + "/sample;DatabaseName=" + dbName + ";charset=uft-8;SendStringParametersAsUnicode=false"; if (!st.isDBexists(path)) {// 先判断数据库是否存在 st.createDB(serverIP, dbPort, dbType, dbName, dbUser, dbPass, dbName); // 调用创建db2数据库的方法 mess = "数据初始化成功,请重新启动服务器"; log.info(mess); } else { mess = "已经使用你原来的数据,请重新启动服务器"; log.info(mess); } setDB.DB2(dbUser, dbPass, url, path); // 将文件中的内容跟新为db2的数据类型 } else if (dbType.equals("mssql")) { url = "jdbc:sqlserver://" + serverIP + ":" + dbPort + ";DatabaseName=" + dbName + ";charset=uft-8;SendStringParametersAsUnicode=false"; if (!st.isDBexists(path)) {// 先判断数据库是否存在 st.createDB(serverIP, dbPort, dbType, dbName, dbUser, dbPass, dbName); // 调用创建mssql数据库的方法 mess = "数据初始化成功,请重新启动服务"; log.info(mess); } else { mess = "已经使用你原来的数据,请重新启动服务器"; log.info(mess); } setDB.sqlserver(dbUser, dbPass, url, path); // 将文件中的内容跟新为mssql的数据类型 } return mess; } catch (DocumentException e) { log.error("setup.xml文件操作失败 "+e); return null; } catch (FileNotFoundException e) { log.error("setup.xml文件没有找到"+e); return null; } catch (IOException e) { log.error("setup.xml文件操作失败"+e); return null; } catch (SQLException e) { log.error("数据库操作失败"+e); return null; } catch (ClassNotFoundException e) { log.error("数据库操作失败"+e); return null; } } /** * 获取初始化数据设置 . * * @param path * 路径 * @return 初始化数据信息 */ public SysInit getSysInit(String path) { SysInit init = new SysInit(); try { SAXReader read = new SAXReader(); InputStream isread = new FileInputStream(path + File.separator +"setup"+File.separator+"setup.xml"); Document document = read.read(isread); Element element = document.getRootElement(); Element el = (Element) element.elementIterator("dataInitialize") .next(); init.setSiteName(el.elementText("siteName")); init.setDataBaseName(el.elementText("dataBaseName")); init.setServerIP(el.elementText("serverIP")); init.setDataPort(el.elementText("dataPort")); init.setDataUserName(el.elementText("dataUserName")); init.setDataUserPass(el.elementText("dataUserPass")); init.setCountId(el.elementText("countId")); log.info("获取初始化数据成功"); return init; } catch (FileNotFoundException e) { log.error("setup.xml文件没有找到"+e); return null; } catch (DocumentException e) { log.error("setup.xml操作失败"+e); return null; } } /** * 将数据初始化配置信息放入文件 . * * @param path * 文件路径 * @param init * 初始化数据的信息 */ public void setSysInit(final String path, SysInit init) { XMLWriter writer = null; try { InputStream isread = new FileInputStream(path + File.separator +"setup"+File.separator +"setup.xml"); SAXReader reader = new SAXReader(); Document document = reader.read(isread); document.selectSingleNode( "//systemSetting//dataInitialize//serverIP").setText( init.getServerIP());// 设置IP document.selectSingleNode( "//systemSetting//dataInitialize//dataPort").setText( init.getDataPort());// 端口 document.selectSingleNode( "//systemSetting//dataInitialize//dataBaseName").setText( init.getDataBaseName()); // 数据库名字 document.selectSingleNode( "//systemSetting//dataInitialize//dataUserName").setText( init.getDataUserName()); // 用户名 document.selectSingleNode( "//systemSetting//dataInitialize//dataUserPass").setText( init.getDataUserPass()); // 密码 document.selectSingleNode( "//systemSetting//dataInitialize//countId").setText( init.getCountId()); // 第几次,如果为1,说明数据库已经创建好,0为每创建 OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); writer = new XMLWriter(new FileOutputStream(new File(path + File.separator + "setup"+File.separator +"setup.xml")), format); writer.write(document);// 保存到文件 log.info("数据保存成功"); } catch (FileNotFoundException e) { log.error("setup.xml文件没有找到"+e); } catch (DocumentException e) { log.error("setup.xml文件操作失败"+e); } catch (IOException e) { log.error("setup.xml文件操作失败"+e); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } /** * 获取参数 . * * @param path * 文件位置 * * @return 参数信息 */ public SysParam getSysParam(final String path) { SysParam info = new SysParam(); try { SAXReader read = new SAXReader(); InputStream isread = new FileInputStream(path + File.separator + "setup"+File.separator+"setup.xml"); Document document = read.read(isread); Element el = (Element) document.getRootElement().elementIterator( "sysParamset").next(); info.setLoadPath(path); info.setServerName(el.elementText("serverName")); info.setDatabaseType(el.elementText("databaseType")); info.setAppName(path.substring(path.lastIndexOf("/") + 1, path .length())); info.setPutType(el.elementText("putType")); Element el2 = (Element) document.getRootElement().elementIterator( "userInfo").next(); info.setPwd(el2.elementText("userpwd")); log.info("参数获取成功"); return info; } catch (FileNotFoundException e) { log.error("setup.xml文件不存在"+e); return null; } catch (DocumentException e) { log.error("setup.xml文件操作失败"+e); return null; } } /** * 设置服务器系统参数 . * * @param path * * @return 设置是否成功 */ public boolean setSysParam(final String path, SysParam info) { XMLWriter writer = null; try { InputStream isread = new FileInputStream(path + File.separator +"setup"+File.separator +"setup.xml"); SAXReader reader = new SAXReader(); Document document = reader.read(isread); Element el = document.getRootElement(); Element el2 = (Element) el.elementIterator("userInfo").next(); // 获取XML文件,并且查找userpwd,将他的值改为实体中的,用户修改了密码才去更该密码,否则不更新 if (!info.getPwd().equals(el2.elementText("userpwd").trim())) { document.selectSingleNode("//systemSetting//userInfo//userpwd") .setText(StringUtil.encryptMD5(info.getPwd())); } document.selectSingleNode("//systemSetting//sysParamset//syspath") .setText(path); // 设置系统路径 document.selectSingleNode( "//systemSetting//sysParamset//serverName").setText( info.getServerName()); // 设置服务器名字tomcat,weblogic,.. document.selectSingleNode( "//systemSetting//sysParamset//databaseType").setText( info.getDatabaseType()); // 设置数据库类型oracle,mysql... document.selectSingleNode("//systemSetting//sysParamset//appName") .setText( path.substring(path.lastIndexOf("/") + 1, path .length())); // 设置应用程序名称 OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); writer = new XMLWriter(new FileOutputStream(new File(path + File.separator +"setup"+File.separator +"setup.xml")), format); writer.write(document); // 写入到文件 log.info(" 设置服务器系统参数成功"); return true; } catch (FileNotFoundException e) { log.error("setup.xml文件不存在"+e); return false; } catch (DocumentException e) { log.error("setup.xml文件操作失败"+e); return false; } catch (IOException e) { log.error("setup.xml文件操作失败"+e); return false; } finally { // 关闭流 if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } /** * cps系统后台登陆验证 . * * @param userName * 用户名 * @param password * 密码 * @param path * 文件路径 * @return 返回验证信息 */ public String getUserInfo(String userName, String password, String path) { String messInfo = ""; try { InputStream is = new FileInputStream(path + File.separator+"setup"+File.separator+"setup.xml"); SAXReader reader = new SAXReader(); Document doc = reader.read(is); Element root = doc.getRootElement(); // 读取文件 Element foo = (Element) root.elementIterator("userInfo").next(); String uname = foo.elementText("userName");// 用户名 String pwd = foo.elementText("userpwd"); if (StringUtil.encryptMD5(userName).equals(uname)) { if (StringUtil.encryptMD5(password).equals(pwd)) { messInfo = "登陆成功"; } else { messInfo = "密码输入有误"; } } else { messInfo = "用户名输入有误"; } log.info(messInfo); return messInfo; } catch (IOException e) { log.error("setup.xml读取文件失败"+e); return null; } catch (DocumentException e) { log.error("setup.xml没有找到文件"+e); return null; } } /** * 获取注册信息 . * * @param form * * @param siteId * @return 返回注册信息 map */ public RegInfo getAllRegiterInfo(String path) { RegInfo ri = new RegInfo(); String mac = getMACMD5(); // MAC. InputStream is = null; try { File file = new File(path + File.separator + "WEB-INF"+File.separator+"cps.licence"); if (!file.exists()) { log.info("cps.licence文件不存在"); return null; } is = new FileInputStream(path + File.separator + "WEB-INF"+ File.separator+"cps.licence"); } catch (FileNotFoundException e) { System.out.println(); log.error("没有找到文件cps.licence"+e); } // 将文件的内容读取并且比较 List<String> list = readToBuffer(is); if (list.size() != 13) { return null; } String str = ""; if (list != null && list.size() >= 0) { for (int i = 0; i < list.size(); i++) { str += list.get(i); } String strSplit[] = new String[8]; String licence = str; for (int i = 1; i < strSplit.length; i++) { String ss[] = licence.split(StringUtil.encryptMD5("#" + i)); strSplit[i] = ss[0]; licence = licence.replaceFirst(ss[0] + StringUtil.encryptMD5("#" + i), ""); } // 如果注册码不匹配就不继续了. if (strSplit[1].equals(StringUtil.encryptMD5(mac))) { ri.setRegCode(StringUtil.encryptMD5(strSplit[1])); ri.setMessInfo("注册码匹配成功"); int j = 0; while (true) { if (StringUtil.encryptMD5(j + "").equals(strSplit[2])) { ri.setColumCount(j + ""); break; } if (j > 10000) { ri=null; break; } j++; } int w = 0; while (true) { if (StringUtil.encryptMD5(w + "").equals(strSplit[3])) { ri.setSiteCount(w + ""); break; } if (w > 1000) { ri=null; break; } w++; } int n = 0; while (true) { if (StringUtil.encryptMD5(n + "@").equals(strSplit[4])) { ri.setDateMax(n + "日"); break; } if (StringUtil.encryptMD5(n + "&").equals(strSplit[4])) { ri.setDateMax(n + "月"); break; } if (n > 200) {// 如果大于200,退出,防止死循环 ri=null; break; } n++; } int y = 2000; while (true) { if (StringUtil.encryptMD5("" + y).equals(strSplit[5])) { ri.setYear(y + ""); break; } if (y > 3000) { ri=null; break; } y++; } int m = 0; while (true) { if (StringUtil.encryptMD5("" + m).equals(strSplit[6])) { ri.setMonth(m + ""); break; } if (m > 1000) { ri=null; break; } m++; } int d = 0; while (true) { if (StringUtil.encryptMD5(d + "").equals(strSplit[7])) { ri.setDay(d + ""); break; } if (d > 1000) { ri=null; break; } d++; } ri.setVersion("2.0"); System.out.println("注册码获取成功"); return ri; } else { System.out.println("注册码获取失败"); return null; } } else { System.out.println("注册没有获取任何信息"); return null; } } /** * 获取MAC地址并且加密 . * * @return 返回一个加密的MAC */ public static String getMACMD5() { String macAddr = ""; String os = getOSName(); if (os.startsWith("windows")) { // 本地是windows macAddr = getWindowsMACAddress(); return StringUtil.encryptMD5(macAddr); } else { // 本地是非windows系统 一般就是unix macAddr = getUnixMACAddress(); return StringUtil.encryptMD5(macAddr); } } /** * 获取当前操作系统名称. * * @return 操作系统名称,例如:windows xp,linux 等. */ public static String getOSName() { return System.getProperty("os.name").toLowerCase(); } /** * 获取unix网卡的mac地址. * * @return 非windows的系统默认调用本方法获取.如果有特殊系统请继续扩充新的取mac地址方法. */ public static String getUnixMACAddress() { String mac = null; BufferedReader bufferedReader = null; Process process = null; try { process = Runtime.getRuntime().exec("ifconfig eth0"); // linux下的命令.一般取eth0作为本地主网卡,显示信息中包含有mac地址信息 bufferedReader = new BufferedReader(new InputStreamReader(process .getInputStream())); String line = null; int index = -1; while ((line = bufferedReader.readLine()) != null) { index = line.toLowerCase().indexOf("hwaddr"); // 寻找标示字符串. if (index >= 0) { mac = line.substring(index + "hwaddr".length() + 1).trim(); // 取出mac地址并去除2边空格 break; } } } catch (IOException e) { log.error("读取linuxMAC失败"+e); } finally { try { if (bufferedReader != null) { bufferedReader.close(); } } catch (IOException e1) { } bufferedReader = null; process = null; } return mac; } /** * 获取widnows网卡的mac地址. * * @return mac地址 */ public static String getWindowsMACAddress() { String mac = null; BufferedReader bufferedReader = null; Process process = null; try { process = Runtime.getRuntime().exec("ipconfig /all"); //windows下的命令, // 显示信息中包含有mac地址信息 bufferedReader = new BufferedReader(new InputStreamReader(process .getInputStream())); String line = null; int index = -1; while ((line = bufferedReader.readLine()) != null) { index = line.toLowerCase().indexOf("physical address"); // 寻找标示字符串 // physical // address // ] if (index >= 0) { // 找到了 index = line.indexOf(":"); // 寻找":"的位置 if (index >= 0) { mac = line.substring(index + 1).trim(); // 取出mac地址并去除2边空格 } break; } } } catch (IOException e) { log.error("读取XP MAC失败"+e); } finally { try { if (bufferedReader != null) { bufferedReader.close(); } } catch (IOException e1) { e1.printStackTrace(); } bufferedReader = null; process = null; } return mac; } /** * 判断是否过期,用于比较. * * @param year1 * 年 * @param month1 * 月 * @param day1 * 日 * @return TRUE 已经过期,FALSE,没过期 */ public boolean isPass(int year1, int month1, int day1, int addDate, String dateText) { boolean flag = true; SimpleDateFormat smdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar c = Calendar.getInstance(); if (dateText.equals("日")) { c.set(year1, month1 - 1, day1);// 设置当前日期 c.add(Calendar.DAY_OF_MONTH, addDate); if (smdf.format(c.getTime()).compareTo(smdf.format(new Date())) < 0) {// 小于零 flag = true;// 过期 } else {// 没有过期 flag = false; } } else if (dateText.equals("月")) { c.set(year1, month1 - 1, day1);// 设置当前日期 c.add(Calendar.MONTH, addDate); if (smdf.format(c.getTime()).compareTo(smdf.format(new Date())) < 0) {// 小于零过期 flag = true;// 过期 } else { flag = false;// 没有过期 } } return flag; } /** * 读出一个文件 . * * @param is * @return list集合 * @throws UnsupportedEncodingException */ public final List<String> readToBuffer(final InputStream is) { BufferedReader reader = null; List<String> list = new ArrayList<String>(); try { reader = new BufferedReader(new InputStreamReader(is,"utf-8")); String line; line = reader.readLine(); while (line != null) { // 如果 line 为空说明读完了 if(!line.trim().equals("")){ list.add(line.trim()); } line = reader.readLine(); // 读取下一行 } is.close(); }catch(UnsupportedEncodingException e){ log.error("转码失败"+e); } catch (IOException e) { log.error("没有找到文件"+e); return null; }finally { if (reader != null) { try { reader.close(); } catch (IOException e) { log.debug("关闭失败!!!"); e.printStackTrace(); } } } return list; } /** * 判断是否过期. * @param r注册信息 * @return true过期,false没过期 */ public boolean checkDate(RegInfo r){ boolean flag= true; // 获取当前是日 还是月 String riText = r.getDateMax().substring( r.getDateMax().length() - 1, r.getDateMax().length()); // 判断当前是日还是月 if (riText.equals("日")) { int regAfter = Integer.parseInt(r.getDateMax().substring(0, r.getDateMax().length() - 1));// 获取注册的有效期 // ,由于里面存放的是月或日,所以只截取日 // ,dateMax-1; boolean isPass = isPass(Integer.parseInt(r.getYear()), Integer.parseInt(r.getMonth()), Integer.parseInt(r .getDay()), regAfter, "日"); if (!isPass) {// 如果是日,就判断是否过期,按日计算,调用方法 // 没有过期,将网站数,和栏目数赋值 flag = false; } else { flag = true;// 已经过期 } } else if (riText.equals("月")) { int regAfter = Integer.parseInt(r.getDateMax().substring(0, r.getDateMax().length() - 1));// 获取注册的有效期,由于里面存放的是月或日, // 所以只截取0,dateMax-1; boolean isPass = isPass(Integer.parseInt(r.getYear()), Integer.parseInt(r.getMonth()), Integer.parseInt(r .getDay()), regAfter, "月"); if (!isPass) { // 没有过期 flag = false; } else { // 已经过期了 flag = true; } } return flag; } /** * 判断oracle数据库是否存在 * @param path * 文件路径 * @return 存在的信息 */ public String isOracleExists(final String path){ String mess=""; String sql = "select count(*) from users"; try { SysInit init = getSysInit(path); Class.forName("oracle.jdbc.driver.OracleDriver"); String url ="jdbc:oracle:thin:@" + init.getServerIP() + ":" + init.getDataPort() + ":"+init.getDataBaseName(); Connection c = DriverManager.getConnection(url,init.getDataUserName(),init.getDataUserPass()); PreparedStatement pstm = c.prepareStatement(sql); ResultSet rs = pstm.executeQuery(); if(rs.next()){ mess = rs.getString(1); } } catch (ClassNotFoundException e) { log.error("没有找到数据库"); } catch (SQLException e) { mess="库不存在"; } return mess; } }
true
6a1598eb9ea7d1d736b27d1e97bb3d26e73a959e
Java
prd4519/madhang
/app/src/main/java/com/android/madhang_ae/SessionManager.java
UTF-8
2,551
2.234375
2
[]
no_license
package com.android.madhang_ae; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import com.android.madhang_ae.Pembeli.NavigationPembeli; import java.util.HashMap; public class SessionManager { SharedPreferences pref; SharedPreferences.Editor editor; Context context; int mode = 0; private static final String pref_name = "crudpref"; private static final String is_login = "isLogin"; public static final String kunci_id = "keyid"; public static final String kunci_pass = "keypass"; public static final String kunci_idKec = "keyidKec"; public static final String kunci_otp = "keyotp"; public SessionManager(Context context) { pref = context.getSharedPreferences(pref_name, mode); editor = pref.edit(); this.context = context; } public void createSession(String id,String password,String idKec,String otp){ editor.putBoolean(is_login,true); editor.putString(kunci_id,id); editor.putString(kunci_pass,password); editor.putString(kunci_idKec,idKec); editor.putString(kunci_otp,otp); editor.commit(); } public void checkLogin(){ if(!this.is_login()){ Intent i = new Intent(context, MainActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); }else { Intent i = new Intent(context, NavigationPembeli.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } } private boolean is_login() { return pref.getBoolean(is_login, false); } public void logout(){ editor.clear(); editor.commit(); Intent i = new Intent(context, MainActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } public HashMap<String, String> getUserDetails(){ HashMap<String, String> user = new HashMap<String, String>(); user.put(pref_name, pref.getString(pref_name, null)); user.put(kunci_id, pref.getString(kunci_id, null)); user.put(kunci_pass, pref.getString(kunci_pass, null)); user.put(kunci_idKec, pref.getString(kunci_idKec, null)); user.put(kunci_otp, pref.getString(kunci_otp, null)); return user; } }
true
f0ace01636899cb5bb5b0daddc4b8bae498e411e
Java
wangym/java-common
/src/main/java/me/yumin/common/asset/result/PageResult.java
UTF-8
3,111
2.796875
3
[]
no_license
package me.yumin.common.asset.result; import lombok.Getter; import me.yumin.common.util.StringUtil; import java.io.Serializable; import java.util.Collection; /** * @author [email protected] * @since 2015-07-09 */ public final class PageResult<T extends Collection> implements Serializable { private static final long serialVersionUID = 2710973307675225562L; @Getter private int pageNum = 0; // 当前页码 @Getter private int pageRows = 0; // 每页数量 @Getter private int totalPage = 0; // 总的页数 @Getter private int totalRows = 0; // 总的行数 private boolean hasNext = false; // 有否下页 @Getter private boolean success = true; @Getter private int code = 200; @Getter private String msg = "OK"; // 提示信息 @Getter protected T data = null; // 结果集合 /** * */ public PageResult() { } /** * @param pageNum 当前页 * @param pageRows 每页数 * @param totalRows 总行数 */ public PageResult(final int pageNum, final int pageRows, final int totalRows) { this.pageNum = pageNum; this.pageRows = pageRows; this.totalRows = totalRows; // 动态值计算 init(); } /** * 是否有数据 * * @return true=有 || false=无 */ public boolean hasData() { boolean result = false; if (0 < totalRows) { if (null != data && 0 < data.size()) { result = true; } } return result; } /** * 是否有下页 * * @return true=有 || false=无 */ public boolean hasNext() { return hasNext; } /** * @param code code * @return this */ public PageResult<T> setCode(final int code) { this.code = code; this.success = (200 == code); return this; } /** * @param data T * @return this */ public PageResult<T> setData(final T data) { if (null != data) { this.data = data; } return this; } /** * @param e Exception * @return this */ public PageResult<T> setException(final Exception e) { if (null != e) { setCode(500).setMsg(e.getMessage()); } return this; } /** * @param msg msg * @return this */ public PageResult<T> setMsg(final String msg) { if (StringUtil.isNotEmpty(msg)) { this.msg = msg; } return this; } /** * ======================================== * private methods * ======================================== */ /** * */ private void init() { if (0 < totalRows && 0 < pageRows) { this.totalPage = (totalRows + pageRows - 1) / pageRows; } this.hasNext = pageNum < totalPage; } public static void main(String[] args) { PageResult pageResult = new PageResult(100, 1, 10); System.out.println(pageResult.toString()); } }
true
2f211cf4505cebebcecfe402519a56d5ac5896ff
Java
shaoFrooter/agos
/evything/src/main/java/commons/deletefileandfolder/DeleteFileFolder.java
UTF-8
833
3.09375
3
[]
no_license
package commons.deletefileandfolder; import java.io.File; /** * Created by sfeng on 2016/10/29. */ public class DeleteFileFolder { public void deleteAll(String path){ File f=new File(path); System.out.println(f.exists()); if(f.exists()&&f.isDirectory()){ if(f.listFiles().length==0){ f.delete(); }else{ File[] fs=f.listFiles(); for(int i=0;i<fs.length;i++){ if(fs[i].isDirectory()){ deleteAll(fs[i].getAbsolutePath()); } fs[i].delete(); } } } } public static void main(String[] args) { DeleteFileFolder deleteFileFolder=new DeleteFileFolder(); deleteFileFolder.deleteAll("d:\\test"); } }
true
096236eede87911bd44fad75e15c82acd4418416
Java
afirst/rfid-duke
/rfid-duke/src/smarthome/rfid/DatabaseUpdater.java
UTF-8
1,480
2.515625
3
[]
no_license
package smarthome.rfid; import java.io.InputStream; import java.net.URL; import smarthome.rfid.data.Location; public class DatabaseUpdater { private static final String WEB_SERVICE_URL = "http://localhost/request.php?pw=7002xav&"; public DatabaseUpdater() { } public boolean toggleTag(int tagId) { try { return callWebService("q=toggle_tag&tag_id="+tagId).equals("0"); } catch (Exception e) { e.printStackTrace(); return false; } } public boolean setHome(int tagId, Location location) { try { location = new Location(location.x() + 0.1, location.y() +.02, location.z()); String x = "" + location.x(); String y = "" + location.y(); String z = "" + location.z(); return callWebService("q=set_home&tag_id="+tagId+"&x="+x+"&y="+y+"&z="+z).equals("0"); } catch (Exception e) { e.printStackTrace(); return false; } } public boolean setAway(int tagId) { try { return callWebService("q=set_away&tag_id="+tagId).equals("0"); } catch (Exception e) { e.printStackTrace(); return false; } } private String callWebService(String query) throws Exception { StringBuilder str = new StringBuilder(); URL url = new URL(WEB_SERVICE_URL + query); InputStream urlRobotStream = url.openStream(); byte[] bytes = new byte[1000]; int n = 0; while ((n = urlRobotStream.read(bytes)) != -1) { str.append(new String(bytes, 0, n)); } urlRobotStream.close(); return str.toString(); } }
true
b7e9c4066d6cdbc94ec2d8f2e3de1b541ffd18b9
Java
fulq1234/hlhlo-single
/translation/src/main/java/com/lummei/translation/mapper/KnowledgeMapper.java
UTF-8
1,015
2.078125
2
[]
no_license
package com.lummei.translation.mapper; import com.lummei.translation.entity.Knowledge; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import java.util.List; @Mapper public interface KnowledgeMapper { /** * select title,content,instr(content,'<p>') * ,substring(content,1,instr(content,'<p>') -1), * replace(replace(replace(replace(replace(replace(substring(content,1,instr(content,'<p>') -1),'<h4>',''),'</h4>',''),'<br />',''),'<span>',''),'</span>',''),'&nbsp',''), * substring(content,instr(content,'<p>')) * from knowledge_new where typename in ( * select id from directory where fatherid=9 or fatherid in(select id from directory where fatherid=9) * ); * @return */ @Select("select id,title,content from knowledge_new where typename in (" + "select id from directory where fatherid=9 or fatherid in(select id from directory where fatherid=9)" + ")") List<Knowledge> select(); }
true
275e4a55c1bfb8afda6a3e78a2114bd856c49087
Java
ahmedouda1995/Old-Competitive-Programming-Practice
/ch3_dp/UVa_507_JillRidesAgain.java
UTF-8
2,269
3.359375
3
[]
no_license
package ch3_dp; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class UVa_507_JillRidesAgain { public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(new FileReader("input.txt")); PrintWriter out = new PrintWriter(System.out); int t = sc.nextInt(), route = 1; while(t-- > 0) { int n = sc.nextInt() - 1; int [] a = new int[n]; for(int i = 0; i < n; ++i) a[i] = sc.nextInt(); solve(a, route++, out); } out.flush(); out.close(); } private static void solve(int[] a, int route, PrintWriter out) { int max = a[0], sum = a[0]; int currSt = 0, currEnd = 0; int st = 0, end = 0; for(int i = 1; i < a.length; ++i) { if(sum + a[i] < a[i]) { sum = a[i]; currSt = i; currEnd = i; } else { sum += a[i]; currEnd = i; } if(max <= sum) { if(max == sum) { if((currEnd - currSt) > (end - st)) { st = currSt; end = currEnd; } } else { max = sum; st = currSt; end = currEnd; } } } if(max <= 0) out.println("Route " + route + " has no nice parts"); else out.println("The nicest part of route " + route + " is between stops " + (st + 1) + " and " + (end + 2)); } static class Pair { char c; int n; public Pair(char c, int n) { this.c = c; this.n = n; } } static class Scanner{ StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader r){ br = new BufferedReader(r);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
true
781faa42cb563b416a517f232c30c28b452449de
Java
lixiaohui333/test
/WhaleMeeting/app/src/main/java/com/meeting/client/domain/base/BaseDataList.java
UTF-8
286
1.75
2
[]
no_license
package com.meeting.client.domain.base; import java.io.Serializable; import java.util.List; public class BaseDataList<T> implements Serializable{ private static final long serialVersionUID = 1L; public List<T> list; public int pageIndex; public int totalPage; }
true
5c51c16b075bee479b0f6f034d73bec9be9731da
Java
yongfengnice/FamouscarLoan
/.svn/pristine/de/de1dd99bc94fa394e3d4195a9006e2ab1d1af481.svn-base
UTF-8
3,855
2.03125
2
[]
no_license
package com.famous.zhifu.loan.famouscarloan.account; import java.util.HashMap; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.baofoo.sdk.vip.BaofooPayActivity; import com.famous.zhifu.loan.R; import com.famous.zhifu.loan.activity.ActivityInterface; import com.famous.zhifu.loan.activity.Consts; import com.famous.zhifu.loan.activity.LoginActivity; import com.famous.zhifu.loan.internet.ServiceClient; import com.famous.zhifu.loan.pay.OrderService; import com.famous.zhifu.loan.util.NetUtil; public class PayActivity extends Activity implements ActivityInterface { private EditText accountText = null; private Button submitBtn = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pay); findView(); addAction(); initData(); } @Override public void findView() { TextView titleView = (TextView) findViewById(R.id.main_header_tv_text); titleView.setText("确认投资"); accountText = (EditText) findViewById(R.id.pay_account); submitBtn = (Button) findViewById(R.id.pay_submit); } @Override public void initData() { } @Override public void addAction() { submitBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getOrderNo(); } }); } private void getOrderNo() { String temp = accountText.getText().toString().trim(); if (temp.length()==0) { Toast.makeText(this, "请输入充值金额", 1).show(); return; } if (NetUtil.isNetworkConnected(this)) { Map<String, Object> params = new HashMap<String, Object>(); params.put("amount",temp); ServiceClient.call(Consts.NetWork.PAY, params, callback); } else { Toast.makeText(this, Consts.NONETWORK, 1).show(); } } ServiceClient.Callback callback = new ServiceClient.Callback() { @Override public void callback(JSONObject data) { System.out.println("交易码: " + data); try { if (data.getInt("errorcode") == 0) { if (!TextUtils.isEmpty(data.get("dataresult").toString())) { JSONObject json = data.getJSONObject("dataresult"); goPay(json.getString("order_id"),json.getBoolean("testMode")); } } } catch (JSONException e) { e.printStackTrace(); try { String str = data.getString("errormsg"); Toast.makeText(PayActivity.this, str, 1).show(); } catch (JSONException ee) { ee.printStackTrace(); Toast.makeText(PayActivity.this, Consts.UNKNOWN_FAULT, 1).show(); } } } }; private void goPay(String orderNo,boolean testMode){ OrderService orderService = new OrderService(this,orderNo,testMode); orderService.execute(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == OrderService.REQUEST_CODE_BAOFOO_SDK) { String result = ""; String msg = ""; if (data == null || data.getExtras() == null) { msg = "支付已被取消"; } else { result = data.getExtras().getString(BaofooPayActivity.PAY_RESULT);//-1:失败 0:取消 1:成功 10:处理中 msg = data.getExtras().getString(BaofooPayActivity.PAY_MESSAGE); } Toast.makeText(this, msg, 1).show(); finish(); /*AlertDialog dialog = new AlertDialog(this) {}; dialog.setMessage(msg); dialog.show();*/ } } public void backHandler(View v){ finish(); } }
true
01a3ea9d4033f88c4b42d9ec574f887d80d2645e
Java
harrybnt/test-multiple-attachment
/src/main/java/com/multiple/attachment/Reproducer/UploadListOfAttachment.java
UTF-8
2,055
2.078125
2
[]
no_license
package com.multiple.attachment.Reproducer; import io.vertx.core.Vertx; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.client.WebClient; import io.vertx.ext.web.multipart.MultipartForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class UploadListOfAttachment { @Autowired private ResponseUtils responseUtils; public void freshdeskPostRequest(RoutingContext routingContext, Vertx vertx) { //put path of any local file WebClient webClient = WebClient.create(vertx); MultipartForm multipartForm = MultipartForm.create() .attribute("description", "test-ticket-description-50") .attribute("subject", "subject") .attribute("unique_external_id", "1") .attribute("status", "2") .attribute("priority", "2") .binaryFileUpload("attachments[]", "Screenshot1.png", "/your local path of image", "image/png") .binaryFileUpload("attachments[]", "Screenshot1.png", "/Another local path of image", "image/png") .attribute("cc_emails[]", "[email protected]") .attribute("cc_emails[]", "[email protected]"); webClient.postAbs("https://swiggyaid227.freshdesk.com/api/v2/tickets") .putHeader("Content-type", "multipart/form-data") .putHeader("Authorization", "Basic aGFyc2l0Lmd1cHRhQHN3aWdneS5pbjpzd2lnZ3lAMTIz") .sendMultipartForm(multipartForm, httpResponseAsyncResult -> { if (httpResponseAsyncResult.succeeded() && httpResponseAsyncResult.result() != null) { responseUtils.buildAndSendResponse(routingContext, 200, "success", httpResponseAsyncResult.result().body().toJsonObject()); } else { responseUtils.buildAndSendResponse(routingContext, -1, "Failed", httpResponseAsyncResult.cause().getMessage()); } }); } }
true
4f23d1c3fdf2b84f9fb345b83d3845d56feecec5
Java
SonOfViktor/CompositeChainTask
/src/com/fairycompany/handling/parser/TextParser.java
UTF-8
260
1.992188
2
[]
no_license
package com.fairycompany.handling.parser; import com.fairycompany.handling.entity.TextComponent; import com.fairycompany.handling.exception.CompositeException; public interface TextParser { TextComponent parse(String text) throws CompositeException; }
true
f4afc45f060547db22682b23c07757147772ee11
Java
menyouping/jLang
/src/com/jay/parser/element/Tree.java
UTF-8
534
2.40625
2
[]
no_license
package com.jay.parser.element; import java.util.List; import com.jay.ast.AstNode; import com.jay.exception.ParseException; import com.jay.lexer.Lexer; import com.jay.parser.Parser; public class Tree extends Element { protected Parser parser; public Tree(Parser p) { parser = p; } public void parse(Lexer lexer, List<AstNode> res) throws ParseException { res.add(parser.parse(lexer)); } public boolean match(Lexer lexer) throws ParseException { return parser.match(lexer); } }
true
f56757300ea18df324a4d7bf434f91ef001c7275
Java
suyash-capiot/operations
/src/main/java/com/coxandkings/travel/operations/repository/merge/AccommodationBookProductRepository.java
UTF-8
341
1.96875
2
[]
no_license
package com.coxandkings.travel.operations.repository.merge; import com.coxandkings.travel.operations.model.merge.AccommodationBookProduct; public interface AccommodationBookProductRepository { AccommodationBookProduct saveOrUpdate(AccommodationBookProduct accommodationBookProduct); AccommodationBookProduct getById(String id); }
true
c8f13dee4e22358db9f9398d3df2701dd41663ea
Java
syntrydy/ISBUSY
/app/src/main/java/com/example/gasmyr/isbusy/src/Message.java
UTF-8
915
2.25
2
[]
no_license
package com.example.gasmyr.isbusy.src; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.telephony.SmsManager; import android.util.Log; import android.widget.Toast; import com.example.gasmyr.isbusy.utils.PhoneNumber; import java.util.ArrayList; /** * Created by gasmyr on 05/01/16. */ public class Message { private SmsManager smsManager; private ArrayList<String> messageParts; public Message() { this.smsManager = SmsManager.getDefault(); } public void sendMessage( String number,String fullMessage){ if(fullMessage.length()>=140){ messageParts=this.smsManager.divideMessage(fullMessage); this.smsManager.sendMultipartTextMessage(number,null,messageParts,null,null); } else{ this.smsManager.sendTextMessage(number, null,fullMessage, null, null); } } }
true
c4ad89ce5d805855e932e650b36b101ab44523a9
Java
AmuseWorkingTeam/XXYP
/app/src/main/java/com/xxyp/xxyp/common/utils/permissions/PermissionsConstant.java
UTF-8
2,013
1.960938
2
[ "Apache-2.0" ]
permissive
package com.xxyp.xxyp.common.utils.permissions; import android.Manifest; import android.annotation.TargetApi; /** * Description : 运行时权限常量 */ @TargetApi(19) public interface PermissionsConstant { /** * 权限被允许 */ int GRANTED = 0; /** * 权限被拒绝 */ int DENIED = -1; /** * 权限没找到 */ int NOT_FOUND = -2; /** * 相机权限 */ String CAMERA = Manifest.permission.CAMERA; /** * 录音权限 */ String RECORD_AUDIO = Manifest.permission.RECORD_AUDIO; /** * 读取联系人 */ String READ_CONTACT = Manifest.permission.READ_CONTACTS; /** * 修改联系人 */ String WRITE_CONTACT = Manifest.permission.WRITE_CONTACTS; /** * 定位1 通过GPS芯片接收卫星的定位信息,定位精度达10米以内 */ String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION; /** * 定位2 通过WiFi或移动基站的方式获取用户错略的经纬度信息,定位精度大概误差在30~1500米 */ String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION; /** * 读取设备信息 */ String READ_PHONE_STATE = Manifest.permission.READ_PHONE_STATE; /** * 打电话 */ String CALL_PHONE = Manifest.permission.CALL_PHONE; /** * 发短信 */ String SEND_SMS = Manifest.permission.SEND_SMS; /** * 读SD卡 */ String READ_STORAGE = Manifest.permission.READ_EXTERNAL_STORAGE; /** * 写SD卡 */ String WRITE_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE; /** * 创建桌面快捷方式 */ String INSTALL_SHORTCUT = Manifest.permission.INSTALL_SHORTCUT; /** * 弹出系统浮层 */ String SYSTEM_ALERT_WINDOW = Manifest.permission.SYSTEM_ALERT_WINDOW; /** * 修改系统设置 */ String WRITE_SETTINGS = Manifest.permission.WRITE_SETTINGS; }
true
1dca2df538efaf91d7e42266acd257d3f0c88845
Java
2weeks-io/nuguya2
/src/main/java/io/weeks/nuguya/Repository/WritingDtlRepository.java
UTF-8
1,047
2.078125
2
[]
no_license
package io.weeks.nuguya.Repository; import io.weeks.nuguya.Entity.Writing; import io.weeks.nuguya.Entity.WritingDtl; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; public interface WritingDtlRepository extends JpaRepository<WritingDtl, Long> { @Query("select w from WritingDtl w where w.writingNo = :writingNo order by function('RAND')") Page<WritingDtl> findByRandomWritingNo(@Param("writingNo") Long writingNo, Pageable pageable); List<WritingDtl> findByWritingNo(Pageable pageable, Long writingNo); List<WritingDtl> findByWritingNo(Integer writingNo); List<WritingDtl> findByWritingNoOrderByRegDtsDesc(Long writingNo); void deleteByWritingNoAndWritingSeq(Long writingNo, Long WritingSeq); WritingDtl findByWritingNoAndWritingSeq(Long writingNo, Long writingSeq); }
true
07c7f99c96cf5fa403cbf9abc86bbf840ce863f8
Java
zhwanwan/my8kdj
/src/main/java/com/xxx/jdk8/stream/StreamTest6.java
UTF-8
1,442
3.328125
3
[]
no_license
package com.xxx.jdk8.stream; import java.util.IntSummaryStatistics; import java.util.UUID; import java.util.stream.Stream; /** * @author zhwanwan * @create 2019-05-25 12:29 PM */ public class StreamTest6 { public static void main(String[] args) { Stream<String> stream = Stream.generate(UUID.randomUUID()::toString); stream.findFirst().ifPresent(System.out::println); System.out.println("---------------"); /** * iterate 会生成一个无限流,一般需要配合limit使用 */ Stream.iterate(1, i -> i + 2).limit(6).forEach(System.out::println); System.out.println("--------------"); int sum = Stream.iterate(1, i -> i + 2) .limit(6) .filter(i -> i > 5) .mapToInt(i -> i * 2) .skip(2) .limit(2) .sum(); System.out.println(sum); System.out.println("--------------"); //min() max()--返回 OptionalInt IntSummaryStatistics summaryStatistics = Stream.iterate(1, i -> i + 2) .limit(6) .filter(i -> i > 4) .mapToInt(i -> i * 2) .skip(2) .limit(2) .summaryStatistics(); System.out.println(summaryStatistics.getMax()); System.out.println(summaryStatistics.getMin()); System.out.println("---------------"); } }
true
38c9fbca6ec7876d1cea84f733c0d163d182c820
Java
weAreAllGod/JZLJ
/src/main/java/cn/edu/bjtu/jzlj/service/impl/CarCarryInfoServiceImpl.java
UTF-8
514
1.671875
2
[]
no_license
package cn.edu.bjtu.jzlj.service.impl; import cn.edu.bjtu.jzlj.domain.CarCarryInfo; import cn.edu.bjtu.jzlj.mapper.CarCarryInfoMapper; import cn.edu.bjtu.jzlj.service.CarCarryInfoService; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author LiuYi * @since 2019-04-17 */ @Service public class CarCarryInfoServiceImpl extends ServiceImpl<CarCarryInfoMapper, CarCarryInfo> implements CarCarryInfoService { }
true
1ca2c4174dabcace8ef75d8f4d8c2992b701022f
Java
RicardoBenetero/academiaDespo
/TrabalhoFinalParteDois/src/main/java/br/gov/serpro/caixa24h/exception/ContaInexistenteException.java
UTF-8
172
2
2
[]
no_license
package br.gov.serpro.caixa24h.exception; public class ContaInexistenteException extends Exception { public ContaInexistenteException (String msg) { super(msg); } }
true
1b9a5fe1abfecc895803e5cd088818106dd0652c
Java
wilczogon/LakeProject
/src/com/edu/agh/student/lakeproject/fish/ReproductiveOrgans.java
UTF-8
522
2.625
3
[]
no_license
package com.edu.agh.student.lakeproject.fish; import java.io.Serializable; public abstract class ReproductiveOrgans implements Serializable{ protected final static int MATURATION_DURATION = 100; protected int maturityCounter = MATURATION_DURATION; public ReproductiveOrgans(){} public Gender getGender(){ return gender; } protected Gender gender; public abstract void step(); public boolean isMature(){ if(maturityCounter == 0) return true; else return false; } }
true
3acceb7f16d1c00cc57c1220db0561c720d156bb
Java
fabitaInes/truextend-problem2
/src/main/java/com/truextend/problem2/service/StudentService.java
UTF-8
5,778
2.875
3
[]
no_license
package com.truextend.problem2.service; import com.truextend.problem2.dao.StudentDao; import com.truextend.problem2.entity.Student; import com.truextend.problem2.exception.StudentAlreadyExistsException; import com.truextend.problem2.exception.StudentFieldsException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; /** * The type Student service. */ public class StudentService { /** * The constant EARTH_RADIO. */ public final static double EARTH_RADIO = 6378.1; private static final Logger logger = LogManager.getLogger(StudentService.class); private static StudentService INSTANCE; /** * Gets instance. * * @return the instance */ public static StudentService getInstance() { if (INSTANCE == null) { INSTANCE = new StudentService(); } return INSTANCE; } /** * Determine lat lon double [ ]. * * @param distance the distance * @param bearingInDegrees the bearing in degrees * @param lat the lat * @param lon the lon * @return the double [ ] */ public double[] determineLatLon(double distance, double bearingInDegrees, double lat, double lon) { double distanceInKm = distance / 1000; double bearing = Math.toRadians(bearingInDegrees); double lat1 = Math.toRadians(lat); //Current lat point converted to radians double lon1 = Math.toRadians(lon); //Current long point converted to radians double lat2 = Math.asin(Math.sin(lat1) * Math.cos(distanceInKm / EARTH_RADIO) + Math.cos(lat1) * Math.sin(distanceInKm / EARTH_RADIO) * Math.cos(bearing)); double lon2 = lon1 + Math.atan2(Math.sin(bearing) * Math.sin(distanceInKm / EARTH_RADIO) * Math.cos(lat1), Math.cos(distanceInKm / EARTH_RADIO) - Math.sin(lat1) * Math.sin(lat2)); lat2 = Math.toDegrees(lat2); lon2 = Math.toDegrees(lon2); logger.debug("Latitude: " + lat2 + " Longitude: " + lon2); return new double[]{lat2, lon2}; } /** * Is point inside polygon boolean. * * @param points the points * @param x the x * @param y the y * @return the boolean */ public boolean isPointInsidePolygon(List<double[]> points, double x, double y) { boolean inside = false; int j = points.size() - 1; for (int i = 0; i < points.size(); j = i++) { double[] u0 = (double[]) points.get(i); double[] u1 = (double[]) points.get(j); if (y < u1[1]) { if (u0[1] <= y && (y - u0[1]) * (u1[0] - u0[0]) > (x - u0[0]) * (u1[1] - u0[1])) { inside = !inside; } } else if (y < u0[1] && (y - u0[1]) * (u1[0] - u0[0]) < (x - u0[0]) * (u1[1] - u0[1])) { inside = !inside; } } return inside; } /** * Select all collection. * * @return the collection */ public Collection<Student> selectAll() { return StudentDao.getDao().fetchAll(); } /** * Add student. * * @param student the student * @return the student * @throws StudentAlreadyExistsException the student already exists exception * @throws StudentFieldsException the student fields exception */ public Student add(Student student) throws StudentAlreadyExistsException, StudentFieldsException { validateStudent(student); return StudentDao.getDao().insert(student); } private void validateStudent(Student student) throws StudentFieldsException { if (student.getName() == null) { throw new StudentFieldsException("Student Name cannot be null"); } if (student.getLatitude() == 0) { throw new StudentFieldsException("Student Latitude cannot be null"); } if (student.getLongitude() == 0) { throw new StudentFieldsException("Student Longitude cannot be null"); } } /** * Gets students in classrooms. * * @param distanceInMeters the distance in meters * @param bearingInDegrees the bearing in degrees * @return the students in classrooms */ public Collection<Student> getStudentsInClassrooms(double distanceInMeters, double[] bearingInDegrees) { return ClassroomService.getInstance().selectAll() .stream().map(classroom -> { double[] vertex1 = determineLatLon(distanceInMeters, bearingInDegrees[0], classroom.getLatitude(), classroom.getLongitude()); double[] vertex2 = determineLatLon(distanceInMeters, bearingInDegrees[1], classroom.getLatitude(), classroom.getLongitude()); double[] vertex3 = determineLatLon(distanceInMeters, bearingInDegrees[2], classroom.getLatitude(), classroom.getLongitude()); double[] vertex4 = determineLatLon(distanceInMeters, bearingInDegrees[3], classroom.getLatitude(), classroom.getLongitude()); List<double[]> points = new ArrayList<>(); points.add(vertex1); points.add(vertex2); points.add(vertex3); points.add(vertex4); return getInstance().selectAll() .stream().filter(student -> isPointInsidePolygon(points, student.getLatitude(), student.getLongitude())) .collect(Collectors.toList()); }).flatMap(Collection::stream).collect(Collectors.toList()); } }
true
aef32fa181b270a7e91de4e67db1c206b0a39335
Java
SubZeroRobotics/SubZeroUltimateGoal
/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/autonomous/trajectories/AutoTrajectoriesHigh.java
UTF-8
15,121
2.46875
2
[ "MIT" ]
permissive
//package org.firstinspires.ftc.teamcode.autonomous.trajectories; // //import com.acmerobotics.roadrunner.geometry.Pose2d; //import com.acmerobotics.roadrunner.geometry.Vector2d; //import com.acmerobotics.roadrunner.trajectory.Trajectory; //import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; //import com.acmerobotics.roadrunner.trajectory.constraints.MecanumVelocityConstraint; //import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; //import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; //import com.qualcomm.robotcore.hardware.HardwareMap; //import com.qualcomm.robotcore.hardware.Servo; // //import org.firstinspires.ftc.teamcode.drive.DriveConstants; //import org.firstinspires.ftc.teamcode.drive.SampleMecanumDrive; //import org.firstinspires.ftc.teamcode.subsystems.Hopper; //import org.firstinspires.ftc.teamcode.subsystems.Shooter; //import org.firstinspires.ftc.teamcode.subsystems.Wobblemech; // //import java.util.ArrayList; //import java.util.Arrays; // //public class AutoTrajectoriesHigh { // // //dt; // public SampleMecanumDrive drive; // // //trajectory array list // public ArrayList<Trajectory> trajectoryRing1 = new ArrayList<Trajectory>(); // public ArrayList<Trajectory> trajectoryRing0 = new ArrayList<Trajectory>(); // public ArrayList<Trajectory> trajectoryRing4 = new ArrayList<Trajectory>(); // // // //robot start position. setting it at 0,0,0 for now; // Pose2d startPose; // Shooter shooter; // public Hopper hopper; // public Servo angleFlap; // public Wobblemech wobblemech; // public HardwareMap hardwareMap; // // double highGoalFlap = .345; // double powershotFlap = .38; // // // public double linkageWait = .75; // // // // public AutoTrajectoriesHigh(HardwareMap hw, SampleMecanumDrive drive, Shooter shooter, Hopper hopper, Wobblemech wobblemech){ // this.drive = drive; // this.shooter = shooter; // this.hopper = hopper; // this.wobblemech = wobblemech; // this.hardwareMap = hw; // angleFlap = hardwareMap.get(Servo.class, "flap"); // } // // public void initTrajectories(Pose2d startPose){ // this.startPose = startPose; // /* // case 4 // */ // // // //drive to shoot 3 rings // //0 // Trajectory trajFour1 = drive.trajectoryBuilder(startPose) // .splineToConstantHeading(new Vector2d(26,12),0) // .addTemporalMarker(.5, () ->{ // shooter.motorSetPIDpower(.92); // hopper.raise(); // angleFlap.setPosition(.37); // }) // .addTemporalMarker(.1, () ->{ // wobblemech.idle(); // }) // .build(); // trajectoryRing4.add(trajFour1); // // //knock rings over // //1 // Trajectory trajFour15 = drive.trajectoryBuilder(trajFour1.end()) // .lineToConstantHeading(new Vector2d(38,12), new MinVelocityConstraint(Arrays.asList( // new AngularVelocityConstraint(DriveConstants.MAX_ANG_VEL), // new MecanumVelocityConstraint(20, DriveConstants.TRACK_WIDTH) // ) // ), new ProfileAccelerationConstraint(DriveConstants.MAX_ACCEL)) // .addTemporalMarker(.5, () ->{ // angleFlap.setPosition(.5); // }) // .addTemporalMarker(2, () ->{ // angleFlap.setPosition(highGoalFlap); // }) // // .build(); // // trajectoryRing4.add(trajFour15); // //intake rings // //2 // Trajectory trajFour16 = drive.trajectoryBuilder(trajFour15.end()) // // .lineToConstantHeading(new Vector2d(46,12), new MinVelocityConstraint(Arrays.asList( // new AngularVelocityConstraint(DriveConstants.MAX_ANG_VEL), // new MecanumVelocityConstraint(3 // , DriveConstants.TRACK_WIDTH) // ) // ), new ProfileAccelerationConstraint(DriveConstants.MAX_ACCEL)) // .addTemporalMarker(.5, () ->{ // shooter.motorSetPIDpower(.95); // }) // // // .build(); // trajectoryRing4.add(trajFour16); // // // //drop wobble off // //3 // Trajectory trajFour2 = drive.trajectoryBuilder(trajFour16.end(), false) // .lineTo(new Vector2d(110,30)) // .addTemporalMarker(.1, () -> { // // raise the linkage // angleFlap.setPosition(.45); // }) // .addDisplacementMarker(() -> { // // // // //drop wobble // wobblemech.letGo(); // angleFlap.setPosition(highGoalFlap); // // }) // .build(); // trajectoryRing4.add(trajFour2); // // //4 // //drop off // // Trajectory trajFour5 = drive.trajectoryBuilder(trajFour2.end()) // .lineToLinearHeading(new Pose2d(16,4, Math.toRadians(90)), new MinVelocityConstraint(Arrays.asList( // new AngularVelocityConstraint(DriveConstants.MAX_ANG_VEL), // new MecanumVelocityConstraint(60, DriveConstants.TRACK_WIDTH) // ) // ), new ProfileAccelerationConstraint(DriveConstants.MAX_ACCEL)) // .addTemporalMarker(.5, () -> { // wobblemech.extend(); // wobblemech.letGo(); // }) // .build(); // trajectoryRing4.add(trajFour5); // // //drop off // // 5 // Trajectory trajFour6 = drive.trajectoryBuilder(trajFour5.end()) // .splineTo(new Vector2d(38,12),Math.toRadians(0), new MinVelocityConstraint(Arrays.asList( // new AngularVelocityConstraint(DriveConstants.MAX_ANG_VEL), // new MecanumVelocityConstraint(55, DriveConstants.TRACK_WIDTH) // ) // ), new ProfileAccelerationConstraint(DriveConstants.MAX_ACCEL)) // .addTemporalMarker(.2, () -> { // shooter.motorSetPIDpower(.9); // }) // .addTemporalMarker(.3, () -> { // // raise the linkage // // shooter.setNoPIDPower(.9); // angleFlap.setPosition(.35); // hopper.raise(); // shooter.motorSetPIDpower(.9); // }) // .build(); // trajectoryRing4.add(trajFour6); // // // //shooting rings in high goal // Trajectory trajFour7 = drive.trajectoryBuilder(trajFour6.end()) // // .lineToLinearHeading(new Pose2d(107,26, Math.toRadians(30))) // .addDisplacementMarker( () -> { // wobblemech.extend(); // }) // .addDisplacementMarker(() -> { // //drop wobble // wobblemech.letGo(); // }) // // .build(); // trajectoryRing4.add(trajFour7); // // // // drop wobble // // // //park // Trajectory trajFour9 = drive.trajectoryBuilder(trajFour7.end()) // .lineTo(new Vector2d(68,-10)) // .addTemporalMarker(.5, () -> { // // raise the linkage // // shooter.setNoPIDPower(.9); // hopper.lower(); // wobblemech.retract(); // }) // .build(); // trajectoryRing4.add(trajFour9); // // // // /* // case 1 // */ // // //power shots // Trajectory trajOne1 = drive.trajectoryBuilder(startPose) // .splineToConstantHeading(new Vector2d(26,12),0) // .addTemporalMarker(.2, () ->{ // shooter.motorSetPIDpower(.92); // hopper.raise(); // angleFlap.setPosition(.37); // }) // .addTemporalMarker(.1, () ->{ // wobblemech.idle(); // }) // .build(); // trajectoryRing1.add(trajOne1); // // Trajectory trajOne15 = drive.trajectoryBuilder(trajOne1.end()) // .lineToConstantHeading(new Vector2d(38,12)) // .addTemporalMarker(.5, () ->{ // angleFlap.setPosition(.5); // }) // .addTemporalMarker(2, () ->{ // angleFlap.setPosition(highGoalFlap); // }) // .addDisplacementMarker(() -> { // hopper.raise(); // }) // // .build(); // // trajectoryRing1.add(trajOne15); // // // // //drop wobble // Trajectory trajOne2 = drive.trajectoryBuilder(trajOne15.end(), false) // .splineTo(new Vector2d(94,0), Math.toRadians(45)) // // .addDisplacementMarker(() -> { // //drop wobble // wobblemech.letGo(); // angleFlap.setPosition(.5); // // }) // .build(); // trajectoryRing1.add(trajOne2); // // // Trajectory trajOne5 = drive.trajectoryBuilder(trajOne2.end()) // .lineToLinearHeading(new Pose2d(16,4,Math.toRadians(90)), new MinVelocityConstraint(Arrays.asList( // new AngularVelocityConstraint(DriveConstants.MAX_ANG_VEL), // new MecanumVelocityConstraint(55, DriveConstants.TRACK_WIDTH) // ) // ), new ProfileAccelerationConstraint(DriveConstants.MAX_ACCEL)) // .addDisplacementMarker(() -> { // //drop wobble // wobblemech.grip(); // }) // .addTemporalMarker(.5, () -> { // wobblemech.extend(); // wobblemech.letGo(); // }) // .build(); // trajectoryRing1.add(trajOne5); // // // drop wobble // Trajectory trajOne7 = drive.trajectoryBuilder(trajOne5.end()) // .splineTo(new Vector2d(89,-6), Math.toRadians(45)) // .addDisplacementMarker(() -> { // wobblemech.letGo(); // }) // .build(); // trajectoryRing1.add(trajOne7); // // //park // Trajectory trajOne8 = drive.trajectoryBuilder(trajOne7.end()) // .lineTo(new Vector2d(68,-10)) // .addTemporalMarker(.5, () -> { // // raise the linkage // // shooter.setNoPIDPower(.9); // hopper.lower(); // wobblemech.retract(); // }) // .build(); // trajectoryRing1.add(trajOne8); // // // /* // case 0 // */ // // // Trajectory trajZero1 = drive.trajectoryBuilder(startPose) // .splineToConstantHeading(new Vector2d(54.5,14),0) // .addTemporalMarker(.5, () ->{ // shooter.motorSetPIDpower(1); // hopper.raise(); // angleFlap.setPosition(.33); // }) // .addTemporalMarker(.1, () ->{ // wobblemech.idle(); // }) // .build(); // trajectoryRing0.add(trajZero1); // // //drop wobble // Trajectory trajZero2 = drive.trajectoryBuilder(trajZero1.end(), false) // .splineTo(new Vector2d(70,18), Math.toRadians(45)) // .addTemporalMarker(.5, () -> { // // raise the linkage // hopper.lower(); // angleFlap.setPosition(.5); // }) // .addDisplacementMarker(() -> { // //drop wobble // wobblemech.letGo(); // angleFlap.setPosition(highGoalFlap); // // }) // .build(); // trajectoryRing0.add(trajZero2); // //// //come to stack //// Trajectory trajZero3 = drive.trajectoryBuilder(trajZero2.end()) //// .lineToLinearHeading(new Pose2d(40,-10, Math.toRadians(90))) //// .addTemporalMarker(.5, () -> { //// // bring back the wobble //// wobblemech.letGo(); //// wobblemech.retract(); //// //// }) //// .build(); //// trajectoryRing0.add(trajZero3); // // //// Trajectory trajZero4 = drive.trajectoryBuilder(trajZero2.end()) //// .lineToConstantHeading(new Vector2d(40,3), new DriveConstraints(65, 65.50393309, 0.0, //// Math.toRadians(359.7672057337132), Math.toRadians(359.7672057337132), 0.0)) //// .addTemporalMarker(.5, () -> { //// wobblemech.extend(); //// wobblemech.letGo(); //// }) //// .build(); //// trajectoryRing0.add(trajZero4); // // // Trajectory trajZero4 = drive.trajectoryBuilder(trajZero2.end()) // .lineToLinearHeading(new Pose2d(16,4, Math.toRadians(90)), new MinVelocityConstraint(Arrays.asList( // new AngularVelocityConstraint(DriveConstants.MAX_ANG_VEL), // new MecanumVelocityConstraint(55, DriveConstants.TRACK_WIDTH) // ) // ), new ProfileAccelerationConstraint(DriveConstants.MAX_ACCEL)) // // .addTemporalMarker(.5, () -> { // //shooter.setNoPIDPower(.9); // wobblemech.extend(); // shooter.motorSetPIDpower(0); // }) // // .build(); // trajectoryRing0.add(trajZero4); // // // //shooting rings in high goal // // // // // drop wobble // Trajectory trajZero5 = drive.trajectoryBuilder(trajZero4.end()) // .splineTo(new Vector2d(66,19), Math.toRadians(45)) // .addDisplacementMarker(() -> { // wobblemech.letGo(); // }) // .build(); // trajectoryRing0.add(trajZero5); // // //park // Trajectory trajZero6 = drive.trajectoryBuilder(trajZero5.end()) // .lineTo(new Vector2d(68,-10)) // .addTemporalMarker(.5, () -> { // // raise the linkage // // shooter.setNoPIDPower(.9); // hopper.lower(); // wobblemech.retract(); // }) // .build(); // trajectoryRing0.add(trajZero6); // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // } // // // // // // // //}
true
55e93f88ad6ee290906c80b5b792149bc459de7a
Java
Yash0494/JenkinsHelloWorld
/HelloWorld.java
UTF-8
160
1.671875
2
[]
no_license
public class HelloWorld { public static void main(String[]args){ System.out.println("Made some changes in github directly to avoid pusing of code"); } }
true
7632f1756b499e34780d0641d51ad4baa489f36d
Java
tanveerafzal/screening
/src/main/java/com/rms/services/schema/CountryDetails.java
UTF-8
4,133
2.15625
2
[]
no_license
package com.rms.services.schema; import java.math.BigInteger; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * CountryDetails entity. * * <p> * Java class for CountryDetails complex type. * * <p> * The following schema fragment specifies the expected content contained within * this class. * * <pre> * &lt;complexType name="CountryDetails"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}integer"/> * &lt;element name="person" type="{http://www.remitservices.com/dowjone}Person"/> * &lt;element name="entities" type="{http://www.remitservices.com/dowjone}Entities"/> * &lt;element name="countryType" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="code" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="value" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CountryDetails", propOrder = { "id", "person", "entities", "countryType", "code", "value" }) public class CountryDetails { @XmlElement(required = true) protected BigInteger id; @XmlElement(required = true) protected Person person; @XmlElement(required = true) protected Entities entities; @XmlElement(required = true) protected String countryType; @XmlElement(required = true) protected String code; @XmlElement(required = true) protected String value; /** * Gets the value of the id property. * * @return possible object is {@link BigInteger } * */ public BigInteger getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link BigInteger } * */ public void setId(BigInteger value) { this.id = value; } /** * Gets the value of the person property. * * @return possible object is {@link Person } * */ public Person getPerson() { return person; } /** * Sets the value of the person property. * * @param value * allowed object is {@link Person } * */ public void setPerson(Person value) { this.person = value; } /** * Gets the value of the entities property. * * @return possible object is {@link Entities } * */ public Entities getEntities() { return entities; } /** * Sets the value of the entities property. * * @param value * allowed object is {@link Entities } * */ public void setEntities(Entities value) { this.entities = value; } /** * Gets the value of the countryType property. * * @return possible object is {@link String } * */ public String getCountryType() { return countryType; } /** * Sets the value of the countryType property. * * @param value * allowed object is {@link String } * */ public void setCountryType(String value) { this.countryType = value; } /** * Gets the value of the code property. * * @return possible object is {@link String } * */ public String getCode() { return code; } /** * Sets the value of the code property. * * @param value * allowed object is {@link String } * */ public void setCode(String value) { this.code = value; } /** * Gets the value of the value property. * * @return possible object is {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is {@link String } * */ public void setValue(String value) { this.value = value; } }
true
83f87bceedf436364c397e816671fecbb00e7321
Java
neshoj/opensrp-server-web
/src/main/java/org/opensrp/web/config/security/filter/XssPreventionRequestWrapper.java
UTF-8
3,829
2.234375
2
[ "Apache-2.0" ]
permissive
package org.opensrp.web.config.security.filter; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.JsonNodeType; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.owasp.encoder.Encode; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.Iterator; import java.util.Map; public class XssPreventionRequestWrapper extends HttpServletRequestWrapper { private static Logger logger = LogManager.getLogger(XssPreventionRequestWrapper.class); private static ObjectMapper mapper = new ObjectMapper(); private byte[] rawData; private HttpServletRequest request; private ResettableServletInputStream servletStream; public XssPreventionRequestWrapper(HttpServletRequest request) { super(request); this.request = request; this.servletStream = new ResettableServletInputStream(); } @Override public ServletInputStream getInputStream() throws IOException { if (rawData == null) { rawData = IOUtils.toByteArray(this.request.getInputStream()); servletStream.stream = new ByteArrayInputStream(rawData); } updateParameters(); return servletStream; } @Override public BufferedReader getReader() throws IOException { if (rawData == null) { rawData = IOUtils.toByteArray(this.request.getReader(),StandardCharsets.UTF_8); servletStream.stream = new ByteArrayInputStream(rawData); } updateParameters(); return new BufferedReader(new InputStreamReader(servletStream)); } private void updateParameters() throws IOException { String requestBody = new String(rawData, StandardCharsets.UTF_8); if (isValidJSON(requestBody)) { JsonNode jsonNode = mapper.readTree(requestBody); JsonNode updatedJsonNode = encode(jsonNode); String encodedJsonString = updatedJsonNode.toString(); rawData = encodedJsonString.getBytes(); servletStream.stream = new ByteArrayInputStream(rawData); } } private static JsonNode encode(JsonNode node) { if (node.isValueNode()) { if (JsonNodeType.STRING == node.getNodeType()) { return JsonNodeFactory.instance.textNode(Encode.forHtmlContent(node.asText())); } else if (JsonNodeType.NULL == node.getNodeType()) { return null; } else { return node; } } else if (node.isNull()) { return null; } else if (node.isArray()) { ArrayNode arrayNode = (ArrayNode) node; ArrayNode cleanedNewArrayNode = mapper.createArrayNode(); for (JsonNode jsonNode : arrayNode) { cleanedNewArrayNode.add(encode(jsonNode)); } return cleanedNewArrayNode; } else { ObjectNode encodedObjectNode = mapper.createObjectNode(); for (Iterator<Map.Entry<String, JsonNode>> it = node.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> entry = it.next(); encodedObjectNode.set(Encode.forHtmlContent(entry.getKey()), encode(entry.getValue())); } return encodedObjectNode; } } private static boolean isValidJSON(final String json) throws IOException { boolean valid = true; try { mapper.readTree(json); } catch (JsonProcessingException e) { logger.error("Error while processing JSON", e); valid = false; } return valid; } private class ResettableServletInputStream extends ServletInputStream { private InputStream stream; @Override public int read() throws IOException { return stream.read(); } } }
true
d789586f56173d4c33088dd87d5b168576ee26c9
Java
JoeWolski/CMSC436
/ThermalViz/app/src/main/java/com/example/team436/thermalviz/Point.java
UTF-8
269
2.640625
3
[ "BSD-3-Clause" ]
permissive
package com.example.team436.thermalviz; public class Point { public int x; public int y; public float temperature; public Point(int x, int y, float temperature){ this.x = x; this.y = y; this.temperature = temperature; } }
true
ad3616c6affb49eaa455da22fe432d7eccbf87c8
Java
GhostNwa/election-eva-admin
/admin/admin-common/src/main/java/no/valg/eva/admin/common/MessageTranslator.java
UTF-8
109
1.523438
2
[]
no_license
package no.valg.eva.admin.common; public interface MessageTranslator { String translate(String message); }
true
2ea8e071ae5192b3a08f390d24c102b70f487bab
Java
ync-it-2020/spring_yolo
/src/main/java/kr/ync/service/AlbumService.java
UTF-8
792
2.015625
2
[]
no_license
package kr.ync.service; import java.util.List; import kr.ync.domain.AlbumVO; import kr.ync.domain.ArtistVO; import kr.ync.domain.Criteria; public interface AlbumService { public int album_register(AlbumVO album); // 전체 글 목록 public List<AlbumVO> getList(); // 글목록 페이징 public List<AlbumVO> getListWithPaging(Criteria cri); // 추가 public int getTotal(Criteria cri); // 글 상세보기 public AlbumVO get(int album_idx); // 글 수정 public boolean album_modify(AlbumVO album); // 글 삭제 public boolean album_remove(int album_idx); //프론트 public List<AlbumVO> frontAlbum(); //프론트 앨범 페이지 public List<AlbumVO> frontAlbum_getListWithPaging(Criteria cri); public List<AlbumVO> frontAlbum_get(int album_idx); }
true
6597d08b9d116ff748561896ef5cb916f0a52d59
Java
jyj2187/SpringMVCHomework2
/src/main/java/kr/ac/hansung/controller/MyClassController.java
UTF-8
1,636
2.265625
2
[]
no_license
package kr.ac.hansung.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import kr.ac.hansung.model.MyClass; import kr.ac.hansung.service.MyClassService; @Controller public class MyClassController { @Autowired private MyClassService myclassService; @RequestMapping("/semester") public String showSemester(Model model) { List<MyClass> myclass = myclassService.getCurrent(); model.addAttribute("myclass", myclass); return "semester"; } @RequestMapping("/semesterdetail") public String showSemesterdetail(Model model, Integer year, Integer semester) { List<MyClass> myclassd = myclassService.getCurrent2(year, semester); model.addAttribute("year", year); model.addAttribute("semester", semester); model.addAttribute("myclassd", myclassd); return "semesterdetail"; } @RequestMapping("/registerclass") public String register(Model model) { return "registerclass"; } @RequestMapping("/doregister") public String doRegister(Model model, MyClass myclass, BindingResult result) { myclassService.insert(myclass); return "classregistered"; } @RequestMapping("/registeredclass") public String showRegisteredclass(Model model) { List<MyClass> registeredclass = myclassService.getregisteredclass(); model.addAttribute("registeredclass", registeredclass); return "registeredclass"; } }
true
20649e15073b4525b92c308ccc4f7c328a37fdd2
Java
gekalogiros/accounts-api
/src/main/java/com/gkalogiros/accounts/exceptions/BusinessRuleException.java
UTF-8
195
2.0625
2
[]
no_license
package com.gkalogiros.accounts.exceptions; public class BusinessRuleException extends RuntimeException { public BusinessRuleException(final String message) { super(message); } }
true
e6079f81cb975dcc21d314fbcb0fe0fdf9ef32a4
Java
pengchenglpc/SMIS
/src/com/smis/service/production/impl/ProcedureServiceImpl.java
UTF-8
4,000
2.1875
2
[]
no_license
package com.smis.service.production.impl; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.smis.dao.production.IProcedureDao; import com.smis.dao.production.IProducePlanDao; import com.smis.dao.production.IWorkingDao; import com.smis.model.production.ProducePlan; import com.smis.model.production.Working; import com.smis.service.production.IProcedureService; import net.sf.json.JSONObject; @Service("procedureService") public class ProcedureServiceImpl implements IProcedureService { @Autowired private IProcedureDao procedureDao; @Autowired private IWorkingDao workingDao; @Autowired private IProducePlanDao producePlanDao; @Override public List<JSONObject> statisticalAnalysis(ProducePlan plan) { List list = procedureDao.statisticalAnalysis(plan); List<JSONObject> arr = new ArrayList<JSONObject>(); for(Object obj : list){ Object[] _arr = (Object[])obj; Long value = (Long)_arr[0]; String name = (String)_arr[1]; JSONObject json = new JSONObject(); json.put("value", value); json.put("name", name); arr.add(json); } return arr; } @Override public List<Working> findAllWorking() { return this.workingDao.findAll(); } @Override public List<JSONObject> findProduceNo() { List list = this.producePlanDao.findProduceNo(); List<JSONObject> arr = new ArrayList<JSONObject>(); for(Object o : list){ JSONObject obj = new JSONObject(); obj.put("name", o); arr.add(obj); } return arr; } @Override public List<JSONObject> findDept() { List list = this.producePlanDao.findDept(); List<JSONObject> arr = new ArrayList<JSONObject>(); for(Object o : list){ JSONObject obj = new JSONObject(); obj.put("name", o); arr.add(obj); } return arr; } @Override public List<JSONObject> deptAnalysis(ProducePlan plan) { List list = procedureDao.deptAnalysis(plan); List<JSONObject> arr = new ArrayList<JSONObject>(); for(Object obj : list){ Object[] _arr = (Object[])obj; Long value = (Long)_arr[0]; String name = (String)_arr[1]; JSONObject json = new JSONObject(); json.put("value", value); json.put("name", name); arr.add(json); } return arr; } @Override public Map<String, Object> dutyCompare(ProducePlan plan) { List list = procedureDao.dutyCompare(plan); Set<String> technology = new HashSet<String>(); List<String> monthSet = new ArrayList<String>(); List<JSONObject> arr = new ArrayList<JSONObject>(); for(Object obj : list){ Object[] datas = (Object[])obj; Long value = ((BigInteger)datas[0]).longValue(); String name = (String)datas[1]; Integer month = (Integer)datas[2]; technology.add(name); JSONObject json = new JSONObject(); json.put("value", value); json.put("name", name); json.put("month", month + "月"); if(monthSet.indexOf(month + "月") < 0) monthSet.add(month + "月"); arr.add(json); } Map<String, List> dataMap = new HashMap<String, List>(); for(String tech : technology){ List data = new ArrayList(); for(String month : monthSet){ System.out.println("month--------->" + month); boolean existFlag = false; for(JSONObject json : arr){ if(month.equals(json.get("month")) && tech.equals(json.get("name"))){ data.add(json.get("value")); existFlag = true; break; } } if(!existFlag){ data.add(0); } } dataMap.put(tech, data); } Map<String, Object> map = new HashMap<String, Object>(); map.put("data", dataMap); map.put("month", monthSet); map.put("technology", technology); System.out.println(JSONObject.fromObject(map)); return map; } }
true
269d8a19ef7fec0343686ce3959b51a2ac920321
Java
imxushuai/leyou
/ly-auth/ly-auth-service/src/main/java/com/leyou/auth/config/JwtProperties.java
UTF-8
1,343
2.453125
2
[ "Apache-2.0" ]
permissive
package com.leyou.auth.config; import com.leyou.auth.utils.RsaUtils; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.properties.ConfigurationProperties; import javax.annotation.PostConstruct; import java.nio.file.Paths; import java.security.PrivateKey; import java.security.PublicKey; @Data @Slf4j @ConfigurationProperties("ly.jwt") public class JwtProperties { private String secret; private String pubKeyPath; private String priKeyPath; private int expire; private PublicKey publicKey; // 公钥 private PrivateKey privateKey; // 私钥 @PostConstruct public void init() { try { checkPubAndPri(); publicKey = RsaUtils.getPublicKey(pubKeyPath); privateKey = RsaUtils.getPrivateKey(priKeyPath); } catch (Exception e) { log.error("初始化公钥私钥失败", e); throw new RuntimeException(); } } /** * 检查公钥与私钥文件是否存在 */ private void checkPubAndPri() throws Exception { if (!Paths.get(pubKeyPath).toFile().exists() || !Paths.get(priKeyPath).toFile().exists()) {// 公钥或私钥不存在 // 重新创建公私钥文件 RsaUtils.generateKey(pubKeyPath, priKeyPath, secret); } } }
true
cedd162ce3175cec6fc3a592c53fc1efc0b1ca4d
Java
zhyzh/Doctor
/app/src/main/java/com/zhang/nong/doctor/com/java/beans/Home_recommend.java
UTF-8
1,939
2.3125
2
[ "Apache-2.0" ]
permissive
package com.zhang.nong.doctor.com.java.beans; import java.io.Serializable; /** * Created by zhangyunzhen on 2016/5/24. */ public class Home_recommend implements Serializable { private String home_recommend_type;//农机类型 private String home_recommend_linkman;//联系人 private String home_recommend_location;//农机主的位置 private String home_recommend_phone;//联系电话 private int home_recommend_item; public Home_recommend(String home_recommend_type, String home_recommend_linkman, String home_recommend_location, String home_recommend_phone, int home_recommend_item) { this.home_recommend_type = home_recommend_type; this.home_recommend_linkman = home_recommend_linkman; this.home_recommend_location = home_recommend_location; this.home_recommend_phone = home_recommend_phone; this.home_recommend_item = home_recommend_item; } public String getHome_recommend_type() { return home_recommend_type; } public void setHome_recommend_type(String home_recommend_type) { this.home_recommend_type = home_recommend_type; } public String getHome_recommend_linkman() { return home_recommend_linkman; } public void setHome_recommend_linkman(String home_recommend_linkman) { this.home_recommend_linkman = home_recommend_linkman; } public String getHome_recommend_location() { return home_recommend_location; } public void setHome_recommend_location(String home_recommend_location) { this.home_recommend_location = home_recommend_location; } public String getHome_recommend_phone() { return home_recommend_phone; } public void setHome_recommend_phone(String home_recommend_phone) { this.home_recommend_phone = home_recommend_phone; } public int getHome_recommend_item() { return home_recommend_item; } public void setHome_recommend_item(int home_recommend_item) { this.home_recommend_item = home_recommend_item; } }
true
822013fa1f23d092abea58eefc81c19b501990b2
Java
zhanght86/realestate
/src/main/java/com/szhome/cq/utils/ImageUtil.java
GB18030
3,653
2.71875
3
[]
no_license
/** * Project Name:dxtx_re * File Name:ImageUtil.java * Package Name:com.szhome.cq.utils * Date:2014-6-1711:58:00 * Copyright (c) 2014, DXTX All Rights Reserved. * */ package com.szhome.cq.utils; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.WritableRaster; import java.io.IOException; import java.io.OutputStream; import javax.imageio.ImageIO; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; /** * ImageUtil ͼ񹤾. * * @author dxtx * @version * @since JDK 1.6 * @see */ public class ImageUtil { /** * Scale <b>srcImg</b> and write to <b>os</b>. * * @param srcImg * @param os * OutputStream * @param width * @param height * @param suffix * ͼƬĸʽ gif JPG png * @since JDK 1.6 */ public static void createThumbnail(BufferedImage srcImg, OutputStream os, int width,int height, String suffix) { try { double Ratio = 0.0; Image Itemp = srcImg.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH); if ((srcImg.getHeight() > width) || (srcImg.getWidth() > height)) { if (srcImg.getHeight() > srcImg.getWidth()) Ratio = (double)width / srcImg.getHeight(); else Ratio = (double)height / srcImg.getWidth(); } AffineTransformOp op = new AffineTransformOp(AffineTransform .getScaleInstance(Ratio, Ratio), null); Itemp = op.filter(srcImg, null); ImageIO.write((BufferedImage) Itemp, suffix, os); os.close(); } catch (IOException e) { e.printStackTrace(); } } /** * ԭͼƬBufferedImageͼ * @param sourceԭͼƬBufferedImage * @param targetW:ͼĿ * @param targetH:ͼĸ * @param os */ public static void resize(BufferedImage source,OutputStream os, int targetW,int targetH,boolean equalProportion){ int type=source.getType(); BufferedImage target=null; double sx=(double)targetW/source.getWidth(); double sy=(double)targetH/source.getHeight(); //ʵtargetWtargetHΧʵֵȱ if(equalProportion){ if(sx>sy){ sx=sy; targetW=(int)(sx*source.getWidth()); }else{ sy=sx; targetH=(int)(sx*source.getHeight()); } } if(type==BufferedImage.TYPE_CUSTOM){ ColorModel cm=source.getColorModel(); WritableRaster raster=cm.createCompatibleWritableRaster(targetW,targetH); boolean alphaPremultiplied=cm.isAlphaPremultiplied(); target=new BufferedImage(cm,raster,alphaPremultiplied,null); }else{ target=new BufferedImage(targetW,targetH,type); Graphics2D g=target.createGraphics(); g.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY); g.drawRenderedImage(source,AffineTransform.getScaleInstance(sx,sy)); g.dispose(); } JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os); try { encoder.encode(target); os.close(); } catch (IOException e) { e.printStackTrace(); } //return target; } }
true
0f79c59ec8869c403757c66d2ba717d896a4c839
Java
ishonowo/supportportal.backend
/src/main/java/com/supportportal/app/service/impl/UserServiceImpl.java
UTF-8
10,977
1.921875
2
[]
no_license
package com.supportportal.app.service.impl; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Date; import java.util.List; import static com.supportportal.app.constant.FileConstant.USER_FOLDER; import static com.supportportal.app.constant.FileConstant.DIRECTORY_CREATED; import static com.supportportal.app.constant.FileConstant.EXTENSION; import static com.supportportal.app.constant.FileConstant.FILE_SAVED_IN_FILE_SYSTEM; import static com.supportportal.app.constant.FileConstant.USER_IMAGE_PATH; import static com.supportportal.app.constant.FileConstant.FORWARD_SLASH; import static com.supportportal.app.constant.FileConstant.BACK_SLASH; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import javax.transaction.Transactional; import static com.supportportal.app.constant.UserImplConstant.NO_USER_FOUND_BY_EMAIL; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.apache.commons.lang3.StringUtils.isNotBlank; import org.apache.commons.lang3.RandomStringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; //import org.springframework.transaction.annotation.Transactional; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.supportportal.app.service.LoginAttemptService; import com.supportportal.app.service.SpringEmailService; import com.supportportal.app.domain.User; import com.supportportal.app.domain.UserPrincipal; import com.supportportal.app.enumeration.Role; import com.supportportal.app.exception.domain.EmailExistException; import com.supportportal.app.exception.domain.EmailNotFoundException; import com.supportportal.app.exception.domain.UserNotFoundException; import com.supportportal.app.exception.domain.UsernameExistException; import com.supportportal.app.repository.UserRepository; import static com.supportportal.app.enumeration.Role.*; import com.supportportal.app.service.UserService; import static com.supportportal.app.constant.UserImplConstant.*; import static com.supportportal.app.constant.FileConstant.DEFAULT_USER_IMAGE_PATH; @Service @Transactional @Qualifier("UserDetailsService") public class UserServiceImpl implements UserService, UserDetailsService{ private Logger LOGGER= LoggerFactory.getLogger(getClass()); private UserRepository userRepo; private BCryptPasswordEncoder passwordEncoder; private LoginAttemptService loginAttemptService; private SpringEmailService emailService; @Autowired public UserServiceImpl(UserRepository userRepo, BCryptPasswordEncoder passwordEncoder, LoginAttemptService loginAttemptService, SpringEmailService emailService) { this.userRepo= userRepo; this.passwordEncoder=passwordEncoder; this.loginAttemptService= loginAttemptService; this.emailService= emailService; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepo.findUserByUsername(username); if(user==null) { LOGGER.error(NO_USER_FOUND_BY_USERNAME+username); throw new UsernameNotFoundException(NO_USER_FOUND_BY_USERNAME+username); } else { validateLoginAttempt(user); user.setLastLoginDateDisplay(user.getLastLoginDate()); user.setLastLoginDate(new Date()); userRepo.save(user); UserPrincipal userPrincipal = new UserPrincipal(user); LOGGER.info(USER_FOUND+username); return userPrincipal; } } private void validateLoginAttempt(User user) { if(user.isNotLocked()) { if(loginAttemptService.hasExceedMaxAttempts(user.getUsername())) { user.setNotLocked(false); } else { user.setNotLocked(true); } }else { loginAttemptService.removeUserFromLoginAttemptCache(user.getUsername()); } } @Override public User register(String firstName, String lastName, String username, String email) throws UserNotFoundException,UsernameExistException,EmailExistException{ validateNewUsernameAndEmail(EMPTY,username,email); User user = new User(); user.setUserId(generateUserId()); String password= generateUserPassword(); user.setFirstName(firstName); user.setLastName(lastName); user.setUsername(username); user.setEmail(email); user.setSignUpDate(new Date()); user.setPassword(encodePassword(password)); user.setActive(true); user.setNotLocked(true); user.setRole(ROLE_USER.name()); user.setAuthorities(ROLE_USER.getAuthorities()); user.setProfileImageUrl(getTemporaryProfileImageURL(username)); userRepo.save(user); LOGGER.info("The new user password is "+password); emailService.sendNewPasswordByEmail(firstName+' '+lastName,password,email); return user; } private String getTemporaryProfileImageURL(String username) { return ServletUriComponentsBuilder.fromCurrentContextPath().path(DEFAULT_USER_IMAGE_PATH + username) .toUriString(); } private String encodePassword(String password) { return passwordEncoder.encode(password); } private String generateUserPassword() { return RandomStringUtils.randomAlphanumeric(10); } private String generateUserId() { return RandomStringUtils.randomNumeric(10); } private User validateNewUsernameAndEmail(String currentUsername, String newUsername, String newEmail) throws UserNotFoundException,UsernameExistException,EmailExistException{ User newUserByUsername= findUserByUsername(newUsername); User newUserByEmail= findUserByEmail(newEmail); if(isNotBlank(currentUsername)) { User currentUser = findUserByUsername(currentUsername); if(currentUser==null) { throw new UserNotFoundException(NO_USER_FOUND_BY_USERNAME+currentUsername); } if(newUserByUsername != null && !currentUser.getId().equals(newUserByUsername.getId())) { throw new UsernameExistException(USERNAME_ALREADY_EXISTS); } if(newUserByEmail != null && !currentUser.getId().equals(newUserByEmail.getId())) { throw new EmailExistException(EMAIL_ALREADY_EXISTS); } return currentUser; } else {//for new user creation if(newUserByUsername!= null) { throw new UsernameExistException(USERNAME_ALREADY_EXISTS); } if(newUserByEmail != null) { throw new EmailExistException(EMAIL_ALREADY_EXISTS); } return null; } } @Override public List<User> getUsers() { return userRepo.findAll(); } @Override public User findUserByUsername(String username) { return userRepo.findUserByUsername(username); } @Override public User findUserByEmail(String email) { return userRepo.findUserByEmail(email); } @Override public User addNewUser(String firstName, String lastName, String username, String email, String role, boolean isNonLocked, boolean isActive, MultipartFile profileImage) throws UserNotFoundException, UsernameExistException, EmailExistException, IOException { validateNewUsernameAndEmail(EMPTY, username, email); User user = new User(); String password= generateUserPassword(); user.setUserId(generateUserId()); user.setFirstName(firstName); user.setLastName(lastName); user.setUsername(username); user.setEmail(email); user.setSignUpDate(new Date()); user.setPassword(encodePassword(password)); user.setActive(true); user.setNotLocked(true); user.setRole(getRoleEnumName(role).name()); user.setAuthorities(getRoleEnumName(role).getAuthorities()); user.setProfileImageUrl(getTemporaryProfileImageUrl(username)); userRepo.save(user); saveProfileImage(user, profileImage); LOGGER.info("The new user password is "+password); return user; } private void saveProfileImage(User user, MultipartFile profileImage) throws IOException { if (profileImage != null) { Path userFolder= Paths.get(USER_FOLDER + user.getUsername()).toAbsolutePath().normalize(); if(!Files.exists(userFolder)) { Files.createDirectories(userFolder); LOGGER.info(DIRECTORY_CREATED + userFolder); } Files.deleteIfExists(Paths.get(userFolder + user.getUsername()+EXTENSION)); Files.copy(profileImage.getInputStream(), userFolder.resolve(user.getUsername()+EXTENSION), REPLACE_EXISTING); //Files.createFile user.setProfileImageUrl(setProfileImageUri(user.getUsername())); userRepo.save(user); LOGGER.info(FILE_SAVED_IN_FILE_SYSTEM + profileImage.getOriginalFilename()); } } private String setProfileImageUri(String username) { return ServletUriComponentsBuilder.fromCurrentContextPath().path(USER_IMAGE_PATH +"/"+ username + "/" + username + EXTENSION).toUriString() ; } private String getTemporaryProfileImageUrl(String username) { return ServletUriComponentsBuilder.fromCurrentContextPath().path(DEFAULT_USER_IMAGE_PATH + username) .toUriString() ; } private Role getRoleEnumName(String role) { return Role.valueOf(role.toUpperCase()); } @Override public User updateUser(String currentUsername, String newFirstName, String newLastName, String newUsername, String newEmail, String newRole, boolean isNonLocked, boolean isActive, MultipartFile profileImage) throws UserNotFoundException, UsernameExistException, EmailExistException, IOException{ User currentUser= validateNewUsernameAndEmail(currentUsername, newUsername, newEmail); currentUser.setFirstName(newFirstName); currentUser.setLastName(newLastName); currentUser.setUsername(newUsername); currentUser.setEmail(newEmail); currentUser.setActive(isActive); currentUser.setNotLocked(isNonLocked); currentUser.setRole(getRoleEnumName(newRole).name()); currentUser.setAuthorities(getRoleEnumName(newRole).getAuthorities()); userRepo.save(currentUser); saveProfileImage(currentUser, profileImage); return currentUser; } @Override public void deleteUser(long id) { userRepo.deleteById(id); } @Override public void resetPassword(String email) throws EmailNotFoundException { User user= userRepo.findUserByEmail(email); if(user== null) { throw new EmailNotFoundException(NO_USER_FOUND_BY_EMAIL + email); } String password= generateUserPassword(); user.setPassword(encodePassword(password)); userRepo.save(user); emailService.sendNewPasswordByEmail(user.getFirstName()+' '+user.getLastName(), password, user.getEmail()); } @Override public User updateProfileImage(String username, MultipartFile profileImage) throws UserNotFoundException, UsernameExistException, EmailExistException, IOException { User user= validateNewUsernameAndEmail(username, null, null); saveProfileImage(user,profileImage); return user; } }
true
172c9a92ddbe18c85ee1746b287f6a2e4b3ee64e
Java
vadimka099/labs-oop
/laba1/src/main.java
UTF-8
782
3.140625
3
[]
no_license
import java.util.Scanner; public class main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] array; int s1=0; int s2=0; int s3=0; int i=0; int lenght=in.nextInt(); array = new int[5]; for (i = 0; i < lenght; i++) { array[i] = in.nextInt(); s1=s1+array[i]; } i=0; while(i<lenght){ s2=s2+array[i]; i++; } i=0; do{ s3=s3+array[i]; i++; }while (i<lenght); System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(array.length); } }
true
7764dc6f9b0332132303dcf935c607a3e28e9b16
Java
formakers-dev/fomes-mobile-app
/app/src/main/java/com/formakers/fomes/betatest/FinishedBetaTestDetailPresenter.java
UTF-8
6,764
1.710938
2
[]
no_license
package com.formakers.fomes.betatest; import android.content.Intent; import android.net.Uri; import android.text.TextUtils; import com.formakers.fomes.R; import com.formakers.fomes.common.constant.FomesConstants; import com.formakers.fomes.common.dagger.AnalyticsModule; import com.formakers.fomes.common.helper.AndroidNativeHelper; import com.formakers.fomes.common.helper.FomesUrlHelper; import com.formakers.fomes.common.helper.ImageLoader; import com.formakers.fomes.common.network.BetaTestService; import com.formakers.fomes.common.network.vo.BetaTest; import com.formakers.fomes.common.network.vo.Mission; import com.formakers.fomes.common.util.Log; import com.google.firebase.remoteconfig.FirebaseRemoteConfig; import java.util.NoSuchElementException; import javax.inject.Inject; import retrofit2.adapter.rxjava.HttpException; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; @FinishedBetaTestDetailDagger.Scope class FinishedBetaTestDetailPresenter implements FinishedBetaTestDetailContract.Presenter { private static final String TAG = "FinishedBetaTestDetailPresenter"; private FinishedBetaTestDetailContract.View view; private AnalyticsModule.Analytics analytics; private ImageLoader imageLoader; private BetaTestService betaTestService; private FomesUrlHelper fomesUrlHelper; private AndroidNativeHelper androidNativeHelper; private FirebaseRemoteConfig remoteConfig; private BetaTest betaTest; private FinishedBetaTestAwardPagerAdapterContract.Model finishedBetaTestAwardPagerModel; @Inject public FinishedBetaTestDetailPresenter(FinishedBetaTestDetailContract.View view, AnalyticsModule.Analytics analytics, ImageLoader imageLoader, BetaTestService betaTestService, FomesUrlHelper fomesUrlHelper, AndroidNativeHelper androidNativeHelper, FirebaseRemoteConfig remoteConfig) { this.view = view; this.analytics = analytics; this.imageLoader = imageLoader; this.betaTestService = betaTestService; this.fomesUrlHelper = fomesUrlHelper; this.androidNativeHelper = androidNativeHelper; this.remoteConfig = remoteConfig; } @Override public AnalyticsModule.Analytics getAnalytics() { return analytics; } @Override public ImageLoader getImageLoader() { return imageLoader; } @Override public void setFinishedBetaTestAwardPagerAdapterModel(FinishedBetaTestAwardPagerAdapterContract.Model model) { this.finishedBetaTestAwardPagerModel = model; } @Override public void setBetaTest(BetaTest betaTest) { this.betaTest = betaTest; } @Override public void requestEpilogueAndAwards(String betaTestId) { this.betaTestService.getEpilogue(betaTestId) .observeOn(AndroidSchedulers.mainThread()) .doOnSuccess(epilogue -> this.view.bindEpilogueView(epilogue)) .observeOn(Schedulers.io()) .flatMap(epilogue -> this.betaTestService.getAwardRecords(betaTestId)) .doOnSuccess(awardRecords -> this.finishedBetaTestAwardPagerModel.addAll(awardRecords)) .observeOn(AndroidSchedulers.mainThread()) .subscribe(awardRecords -> this.view.refreshAwardPagerView(), e -> { Log.e(TAG, String.valueOf(e)); if (e instanceof HttpException && ((HttpException) e).code() == 404) { this.view.disableEpilogueView(); this.view.bindAwardRecordsWithRewardItems(betaTest.getRewards().getList()); } if (e instanceof NoSuchElementException || betaTest.getRewards().getList() == null || betaTest.getRewards().getList().size() <= 0) { this.view.hideAwardsView(); } }); } @Override public void requestRecheckableMissions(String betaTestId) { this.betaTestService.getCompletedMissions(betaTestId) .toObservable() .concatMap(Observable::from) .filter(Mission::isRecheckable) .toList() .observeOn(AndroidSchedulers.mainThread()) .subscribe(missions -> { Log.i(TAG, String.valueOf(missions)); if (missions != null && missions.size() > 0) { this.view.bindMyAnswersView(missions); } }, e -> Log.e(TAG, "getRecheckableMissions) " + e)); } @Override public void emitRecheckMyAnswer(Mission mission) { this.view.showNoticePopupView(R.string.finished_betatest_recheck_my_answer_title, R.string.finished_betatest_recheck_my_answer_popup_subtitle, R.drawable.notice_recheck_my_answer, R.string.finished_betatest_recheck_my_answer_popup_positive_button_text, v -> processMissionItemAction(mission)); } private void processMissionItemAction(Mission missionItem) { // TODO : [중복코드] BetaTestHelper 등과 같은 로직으로 공통화 시킬 필요 있음 String action = missionItem.getAction(); if (TextUtils.isEmpty(action)) { return; } String url = fomesUrlHelper.interpretUrlParams(action); Uri uri = Uri.parse(url); if (FomesConstants.BetaTest.Mission.TYPE_PLAY.equals(missionItem.getType())) { Intent intent = this.androidNativeHelper.getLaunchableIntent(missionItem.getPackageName()); if (intent != null) { view.startActivity(intent); return; } } // below condition logic should be move to URL Manager(or Parser and so on..) if (FomesConstants.BetaTest.Mission.ACTION_TYPE_INTERNAL_WEB.equals(missionItem.getActionType()) || (uri.getQueryParameter("internal_web") != null && uri.getQueryParameter("internal_web").equals("true"))) { view.startWebViewActivity(missionItem.getTitle(), url); } else { // Default가 딥링크인게 좋을 것 같음... 여러가지 방향으로 구현가능하니까 view.startByDeeplink(Uri.parse(url)); } } }
true
e590a1f75f9a8aa167aadaaab0c14b4dba66a4c7
Java
dystudio/simple-spring-batch
/src/main/java/com/purnima/jain/springbatch/controller/SpringBatchController.java
UTF-8
3,853
2.328125
2
[]
no_license
package com.purnima.jain.springbatch.controller; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.JobParametersInvalidException; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException; import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException; import org.springframework.batch.core.repository.JobRestartException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.purnima.jain.springbatch.json.ExportDataRequestDto; import com.purnima.jain.springbatch.json.ExportDataResponseDto; @RestController public class SpringBatchController { private static final Logger logger = LoggerFactory.getLogger(SpringBatchController.class); private static AtomicBoolean isJobInProgress = new AtomicBoolean(Boolean.FALSE); @Autowired private JobLauncher jobLauncher; @Autowired @Qualifier("exportDataJob") private Job exportDataJob; @PostMapping(value = "batchjob/exportData") public ExportDataResponseDto exportData(@RequestBody ExportDataRequestDto exportDataRequestDto) throws Exception { logger.info("Entering SpringBatchController.exportData() with exportDataRequestDto :: {}", exportDataRequestDto.getIds()); ExportDataResponseDto exportDataResponseDto = new ExportDataResponseDto(); if (Boolean.TRUE.equals(isJobInProgress.get())) exportDataResponseDto.setMessage("Another Batch Job In-Progress. Please try later."); else { JobExecution jobExecution = executeDataExportJob(exportDataRequestDto.getIds()); logger.info("Status of the JobExecution :: {}", jobExecution.getStatus()); if(BatchStatus.COMPLETED.equals(jobExecution.getStatus())) exportDataResponseDto.setMessage(String.format("Batch job has finished migrating given customerIds: %s", exportDataRequestDto.getIds().toString())); else exportDataResponseDto.setMessage(String.format("Batch job could not finish migrating given customerIds: %s", exportDataRequestDto.getIds().toString())); } logger.info("Leaving SpringBatchController.exportData() with exportDataResponseDto:: {}", exportDataResponseDto); return exportDataResponseDto; } private JobExecution executeDataExportJob(List<Integer> idList) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException { JobParameters jobParameters = new JobParametersBuilder() .addString("idListStr", idList.toString()) .addString("time", ZonedDateTime.now().format(DateTimeFormatter.ISO_ZONED_DATE_TIME)) .toJobParameters(); JobExecution jobExecution = executeJob(jobParameters); return jobExecution; } private synchronized JobExecution executeJob(final JobParameters jobParameters) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException { isJobInProgress.compareAndSet(Boolean.FALSE, Boolean.TRUE); JobExecution jobExecution = jobLauncher.run(exportDataJob, jobParameters); isJobInProgress.compareAndSet(Boolean.TRUE, Boolean.FALSE); return jobExecution; } }
true
f37ce64294e13b863104be7dc4a576c86e21c1a5
Java
hubdaba/Fireplace
/merchant/Fireplace/app/src/main/java/com/thefriendlybronto/fireplace/MerchantFragment.java
UTF-8
11,329
1.882813
2
[]
no_license
package com.thefriendlybronto.fireplace; import android.accounts.AccountManager; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.google.android.gms.common.AccountPicker; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by thefriendlybronto on 8/29/15. */ public class MerchantFragment extends Fragment { private static final String TAG = MerchantFragment.class.getSimpleName(); private TextView accountNameView; private TextView merchantNameView; private TextView inputTextView; private SharedPreferences sharedPreferences; private Button insertMerchantButton; private MerchantBeaconArrayAdapter merchantBeaconArrayAdapter; private List<String> beaconIds; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); sharedPreferences = getActivity().getSharedPreferences(Constants.PREFS_NAME, 0); beaconIds = new ArrayList<>(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.merchant, container, false); accountNameView = (TextView) rootView.findViewById(R.id.merchantAccountName); accountNameView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pickUserAccount(); } }); merchantNameView = (TextView) rootView.findViewById(R.id.merchantName); inputTextView = (TextView) rootView.findViewById(R.id.editTextMerchantName); merchantBeaconArrayAdapter = new MerchantBeaconArrayAdapter(getActivity(), R.id.merchantBeaconList, beaconIds); insertMerchantButton = (Button) rootView.findViewById(R.id.insertMerchantButton); final ListView merchantBeaconListView = (ListView) rootView.findViewById(R.id.merchantBeaconList); merchantBeaconListView.setAdapter(merchantBeaconArrayAdapter); merchantBeaconListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String beaconName = merchantBeaconArrayAdapter.getItem(position); BeaconAttachmentFragment fragment = new BeaconAttachmentFragment(); Bundle bundle = new Bundle(); bundle.putString(Constants.BUNDLE_ACCOUNTNAME, accountNameView.getText().toString()); bundle.putString(Constants.BUNDLE_BEACON_NAME, beaconName); fragment.setArguments(bundle); getFragmentManager() .beginTransaction() .replace(R.id.fragment, fragment) .addToBackStack(TAG) .commit(); } }); setUpMerchantInsertButton(); final String accountName = sharedPreferences.getString("accountName", ""); if (accountName != null && !accountName.isEmpty()) { accountNameView.setText(accountName); Response.Listener<JSONObject> responseListener = new Response.Listener<JSONObject>() { @Override public void onResponse(final JSONObject response) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { try { merchantNameView.setText("Merchant Name: " + response.getString("merchantName")); JSONArray beaconJsonArray = response.getJSONArray("beacons"); Log.d(TAG, beaconJsonArray.toString()); beaconIds.clear(); for (int i = 0; i < beaconJsonArray.length(); i++) { String beaconId = beaconJsonArray.getString(i); beaconIds.add(beaconId); } Log.d(TAG, beaconIds.toString()); merchantBeaconArrayAdapter.notifyDataSetChanged(); } catch (JSONException e) { Log.e(TAG, "got exception when processing response.", e); } inputTextView.setVisibility(View.INVISIBLE); insertMerchantButton.setVisibility(View.INVISIBLE); } }); } }; Response.ErrorListener errorListener = new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { try { if (error.networkResponse == null || error.networkResponse.data == null) { Log.e(TAG, "problem with volley"); return; } Log.d(TAG, new String(error.networkResponse.data)); JSONObject err = new JSONObject(new String(error.networkResponse.data)); Log.d(TAG, err.toString()); int responseCode = err.getInt("status_code"); if (responseCode == 404) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { merchantNameView.setText("please set up a merchant"); inputTextView.setVisibility(View.VISIBLE); insertMerchantButton.setVisibility(View.VISIBLE); } }); } } catch (JSONException e) { Log.d(TAG, "got excpetion when parsing error", e); } } }; new MerchantServiceTask( getActivity(), accountName, Request.Method.GET, "merchant?email=" + accountName, responseListener, errorListener).execute(); } else { pickUserAccount(); } return rootView; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == Constants.REQUEST_CODE_PICK_ACCOUNT) { // Receiving a result from the AccountPicker if (resultCode == Activity.RESULT_OK) { String name = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); accountNameView.setText(name); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("accountName", name); editor.apply(); // The first time the account tries to contact the beacon service we'll pop a dialog // asking the user to authorize our activity. Ensure that's handled cleanly here, rather // than when the scan tries to fetch the status of every beacon within range. new AuthorizedServiceTask(getActivity(), name).execute(); } else if (resultCode == Activity.RESULT_CANCELED) { // The account picker dialog closed without selecting an account. // Notify users that they must pick an account to proceed. Toast.makeText(getActivity(), "Please pick an account", Toast.LENGTH_SHORT).show(); } } } private void pickUserAccount() { String[] accountTypes = new String[]{"com.google"}; Intent intent = AccountPicker.newChooseAccountIntent( null, null, accountTypes, false, null, null, null, null); startActivityForResult(intent, Constants.REQUEST_CODE_PICK_ACCOUNT); } private void setUpMerchantInsertButton() { final Response.Listener<JSONObject> responseListener = new Response.Listener<JSONObject>() { @Override public void onResponse(final JSONObject response) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { try { merchantNameView.setText(response.getString("merchantName")); insertMerchantButton.setVisibility(View.INVISIBLE); inputTextView.setVisibility(View.INVISIBLE); } catch(JSONException e) { e.printStackTrace(); } } }); } }; final Response.ErrorListener errorListener = new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d(TAG, new String(error.networkResponse.data)); } }; insertMerchantButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { JSONObject body; try { JSONObject merchantData = new JSONObject().put("email", accountNameView.getText()).put("merchantName", inputTextView.getText()); body = new JSONObject().put("body", merchantData); } catch (JSONException e) { Log.d(TAG, "exceptoin when making jsonbdoy", e); return; } new MerchantServiceTask( getActivity(), accountNameView.getText().toString(), Request.Method.POST, "merchant", body, responseListener, errorListener).execute(); } }); } }
true
b86964902dff1a4397298b73c62b911d7228c764
Java
abhissaw10/doctor-service
/src/main/java/com/bmc/doctorservice/model/UpdateDoctorRequest.java
UTF-8
308
1.578125
2
[]
no_license
package com.bmc.doctorservice.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class UpdateDoctorRequest { private String approvedBy; private String approverComments; }
true
ab1d5cb065191cbb039e572c565122d49dd525a2
Java
codingapi/tx-lcn
/txlcn-tc/src/main/java/com/codingapi/txlcn/tc/event/transaction/DefaultTransactionEventListener.java
UTF-8
716
1.882813
2
[ "Apache-2.0" ]
permissive
package com.codingapi.txlcn.tc.event.transaction; import com.codingapi.txlcn.tc.info.TransactionInfo; class DefaultTransactionEventListener implements TransactionEventListener { @Override public void onBeforeCreateTransaction(TransactionInfo transactionInfo) { } @Override public void onAfterCreateTransaction(TransactionInfo transactionInfo) { } @Override public void onBeforeJoinTransaction(TransactionInfo transactionInfo) { } @Override public void onAfterJoinTransaction(TransactionInfo transactionInfo) { } @Override public void onBeforeNotifyTransaction(TransactionInfo transactionInfo) { } @Override public void onAfterNotifyTransaction(TransactionInfo transactionInfo) { } }
true
dcbcc4bf31b2611654bf2a569fc4d5e50acd5a12
Java
KChernenko/GitHubSearch
/app/src/main/java/me/bitfrom/githubsearch/core/network/ServerResponse.java
UTF-8
692
2.421875
2
[]
no_license
package me.bitfrom.githubsearch.core.network; import android.support.annotation.Nullable; /** * <p>Represents general type for response from the server.</p> * * @author const * @version 1 * @since 29.06.2017 */ public final class ServerResponse<T> { @Nullable private String errorMessage; @Nullable private T data; public void setErrorMessage(@Nullable String errorMessage) { this.errorMessage = errorMessage; } public void setData(@Nullable T data) { this.data = data; } @Nullable public String getErrorMessage() { return errorMessage; } @Nullable public T getData() { return this.data; } }
true
126d479bb99595d7eceb0fd9e6891c415060d9d7
Java
SunZuoming/Campus-Course-System-Development
/src/main/java/com/courseplatform/po/SharedfileTable.java
UTF-8
3,297
1.859375
2
[]
no_license
package com.courseplatform.po; public class SharedfileTable { private String sharedfileno; private String uploader; private String uploadtime; private String sharedfileurl; private String sharedfiletypes; private String sharedfilepassflag; private Integer sharedfilegoognum; private Integer sharedfilebadnum; private Integer sharedfilecollectnum; private Integer sharedfilereportnum; private Integer sharedfiledownloadnum; private String sharedfilename; private Float sharedfilegoodrate; public String getSharedfileno() { return sharedfileno; } public void setSharedfileno(String sharedfileno) { this.sharedfileno = sharedfileno == null ? null : sharedfileno.trim(); } public String getUploader() { return uploader; } public void setUploader(String uploader) { this.uploader = uploader == null ? null : uploader.trim(); } public String getUploadtime() { return uploadtime; } public void setUploadtime(String uploadtime) { this.uploadtime = uploadtime == null ? null : uploadtime.trim(); } public String getSharedfileurl() { return sharedfileurl; } public void setSharedfileurl(String sharedfileurl) { this.sharedfileurl = sharedfileurl == null ? null : sharedfileurl.trim(); } public String getSharedfiletypes() { return sharedfiletypes; } public void setSharedfiletypes(String sharedfiletypes) { this.sharedfiletypes = sharedfiletypes == null ? null : sharedfiletypes.trim(); } public String getSharedfilepassflag() { return sharedfilepassflag; } public void setSharedfilepassflag(String sharedfilepassflag) { this.sharedfilepassflag = sharedfilepassflag == null ? null : sharedfilepassflag.trim(); } public Integer getSharedfilegoognum() { return sharedfilegoognum; } public void setSharedfilegoognum(Integer sharedfilegoognum) { this.sharedfilegoognum = sharedfilegoognum; } public Integer getSharedfilebadnum() { return sharedfilebadnum; } public void setSharedfilebadnum(Integer sharedfilebadnum) { this.sharedfilebadnum = sharedfilebadnum; } public Integer getSharedfilecollectnum() { return sharedfilecollectnum; } public void setSharedfilecollectnum(Integer sharedfilecollectnum) { this.sharedfilecollectnum = sharedfilecollectnum; } public Integer getSharedfilereportnum() { return sharedfilereportnum; } public void setSharedfilereportnum(Integer sharedfilereportnum) { this.sharedfilereportnum = sharedfilereportnum; } public Integer getSharedfiledownloadnum() { return sharedfiledownloadnum; } public void setSharedfiledownloadnum(Integer sharedfiledownloadnum) { this.sharedfiledownloadnum = sharedfiledownloadnum; } public String getSharedfilename() { return sharedfilename; } public void setSharedfilename(String sharedfilename) { this.sharedfilename = sharedfilename == null ? null : sharedfilename.trim(); } public Float getSharedfilegoodrate() { return sharedfilegoodrate; } public void setSharedfilegoodrate(Float sharedfilegoodrate) { this.sharedfilegoodrate = sharedfilegoodrate; } }
true
16ba61b3db44b97934378a8e37c1f36fdf73bce3
Java
cliicy/autoupdate
/Central/Server/EdgeAppBaseServiceImpl/src/com/ca/arcserve/edge/app/base/webservice/sync/arcserve/impl/BranchSyncTaskFactory.java
UTF-8
556
2.25
2
[]
no_license
package com.ca.arcserve.edge.app.base.webservice.sync.arcserve.impl; import com.ca.arcserve.edge.app.base.appdaos.EdgeGDBSyncStatus; public class BranchSyncTaskFactory { public static BranchSyncTask Create(int syncType) { EdgeGDBSyncStatus type = EdgeGDBSyncStatus.fromInt(syncType); BranchSyncTask task = null; switch (type) { case GDB_Full_Sync_Succeed: task = new BranchIncSyncTask(); break; case GDB_Full_Sync_Failed: task = new BranchFullSyncTask(); break; default: return null; } return task; } }
true
2be946a579da6f02422060028325b82102e449f0
Java
easpex/java
/Exams/testb2010b3/IntVector.java
UTF-8
777
3.546875
4
[]
no_license
public class IntVector { private int []_arr; /** * Constructor for objects of class IntVector */ public IntVector(int[] arr) { _arr= new int[arr.length]; for(int i = 0; i < arr.length; i++) { _arr[i] = arr[i]; } } public int what () { int m =_arr[0]; for (int i=0; i<_arr.length; i++) for (int j=i; j<_arr.length; j++) { int s=_arr[i]; for (int k=i+1; k<=j; k++) s += _arr[k]; if (s > m) m=s; } return m; } public String toString() { String s = ""; for(int i = 0; i < this._arr.length; i++) { s+= this._arr[i] + " "; } return s; } public static void main(String[] args) { int[] arr = {100,2,3,4}; IntVector b = new IntVector(arr); System.out.println(b); System.out.println(b.what()); } }
true
83d7cbafa4c8ff782fd8be808b763cf5c19ad785
Java
xienian/budget-service
/src/main/java/com/hbhb/cw/budget/web/vo/BudgetProgressReqVO.java
UTF-8
923
1.75
2
[]
no_license
package com.hbhb.cw.budget.web.vo; import java.io.Serializable; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class BudgetProgressReqVO implements Serializable { private static final long serialVersionUID = -1635164445622875008L; @Schema(description = "单位id", required = true) private Integer unitId; @Schema(description = "项目名称") private String projectItem; @Schema(description = "时间(年限)") private String year; @Schema(description = "时间(精确到月)") private String date; @Schema(description = "状态") private Integer state; @Schema(description = "预算id") private Long budgetId; @Schema(description = "预算编号") private String serialNum; }
true
fb300b4f9e2dd60bab4c54ebfd5d910316a99e1c
Java
renansilvamaciel/projectPI_senac_santo_amaro
/src/main/java/br/senac/sp/servlet/PlanoServlet.java
UTF-8
2,233
2.3125
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 br.senac.sp.servlet; import br.senac.sp.dao.PlanoDAO; import br.senac.sp.entidade.Plano; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Azazel */ public class PlanoServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PlanoDAO planoDAO = new PlanoDAO(); List<Plano> listarPlanos; try { listarPlanos = planoDAO.listPlanos(); request.setAttribute("listarPlanos", listarPlanos); RequestDispatcher requestDispatcher = getServletContext() .getRequestDispatcher("/protegido/Plano.jsp"); requestDispatcher.forward(request, response); } catch (SQLException | ClassNotFoundException ex) { Logger.getLogger(PlanoServlet.class.getName()).log(Level.SEVERE, null, ex); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Plano plano = new Plano(); plano.setNome(request.getParameter("nome")); plano.setDescricao(request.getParameter("descricao")); plano.setValor(Double.parseDouble(request.getParameter("valor"))); PlanoDAO planoDAO = new PlanoDAO(); planoDAO.insertPlanos(plano); response.sendRedirect(request.getContextPath()+"//PlanoServlet"); } catch (ClassNotFoundException | NumberFormatException | SQLException ex) { Logger.getLogger(PlanoServlet.class.getName()).log(Level.SEVERE, null, ex); } } }
true