blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
sequence
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
sequence
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
621470498b1206b90e21fcad7901c88bc3b36bd6
31,336,081,412,286
e50550a402c0a7bc48cbd9ceafd831df57430c32
/src/snake/Sigmoid.java
5acfac0b9e95d7bc9f4559d4525bf24021250246
[]
no_license
RoCoBo44/sNNake
https://github.com/RoCoBo44/sNNake
31124c4c35e52e2cdb8fe4cf262c339f1d9ce08a
4a5010a5219636687c80a8f52fb6b24d3c2a50e6
refs/heads/master
2021-05-18T05:17:25.339000
2020-10-23T17:30:08
2020-10-23T17:30:08
251,130,877
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package snake; public class Sigmoid implements ActivationFunction{ public Sigmoid(){ } public Double transform(Double in) { //problema con gradiente, si es muy sercano a 0 se estanca y su formula no esta centrada en 0 tampoco return (1/ (1 + Math.exp(-in)) ); } @Override public Double Derivative(Double in) { return in * (1.0 - in); } }
UTF-8
Java
368
java
Sigmoid.java
Java
[]
null
[]
package snake; public class Sigmoid implements ActivationFunction{ public Sigmoid(){ } public Double transform(Double in) { //problema con gradiente, si es muy sercano a 0 se estanca y su formula no esta centrada en 0 tampoco return (1/ (1 + Math.exp(-in)) ); } @Override public Double Derivative(Double in) { return in * (1.0 - in); } }
368
0.668478
0.652174
23
15
24.0868
103
false
false
0
0
0
0
0
0
1.043478
false
false
9
4db071f83e2bc0baae4859e7ce259019eb1f81ee
29,489,245,474,598
2bba7366e6fc6123390bd689bf895248ed081f4a
/microservicio/infraestructura/src/main/java/com/ceiba/producto/controlador/ConsultaControladorProducto.java
17813262a9778c0a7df93a28f8c531cfabac3f31
[]
no_license
jefer10/ADNceiba
https://github.com/jefer10/ADNceiba
01bd8a786ac9c5f3fb1b961da9556e7ed5de0a97
ad8cd67b36865c5994f36ebeb7125d1acca3f712
refs/heads/main
2023-05-15T00:01:14.638000
2021-05-26T04:36:09
2021-05-26T04:36:09
370,902,809
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ceiba.producto.controlador; import com.ceiba.producto.consulta.ManejadorProducto; import com.ceiba.producto.modelo.entidad.Producto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/producto") public class ConsultaControladorProducto { @Autowired private ManejadorProducto manejadorProducto; @GetMapping(value = "/") public List<Producto>findAll(){ return manejadorProducto.listaProductos(); } @GetMapping(value = "/{id}") public Producto findById(@PathVariable long id){ return manejadorProducto.findById(id); } }
UTF-8
Java
931
java
ConsultaControladorProducto.java
Java
[]
null
[]
package com.ceiba.producto.controlador; import com.ceiba.producto.consulta.ManejadorProducto; import com.ceiba.producto.modelo.entidad.Producto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/producto") public class ConsultaControladorProducto { @Autowired private ManejadorProducto manejadorProducto; @GetMapping(value = "/") public List<Producto>findAll(){ return manejadorProducto.listaProductos(); } @GetMapping(value = "/{id}") public Producto findById(@PathVariable long id){ return manejadorProducto.findById(id); } }
931
0.754028
0.754028
31
28.032259
23.504953
62
false
false
0
0
0
0
0
0
0.387097
false
false
9
4af8f2bac0f5ed385f638b4bdb5d9b67e0c6f9b5
26,036,091,768,482
6e3f515fb5981ca86ce7f1c7a9e986b5bb841182
/quiz/4/Empresa.java
bbe7b9f39c446123684d33dba000e665d1a1f4aa
[]
no_license
jairyara/Programaci-n-I---ETITC
https://github.com/jairyara/Programaci-n-I---ETITC
7c45254c8fa666a24de33d64a3ac5c106d5a5965
f5435c146f5ee63216431b7004635a44bcffeec2
refs/heads/master
2023-03-11T03:39:09.689000
2021-02-17T23:16:30
2021-02-17T23:16:30
296,476,025
0
2
null
false
2020-10-09T15:29:44
2020-09-18T00:50:52
2020-10-08T02:06:39
2020-10-08T02:06:37
188
0
1
0
Java
false
false
/** * Objeto empresa * Hereda de la clase Usuario los atributos en común */ public class Empresa extends Usuario { //Atributos private String sector; private String descripcion; private int annioFundacion; private int cantidadEmpleados; //Método constructor public Empresa(String nombre, long dni, String direccion, long telefono, String correo, String sector, String descripcion, int annioFundacion, int cantidadEmpleados) { super(nombre, dni, direccion, telefono, correo); this.sector = sector; this.descripcion = descripcion; this.annioFundacion = annioFundacion; this.cantidadEmpleados = cantidadEmpleados; } //Métodos get y set public String getSector() { return sector; } public void setSector(String sector) { this.sector = sector; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public int getAnnioFundacion() { return annioFundacion; } public void setAnnioFundacion(int annioFundacion) { this.annioFundacion = annioFundacion; } public int getCantidadEmpleados() { return cantidadEmpleados; } public void setCantidadEmpleados(int cantidadEmpleados) { this.cantidadEmpleados = cantidadEmpleados; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Registro Empresa"); sb.append("\n Nombre: "); sb.append(getNombre()); sb.append("\n DNI: "); sb.append(getDni()); sb.append("\n Dirección: "); sb.append(getDireccion()); sb.append("\n Teléfono: "); sb.append(getTelefono()); sb.append("\n Correo: "); sb.append(getCorreo()); sb.append("\n Sector: "); sb.append(getSector()); sb.append("\n Descripción: "); sb.append(getDescripcion()); sb.append("\n Año de fundación: "); sb.append(getAnnioFundacion()); sb.append("\n No. Empleados: "); sb.append(getCantidadEmpleados()); sb.append("\n-----------------------\n"); return sb.toString(); } }
UTF-8
Java
2,287
java
Empresa.java
Java
[]
null
[]
/** * Objeto empresa * Hereda de la clase Usuario los atributos en común */ public class Empresa extends Usuario { //Atributos private String sector; private String descripcion; private int annioFundacion; private int cantidadEmpleados; //Método constructor public Empresa(String nombre, long dni, String direccion, long telefono, String correo, String sector, String descripcion, int annioFundacion, int cantidadEmpleados) { super(nombre, dni, direccion, telefono, correo); this.sector = sector; this.descripcion = descripcion; this.annioFundacion = annioFundacion; this.cantidadEmpleados = cantidadEmpleados; } //Métodos get y set public String getSector() { return sector; } public void setSector(String sector) { this.sector = sector; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public int getAnnioFundacion() { return annioFundacion; } public void setAnnioFundacion(int annioFundacion) { this.annioFundacion = annioFundacion; } public int getCantidadEmpleados() { return cantidadEmpleados; } public void setCantidadEmpleados(int cantidadEmpleados) { this.cantidadEmpleados = cantidadEmpleados; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Registro Empresa"); sb.append("\n Nombre: "); sb.append(getNombre()); sb.append("\n DNI: "); sb.append(getDni()); sb.append("\n Dirección: "); sb.append(getDireccion()); sb.append("\n Teléfono: "); sb.append(getTelefono()); sb.append("\n Correo: "); sb.append(getCorreo()); sb.append("\n Sector: "); sb.append(getSector()); sb.append("\n Descripción: "); sb.append(getDescripcion()); sb.append("\n Año de fundación: "); sb.append(getAnnioFundacion()); sb.append("\n No. Empleados: "); sb.append(getCantidadEmpleados()); sb.append("\n-----------------------\n"); return sb.toString(); } }
2,287
0.614305
0.614305
80
27.487499
23.776562
171
false
false
0
0
0
0
0
0
0.6375
false
false
9
8062d06efce1c3923ec7fa54b416d5feccad419d
23,837,068,518,618
0ce1b5f1ef3b19bd216258e2abe593abc53e95cc
/src/org/usfirst/frc/team3501/robot/commands/driving/AlignWithCubeRotate.java
a1bc33ba42eee90333c47ec6145e52ae9c320c92
[]
no_license
AminHakem/2018PowerUp
https://github.com/AminHakem/2018PowerUp
4e3c21b19832f762bcbb8fbb70271721c2545ac7
f1de78a39f6b8a98131ed7c688a54186ba710649
refs/heads/master
2020-04-29T07:34:18.359000
2018-06-27T06:22:59
2018-06-27T06:22:59
175,957,780
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.usfirst.frc.team3501.robot.commands.driving; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc.team3501.robot.Robot; import org.usfirst.frc.team3501.robot.subsystems.DriveTrain; import org.usfirst.frc.team3501.robot.utils.NetworkThread; import org.usfirst.frc.team3501.robot.utils.PIDController; /** * Command starts a thread which will get values from RaspberryPi regarding the alignment of a cube * using camera input Is currently mapped to the X button on controller. Uses values from camera * to align itself with the cube by rotating * @author Amin Hakem * */ public class AlignWithCubeRotate extends Command { private PIDController alignmentController; private NetworkThread thread; public AlignWithCubeRotate() { requires(Robot.getDriveTrain()); alignmentController = new PIDController(DriveTrain.driveSidewaysPLong, DriveTrain.driveSidewaysILong, 0); alignmentController.setDoneRange(5); // initialize a thread which will run code to constantly update thread = new NetworkThread(); thread.start(); // RaspberryPi will output 0 when camera is aligned } // Called just before this Command runs the first time protected void initialize() { alignmentController.setSetPoint(0); } // Called repeatedly when this Command is scheduled to run protected void execute() { if (NetworkThread.isBoxVisible()) { double output = alignmentController.calcPID(NetworkThread.getBoxX()); DriveTrain.getDriveTrain().mecanumDrive(0, 0, -output); } } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return this.alignmentController.isDone(); } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
UTF-8
Java
2,012
java
AlignWithCubeRotate.java
Java
[ { "context": " align itself with the cube by rotating\n * @author Amin Hakem\n *\n */\npublic class AlignWithCubeRotate extends C", "end": 596, "score": 0.99969881772995, "start": 586, "tag": "NAME", "value": "Amin Hakem" } ]
null
[]
package org.usfirst.frc.team3501.robot.commands.driving; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc.team3501.robot.Robot; import org.usfirst.frc.team3501.robot.subsystems.DriveTrain; import org.usfirst.frc.team3501.robot.utils.NetworkThread; import org.usfirst.frc.team3501.robot.utils.PIDController; /** * Command starts a thread which will get values from RaspberryPi regarding the alignment of a cube * using camera input Is currently mapped to the X button on controller. Uses values from camera * to align itself with the cube by rotating * @author <NAME> * */ public class AlignWithCubeRotate extends Command { private PIDController alignmentController; private NetworkThread thread; public AlignWithCubeRotate() { requires(Robot.getDriveTrain()); alignmentController = new PIDController(DriveTrain.driveSidewaysPLong, DriveTrain.driveSidewaysILong, 0); alignmentController.setDoneRange(5); // initialize a thread which will run code to constantly update thread = new NetworkThread(); thread.start(); // RaspberryPi will output 0 when camera is aligned } // Called just before this Command runs the first time protected void initialize() { alignmentController.setSetPoint(0); } // Called repeatedly when this Command is scheduled to run protected void execute() { if (NetworkThread.isBoxVisible()) { double output = alignmentController.calcPID(NetworkThread.getBoxX()); DriveTrain.getDriveTrain().mecanumDrive(0, 0, -output); } } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return this.alignmentController.isDone(); } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
2,008
0.725149
0.712227
59
33.101696
27.996788
99
false
false
0
0
0
0
0
0
0.355932
false
false
9
bf5a30d6072da9de3818b46af0bdbd3fc4b54e16
11,218,454,614,045
b3495a856d091ddb227bbbd667c8f35a0be7dde8
/src/main/java/com/claro/gestionrecursosapi/entity/ProveedoratributoEntity.java
d13f546b066ee92ca6571dd483b84b077c9638a4
[]
no_license
andrespperdomo/gestion-recursos-api
https://github.com/andrespperdomo/gestion-recursos-api
5fd06f1d287840570a2232fac99d9d4b2adc089c
5e479c73ee58e611ecfa09b0b6cca56fe605048f
refs/heads/master
2021-01-06T22:18:26.823000
2020-02-21T19:36:00
2020-02-21T19:36:00
241,498,666
0
0
null
true
2020-02-19T00:35:48
2020-02-19T00:35:47
2020-02-18T21:41:36
2020-02-18T21:41:34
186
0
0
0
null
false
false
package com.claro.gestionrecursosapi.entity; import java.io.Serializable; import java.sql.Timestamp; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; /** * The persistent class for the proveedoratributo database table. * */ @Entity @Table(name="proveedoratributo") @NamedQuery(name="ProveedoratributoEntity.findAll", query="SELECT p FROM ProveedoratributoEntity p") public class ProveedoratributoEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; private String estado; private Timestamp fechacreacion; private Timestamp fechamodificacion; private String nombre; //bi-directional many-to-one association to ProveedoratributotipoEntity @ManyToOne @JoinColumn(name="CODPROVEEDORATRIBUTOTIPO") private ProveedoratributotipoEntity proveedoratributotipo; public ProveedoratributoEntity() { } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public String getEstado() { return this.estado; } public void setEstado(String estado) { this.estado = estado; } public Timestamp getFechacreacion() { return this.fechacreacion; } public void setFechacreacion(Timestamp fechacreacion) { this.fechacreacion = fechacreacion; } public Timestamp getFechamodificacion() { return this.fechamodificacion; } public void setFechamodificacion(Timestamp fechamodificacion) { this.fechamodificacion = fechamodificacion; } public String getNombre() { return this.nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public ProveedoratributotipoEntity getProveedoratributotipo() { return this.proveedoratributotipo; } public void setProveedoratributotipo(ProveedoratributotipoEntity proveedoratributotipo) { this.proveedoratributotipo = proveedoratributotipo; } }
UTF-8
Java
2,175
java
ProveedoratributoEntity.java
Java
[]
null
[]
package com.claro.gestionrecursosapi.entity; import java.io.Serializable; import java.sql.Timestamp; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; /** * The persistent class for the proveedoratributo database table. * */ @Entity @Table(name="proveedoratributo") @NamedQuery(name="ProveedoratributoEntity.findAll", query="SELECT p FROM ProveedoratributoEntity p") public class ProveedoratributoEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; private String estado; private Timestamp fechacreacion; private Timestamp fechamodificacion; private String nombre; //bi-directional many-to-one association to ProveedoratributotipoEntity @ManyToOne @JoinColumn(name="CODPROVEEDORATRIBUTOTIPO") private ProveedoratributotipoEntity proveedoratributotipo; public ProveedoratributoEntity() { } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public String getEstado() { return this.estado; } public void setEstado(String estado) { this.estado = estado; } public Timestamp getFechacreacion() { return this.fechacreacion; } public void setFechacreacion(Timestamp fechacreacion) { this.fechacreacion = fechacreacion; } public Timestamp getFechamodificacion() { return this.fechamodificacion; } public void setFechamodificacion(Timestamp fechamodificacion) { this.fechamodificacion = fechamodificacion; } public String getNombre() { return this.nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public ProveedoratributotipoEntity getProveedoratributotipo() { return this.proveedoratributotipo; } public void setProveedoratributotipo(ProveedoratributotipoEntity proveedoratributotipo) { this.proveedoratributotipo = proveedoratributotipo; } }
2,175
0.792184
0.791724
96
21.666666
22.822535
100
false
false
0
0
0
0
0
0
0.989583
false
false
9
52d4942b3cdd4cfee301884f9e80669c2bd974f2
26,173,530,727,051
c51f0c96c6d26d277b828c21f79ea38f0517b39f
/src/main/java/projekti/controller/MessageController.java
14bb50aeea02c46f7b49f25eb42b9e3670987c8b
[]
no_license
k1mtap/SkillerApp
https://github.com/k1mtap/SkillerApp
b4dcc93dd09e4360b9b68542d916a78f8dd450f3
62352507b9090ba4260f3ccd645a3274ee7d8a38
refs/heads/master
2023-01-11T04:44:46.329000
2020-11-19T15:48:38
2020-11-19T15:48:38
297,728,110
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package projekti.controller; import projekti.service.MessageService; import projekti.service.AccountService; import projekti.domain.Message; import projekti.domain.Account; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.RequestParam; @Controller public class MessageController { @Autowired private MessageService messageService; @Autowired private AccountService accountService; // ====== MESSAGES ====== @GetMapping("/messages") public String showMessagesAndComments(Model model, @RequestParam(defaultValue = "0") Integer msgPage) { Account currentAccount = accountService.getCurrentAccount(); Page<Message> messagePage = messageService.getAllContactMessages(currentAccount, msgPage); model.addAttribute("currentAccount", currentAccount); model.addAttribute("messagePage", messagePage); model.addAttribute("messageService", messageService); return "messages"; } @PostMapping("/messages") public String addMessage(@RequestParam String content) { messageService.addMessage(content); return "redirect:/messages"; } @PutMapping("/messages/{id}") public String addLikeToMessage(@PathVariable("id") Long id, @RequestParam(defaultValue = "0") Integer msgPage) { messageService.addLikeToMessage(id); return "redirect:/messages?msgPage=" + msgPage + "#" + id; } @DeleteMapping("/messages/{id}") public String deleteMessage(@PathVariable Long id, @RequestParam(defaultValue = "0") Integer msgPage) { Account currentAccount = accountService.getCurrentAccount(); Page<Message> messagePage = messageService.getAllContactMessages(currentAccount, msgPage); if (messagePage.getContent().size() == 1) { msgPage = 0; } messageService.deleteMessage(id); return "redirect:/messages?msgPage=" + msgPage; } // ====== COMMENTS ====== @PostMapping("/messages/{id}/comments") public String addComment(@PathVariable Long id, @RequestParam String content, @RequestParam(defaultValue = "0") Integer msgPage) { messageService.addComment(id, content); return "redirect:/messages?msgPage=" + msgPage + "#" + id; } @PutMapping("/messages/{id}/comments/{commentId}") public String addLikeToComment(@PathVariable("commentId") Long commentId, @RequestParam(defaultValue = "0") Integer msgPage) { messageService.addLikeToComment(commentId); return "redirect:/messages?msgPage=" + msgPage + "#" + commentId; } @DeleteMapping("/messages/{id}/comments/{commentId}") public String deleteComment(@PathVariable("id") Long id, @PathVariable("commentId") Long commentId, @RequestParam(defaultValue = "0") Integer msgPage) { messageService.deleteComment(id, commentId); return "redirect:/messages?msgPage=" + msgPage + "#" + id; } }
UTF-8
Java
3,433
java
MessageController.java
Java
[]
null
[]
package projekti.controller; import projekti.service.MessageService; import projekti.service.AccountService; import projekti.domain.Message; import projekti.domain.Account; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.RequestParam; @Controller public class MessageController { @Autowired private MessageService messageService; @Autowired private AccountService accountService; // ====== MESSAGES ====== @GetMapping("/messages") public String showMessagesAndComments(Model model, @RequestParam(defaultValue = "0") Integer msgPage) { Account currentAccount = accountService.getCurrentAccount(); Page<Message> messagePage = messageService.getAllContactMessages(currentAccount, msgPage); model.addAttribute("currentAccount", currentAccount); model.addAttribute("messagePage", messagePage); model.addAttribute("messageService", messageService); return "messages"; } @PostMapping("/messages") public String addMessage(@RequestParam String content) { messageService.addMessage(content); return "redirect:/messages"; } @PutMapping("/messages/{id}") public String addLikeToMessage(@PathVariable("id") Long id, @RequestParam(defaultValue = "0") Integer msgPage) { messageService.addLikeToMessage(id); return "redirect:/messages?msgPage=" + msgPage + "#" + id; } @DeleteMapping("/messages/{id}") public String deleteMessage(@PathVariable Long id, @RequestParam(defaultValue = "0") Integer msgPage) { Account currentAccount = accountService.getCurrentAccount(); Page<Message> messagePage = messageService.getAllContactMessages(currentAccount, msgPage); if (messagePage.getContent().size() == 1) { msgPage = 0; } messageService.deleteMessage(id); return "redirect:/messages?msgPage=" + msgPage; } // ====== COMMENTS ====== @PostMapping("/messages/{id}/comments") public String addComment(@PathVariable Long id, @RequestParam String content, @RequestParam(defaultValue = "0") Integer msgPage) { messageService.addComment(id, content); return "redirect:/messages?msgPage=" + msgPage + "#" + id; } @PutMapping("/messages/{id}/comments/{commentId}") public String addLikeToComment(@PathVariable("commentId") Long commentId, @RequestParam(defaultValue = "0") Integer msgPage) { messageService.addLikeToComment(commentId); return "redirect:/messages?msgPage=" + msgPage + "#" + commentId; } @DeleteMapping("/messages/{id}/comments/{commentId}") public String deleteComment(@PathVariable("id") Long id, @PathVariable("commentId") Long commentId, @RequestParam(defaultValue = "0") Integer msgPage) { messageService.deleteComment(id, commentId); return "redirect:/messages?msgPage=" + msgPage + "#" + id; } }
3,433
0.710749
0.708418
94
35.521278
34.869278
156
false
false
0
0
0
0
0
0
0.56383
false
false
9
5111c5ce944f626b61748734913edace7bbd42a6
18,743,237,309,960
aa10bd30ed4c961ff8baade9aa58dceb75197875
/src/test/CsvTest.java
7032b7bf1260f1ff3914e082bc2205d523f03d54
[]
no_license
RustLi/JavaLearning
https://github.com/RustLi/JavaLearning
0a2e669f88ece0349b175de343daa3fb4c5b70f8
9346cbf330393d6218fa5c0a17bdf16ab9253507
refs/heads/master
2023-09-01T00:05:31.352000
2023-08-16T02:43:43
2023-08-16T02:43:43
154,470,973
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test; import java.io.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; public class CsvTest { public static void main(String[] args) { try { // test(); test1(); } catch (Exception e) { e.printStackTrace(); } } /** * 替换csv中的字符,然后写入到新到csv中; **/ public static void test() throws Exception { String sourceFilePath = "/Users/lwl/work/数据处理/abc.csv"; String newFilePath = "/Users/lwl/work/数据处理/abc1.csv"; File sourceCsvFile = new File(sourceFilePath); File finalCsvFile = new File(newFilePath); final Charset Encoding = StandardCharsets.UTF_8; String line = ""; try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(finalCsvFile), Encoding))) { try (BufferedReader br = new BufferedReader(new FileReader(sourceCsvFile))) { while ((line = br.readLine()) != null) { System.out.println("line = " + line); if (line.contains("你好")){ line = line.replace("你好","A"); } String newFileLine = line; writer.write(newFileLine); writer.newLine(); } } } } public static void test1() throws Exception { String sourceFilePath = "/Users/lwl/work/backend/电商项目/refundReason"; String newFilePath = "/Users/lwl/work/backend/电商项目/refundReason1"; File sourceCsvFile = new File(sourceFilePath); File finalCsvFile = new File(newFilePath); final Charset Encoding = StandardCharsets.UTF_8; String line = ""; try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(finalCsvFile), Encoding))) { try (BufferedReader br = new BufferedReader(new FileReader(sourceCsvFile))) { while ((line = br.readLine()) != null) { System.out.println("line = " + line); if (line.contains("你好")){ line = line.replace("你好","A"); } String newFileLine = ""; if (line.contains("-")){ String[] newStrArr = line.split("-"); String arr0 = newStrArr[0].trim(); String arr1 = newStrArr[1].replace(";","").trim(); newFileLine = arr0 + "(\"" + arr0 + "\" , " + "\"" + arr1 + "\"),"; } System.out.println("newFileLine = " + newFileLine); if (newFileLine != null && newFileLine.length() > 1){ writer.write(newFileLine); writer.newLine(); } } } } } }
UTF-8
Java
3,008
java
CsvTest.java
Java
[]
null
[]
package test; import java.io.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; public class CsvTest { public static void main(String[] args) { try { // test(); test1(); } catch (Exception e) { e.printStackTrace(); } } /** * 替换csv中的字符,然后写入到新到csv中; **/ public static void test() throws Exception { String sourceFilePath = "/Users/lwl/work/数据处理/abc.csv"; String newFilePath = "/Users/lwl/work/数据处理/abc1.csv"; File sourceCsvFile = new File(sourceFilePath); File finalCsvFile = new File(newFilePath); final Charset Encoding = StandardCharsets.UTF_8; String line = ""; try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(finalCsvFile), Encoding))) { try (BufferedReader br = new BufferedReader(new FileReader(sourceCsvFile))) { while ((line = br.readLine()) != null) { System.out.println("line = " + line); if (line.contains("你好")){ line = line.replace("你好","A"); } String newFileLine = line; writer.write(newFileLine); writer.newLine(); } } } } public static void test1() throws Exception { String sourceFilePath = "/Users/lwl/work/backend/电商项目/refundReason"; String newFilePath = "/Users/lwl/work/backend/电商项目/refundReason1"; File sourceCsvFile = new File(sourceFilePath); File finalCsvFile = new File(newFilePath); final Charset Encoding = StandardCharsets.UTF_8; String line = ""; try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(finalCsvFile), Encoding))) { try (BufferedReader br = new BufferedReader(new FileReader(sourceCsvFile))) { while ((line = br.readLine()) != null) { System.out.println("line = " + line); if (line.contains("你好")){ line = line.replace("你好","A"); } String newFileLine = ""; if (line.contains("-")){ String[] newStrArr = line.split("-"); String arr0 = newStrArr[0].trim(); String arr1 = newStrArr[1].replace(";","").trim(); newFileLine = arr0 + "(\"" + arr0 + "\" , " + "\"" + arr1 + "\"),"; } System.out.println("newFileLine = " + newFileLine); if (newFileLine != null && newFileLine.length() > 1){ writer.write(newFileLine); writer.newLine(); } } } } } }
3,008
0.507519
0.502734
76
37.5
28.854216
127
false
false
0
0
0
0
0
0
0.539474
false
false
9
3d16b493ee340a595a707a7872cd72054674a518
8,315,056,686,210
88ac60772afd0abee51f3965cd7fa1da78eddad7
/src/com/essar/suggestion/SuggestionExampleMain.java
5668ca687c09341ca03c02bdec9fc1afb2451cfa
[]
no_license
Rahumathulla/tienda_art
https://github.com/Rahumathulla/tienda_art
1eb6af006414438983d62f0a3c5c9fb6ccf519cf
8bdc919dfc049176aaaeed9a66cd81cdfe33c9c1
refs/heads/main
2023-08-19T05:42:12.923000
2021-10-08T05:24:00
2021-10-08T05:24:00
412,574,375
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 com.essar.suggestion; import com.essar.dao.StockDAO; import javax.swing.*; import java.awt.*; import java.util.List; import java.util.stream.Collectors; /** * * @author rahumathulla */ public class SuggestionExampleMain { // public static void main(String[] args) { //StockDAO stockDAO = null; public SuggestionExampleMain(){ //stockDAO = new StockDAO(); } public static void populateItemNames(JFrame frame, JTextField textField) { //JFrame frame = createFrame(); //JTextField textField = new JTextField(10); SuggestionDropDownDecorator.decorate(textField, new TextComponentSuggestionClient(SuggestionExampleMain::getSuggestions)); /*Font font = new Font(Font.SANS_SERIF, 2, 2); JTextPane textPane = new JTextPane(); JScrollPane jsp = new JScrollPane(textPane); textPane.setFont(font); frame.add(new JScrollPane(textPane));*/ //frame.add(jsp); frame.setVisible(true); //SuggestionDropDownDecorator.decorate(textPane, //new TextComponentWordSuggestionClient(SuggestionExampleMain::getSuggestions)); //frame.add(textField, BorderLayout.NORTH); //frame.add(new JScrollPane(textPane)); //frame.setVisible(true); } public void populateItemNamesStock(JFrame frame, JTextField textField) { //JFrame frame = createFrame(); //JTextField textField = new JTextField(10); SuggestionDropDownDecorator.decorate(textField, new TextComponentSuggestionClient(SuggestionExampleMain::getSuggestions)); frame.setVisible(true); } private static List<String> words = StockDAO.retrieveItemNames(); //RandomUtil.getWords(2, 400).stream().map(String::toLowerCase).collect(Collectors.toList()); private static List<String> getSuggestions(String input) { //the suggestion provider can control text search related stuff, e.g case insensitive match, the search limit etc. List<String> items = StockDAO.retrieveItemNames(); if (input.isEmpty()) { return null; } return items.stream() .filter(s -> s.toLowerCase().contains(input.toLowerCase())) .limit(20) .collect(Collectors.toList()); } }
UTF-8
Java
2,593
java
SuggestionExampleMain.java
Java
[ { "context": "ort java.util.stream.Collectors;\n/**\n *\n * @author rahumathulla\n */\n\n\npublic class SuggestionExampleMain {\n \n ", "end": 376, "score": 0.8707787394523621, "start": 364, "tag": "USERNAME", "value": "rahumathulla" } ]
null
[]
/* * 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 com.essar.suggestion; import com.essar.dao.StockDAO; import javax.swing.*; import java.awt.*; import java.util.List; import java.util.stream.Collectors; /** * * @author rahumathulla */ public class SuggestionExampleMain { // public static void main(String[] args) { //StockDAO stockDAO = null; public SuggestionExampleMain(){ //stockDAO = new StockDAO(); } public static void populateItemNames(JFrame frame, JTextField textField) { //JFrame frame = createFrame(); //JTextField textField = new JTextField(10); SuggestionDropDownDecorator.decorate(textField, new TextComponentSuggestionClient(SuggestionExampleMain::getSuggestions)); /*Font font = new Font(Font.SANS_SERIF, 2, 2); JTextPane textPane = new JTextPane(); JScrollPane jsp = new JScrollPane(textPane); textPane.setFont(font); frame.add(new JScrollPane(textPane));*/ //frame.add(jsp); frame.setVisible(true); //SuggestionDropDownDecorator.decorate(textPane, //new TextComponentWordSuggestionClient(SuggestionExampleMain::getSuggestions)); //frame.add(textField, BorderLayout.NORTH); //frame.add(new JScrollPane(textPane)); //frame.setVisible(true); } public void populateItemNamesStock(JFrame frame, JTextField textField) { //JFrame frame = createFrame(); //JTextField textField = new JTextField(10); SuggestionDropDownDecorator.decorate(textField, new TextComponentSuggestionClient(SuggestionExampleMain::getSuggestions)); frame.setVisible(true); } private static List<String> words = StockDAO.retrieveItemNames(); //RandomUtil.getWords(2, 400).stream().map(String::toLowerCase).collect(Collectors.toList()); private static List<String> getSuggestions(String input) { //the suggestion provider can control text search related stuff, e.g case insensitive match, the search limit etc. List<String> items = StockDAO.retrieveItemNames(); if (input.isEmpty()) { return null; } return items.stream() .filter(s -> s.toLowerCase().contains(input.toLowerCase())) .limit(20) .collect(Collectors.toList()); } }
2,593
0.646741
0.642113
76
33.11842
28.750729
123
false
false
0
0
0
0
0
0
0.592105
false
false
9
f7e257eff4ef360c540fcc6c64426379a2b461f8
28,389,733,850,020
9eb56f77d7e4d15186b40ac5c9b2aa0007a95605
/Math/src/fr/hadriel/math/Matrix4.java
e12bd63a2d10d32afae67e50ed8ab6056a562a4f
[]
no_license
HaDriell/HaDrielUtil
https://github.com/HaDriell/HaDrielUtil
2e2e9e6b8abfd29c45d551efc82af7f1545f4dc0
fb4abfcd6fa7a43589c0d9e05747adf65f0acb5c
refs/heads/master
2020-05-21T20:53:08.664000
2018-06-14T15:05:47
2018-06-14T15:05:47
65,190,966
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.hadriel.math; /** * Created by glathuiliere on 13/07/2016. * * inspiration from * https://github.com/gamedev-js/vmath/blob/master/lib/mat4.js */ public strictfp class Matrix4 { private static final float[] IDENTITY = new float[] { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; public static final Matrix4 Identity = new Matrix4(); /* * Matrix Order [M_COL_ROW] : * * [M00 .... M30] * [M01 .... M31] * [M02 .... M32] * [M03 .... M33] * */ //First Row public static final byte M00 = 0; public static final byte M01 = 1; public static final byte M02 = 2; public static final byte M03 = 3; //Second Row public static final byte M10 = 4; public static final byte M11 = 5; public static final byte M12 = 6; public static final byte M13 = 7; //Third Row public static final byte M20 = 8; public static final byte M21 = 9; public static final byte M22 = 10; public static final byte M23 = 11; //Third Row public static final byte M30 = 12; public static final byte M31 = 13; public static final byte M32 = 14; public static final byte M33 = 15; public final float m00, m01, m02, m03; public final float m10, m11, m12, m13; public final float m20, m21, m22, m23; public final float m30, m31, m32, m33; public Matrix4( float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23; this.m30 = m30; this.m31 = m31; this.m32 = m32; this.m33 = m33; } public Matrix4(float[] matrix) { this( matrix[M00], matrix[M01], matrix[M02], matrix[M03], matrix[M10], matrix[M11], matrix[M12], matrix[M13], matrix[M20], matrix[M21], matrix[M22], matrix[M23], matrix[M30], matrix[M31], matrix[M32], matrix[M33]); } public Matrix4(Matrix4 m) { this( m.m00, m.m01, m.m02, m.m03, m.m10, m.m11, m.m12, m.m13, m.m20, m.m21, m.m22, m.m23, m.m30, m.m31, m.m32, m.m33); } public Matrix4() { this(IDENTITY); } public float determinant() { float b00 = m00 * m11 - m01 * m10; float b01 = m00 * m12 - m02 * m10; float b02 = m00 * m13 - m03 * m10; float b03 = m01 * m12 - m02 * m11; float b04 = m01 * m13 - m03 * m11; float b05 = m02 * m13 - m03 * m12; float b06 = m20 * m31 - m21 * m30; float b07 = m20 * m32 - m22 * m30; float b08 = m20 * m33 - m23 * m30; float b09 = m21 * m32 - m22 * m31; float b10 = m21 * m33 - m23 * m31; float b11 = m22 * m33 - m23 * m32; return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; } public Matrix4 invert() { float b00 = m00 * m11 - m01 * m10; float b01 = m00 * m12 - m02 * m10; float b02 = m00 * m13 - m03 * m10; float b03 = m01 * m12 - m02 * m11; float b04 = m01 * m13 - m03 * m11; float b05 = m02 * m13 - m03 * m12; float b06 = m20 * m31 - m21 * m30; float b07 = m20 * m32 - m22 * m30; float b08 = m20 * m33 - m23 * m30; float b09 = m21 * m32 - m22 * m31; float b10 = m21 * m33 - m23 * m31; float b11 = m22 * m33 - m23 * m32; float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if(det == 0) return null; // singular matrix det = 1f / det; float[] elements = new float[16]; elements[M00] = (m11 * b11 - m12 * b10 + m13 * b09) * det; elements[M01] = (m02 * b10 - m01 * b11 - m03 * b09) * det; elements[M02] = (m31 * b05 - m32 * b04 + m33 * b03) * det; elements[M03] = (m22 * b04 - m21 * b05 - m23 * b03) * det; elements[M10] = (m12 * b08 - m10 * b11 - m13 * b07) * det; elements[M11] = (m00 * b11 - m02 * b08 + m03 * b07) * det; elements[M12] = (m32 * b02 - m30 * b05 - m33 * b01) * det; elements[M13] = (m20 * b05 - m22 * b02 + m23 * b01) * det; elements[M20] = (m10 * b10 - m11 * b08 + m13 * b06) * det; elements[M21] = (m01 * b08 - m00 * b10 - m03 * b06) * det; elements[M22] = (m30 * b04 - m31 * b02 + m33 * b00) * det; elements[M23] = (m21 * b02 - m20 * b04 - m23 * b00) * det; elements[M30] = (m11 * b07 - m10 * b09 - m12 * b06) * det; elements[M31] = (m00 * b09 - m01 * b07 + m02 * b06) * det; elements[M32] = (m31 * b01 - m30 * b03 - m32 * b00) * det; elements[M33] = (m20 * b03 - m21 * b01 + m22 * b00) * det; return new Matrix4(elements); } public static Matrix4 Orthographic(float left, float right, float top, float bottom, float near, float far) { float[] elements = new float[16]; elements[M00] = 2f / (right - left); elements[M11] = 2f / (top - bottom); elements[M22] = -2f / (far - near); elements[M33] = 1f; elements[M30] = -(right + left) / (right - left); elements[M31] = -(top + bottom) / (top - bottom); elements[M32] = -(far + near) / (far - near); return new Matrix4(elements); } public Matrix4 Perspective(float fov, float aspectRatio, float near, float far) { float[] elements = new float[16]; elements[M00] = 1f; elements[M11] = 1f; elements[M22] = 1f; elements[M33] = 1f; float q = 1f / (float) Math.tan(Math.toRadians(0.5f * fov)); float a = q / aspectRatio; float b = (near + far) / (near - far); float c = (2f * near * far) / (near - far); elements[M00] = a; elements[M11] = q; elements[M22] = b; elements[M23] = -1f; elements[M32] = c; return new Matrix4(elements); } public Matrix4 LookAt(Vec3 position, Vec3 target, Vec3 up) { float[] elements = new float[16]; elements[M00] = 1f; elements[M11] = 1f; elements[M22] = 1f; elements[M33] = 1f; Vec3 f = position.sub(target).normalize(); Vec3 s = f.cross(up.normalize()); Vec3 u = s.cross(f); elements[M00] = s.x; elements[M01] = s.y; elements[M02] = s.z; elements[M10] = u.x; elements[M11] = u.y; elements[M12] = u.z; elements[M20] = -f.x; elements[M21] = -f.y; elements[M22] = -f.z; return new Matrix4(elements).multiply(Translation(-position.x, -position.y, -position.z)); } public static Matrix4 Scale(float sx, float sy, float sz) { float[] elements = new float[16]; elements[M00] = 1f; elements[M11] = 1f; elements[M22] = 1f; elements[M33] = 1f; elements[M00] *= sx; elements[M11] *= sy; elements[M22] *= sz; return new Matrix4(elements); } public static Matrix4 Rotation(float angle, Vec3 axis) { float[] elements = new float[16]; float r = Mathf.toRadians(angle); float c = Mathf.cos(r); float s = Mathf.sin(r); float t = 1 - c; float x = axis.x; float y = axis.y; float z = axis.z; elements[M00] = x * x * t + c; elements[M01] = y * x * t + z * s; elements[M02] = z * x * t - y * s; // elements[M03] = 0; elements[M10] = x * y * t - z * s; elements[M11] = y * y * t + c; elements[M12] = z * y * t + x * s; // elements[M13] = 0; elements[M20] = x * z * t + y * s; elements[M21] = y * z * t - x * s; elements[M22] = z * z * t + c; // elements[M23] = 0; // elements[M30] = 0; // elements[M31] = 0; // elements[M32] = 0; elements[M33] = 1; return new Matrix4(elements); } public static Matrix4 RotationX(float angle) { float r = Mathf.toRadians(angle); float c = Mathf.cos(r); float s = Mathf.sin(r); float[] elements = new float[16]; elements[M00] = 1; // elements[M01] = 0; // elements[M02] = 0; // elements[M03] = 0; // elements[M10] = 0; elements[M11] = c; elements[M12] = s; // elements[M13] = 0; // elements[M20] = 0; elements[M21] = -s; elements[M22] = c; // elements[M23] = 0; // elements[M30] = 0; // elements[M31] = 0; // elements[M32] = 0; elements[M33] = 1; return new Matrix4(elements); } public static Matrix4 RotationY(float angle) { float r = Mathf.toRadians(angle); float c = Mathf.cos(r); float s = Mathf.sin(r); float[] elements = new float[16]; elements[M00] = c; // elements[M01] = 0; elements[M02] = -s; // elements[M03] = 0; // elements[M10] = 0; elements[M11] = 1; // elements[M12] = 0; // elements[M13] = 0; elements[M20] = s; // elements[M21] = 0; elements[M22] = c; // elements[M23] = 0; // elements[M30] = 0; // elements[M31] = 0; // elements[M32] = 0; elements[M33] = 1; return new Matrix4(elements); } public static Matrix4 RotationZ(float angle) { float r = Mathf.toRadians(angle); float c = Mathf.cos(r); float s = Mathf.sin(r); float[] elements = new float[16]; elements[M00] = c; elements[M01] = s; // elements[M02] = 0; // elements[M03] = 0; elements[M10] = -s; elements[M11] = c; // elements[M12] = 0; // elements[M13] = 0; // elements[M20] = 0; // elements[M21] = 0; elements[M22] = 1; // elements[M23] = 0; // elements[M30] = 0; // elements[M31] = 0; // elements[M32] = 0; elements[M33] = 1; return new Matrix4(elements); } public static Matrix4 Translation(float x, float y, float z) { float[] elements = new float[16]; elements[M00] = 1f; elements[M11] = 1f; elements[M22] = 1f; elements[M33] = 1f; elements[M30] = x; elements[M31] = y; elements[M32] = z; return new Matrix4(elements); } public float[] elements() { return new float[] { m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33 }; } public Matrix4 multiply(Matrix4 m) { float[] elements = new float[16]; //ROW 0 elements[M00] = m.m00 * m00 + m.m01 * m10 + m.m02 * m20 + m.m03 * m30; elements[M01] = m.m00 * m01 + m.m01 * m11 + m.m02 * m21 + m.m03 * m31; elements[M02] = m.m00 * m02 + m.m01 * m12 + m.m02 * m22 + m.m03 * m32; elements[M03] = m.m00 * m03 + m.m01 * m13 + m.m02 * m23 + m.m03 * m33; //ROW 1 elements[M10] = m.m10 * m00 + m.m11 * m10 + m.m12 * m20 + m.m13 * m30; elements[M11] = m.m10 * m01 + m.m11 * m11 + m.m12 * m21 + m.m13 * m31; elements[M12] = m.m10 * m02 + m.m11 * m12 + m.m12 * m22 + m.m13 * m32; elements[M13] = m.m10 * m03 + m.m11 * m13 + m.m12 * m23 + m.m13 * m33; //ROW 2 elements[M20] = m.m20 * m00 + m.m21 * m10 + m.m22 * m20 + m.m23 * m30; elements[M21] = m.m20 * m01 + m.m21 * m11 + m.m22 * m21 + m.m23 * m31; elements[M22] = m.m20 * m02 + m.m21 * m12 + m.m22 * m22 + m.m23 * m32; elements[M23] = m.m20 * m03 + m.m21 * m13 + m.m22 * m23 + m.m23 * m33; //ROW 3 elements[M30] = m.m30 * m00 + m.m31 * m10 + m.m32 * m20 + m.m33 * m30; elements[M31] = m.m30 * m01 + m.m31 * m11 + m.m32 * m21 + m.m33 * m31; elements[M32] = m.m30 * m02 + m.m31 * m12 + m.m32 * m22 + m.m33 * m32; elements[M33] = m.m30 * m03 + m.m31 * m13 + m.m32 * m23 + m.m33 * m33; return new Matrix4(elements); } // assumed Vec4(x, y, 0, 0) public Vec2 multiply(Vec2 v) { float x = m00 * v.x + m10 * v.y; float y = m01 * v.x + m11 * v.y; return new Vec2(x, y); } // assumed Vec4(x, y, z, 0) public Vec3 multiply(Vec3 v) { float x = m00 * v.x + m10 * v.y + m20 * v.z; float y = m01 * v.x + m11 * v.y + m21 * v.z; float z = m02 * v.x + m12 * v.y + m22 * v.z; return new Vec3(x, y, z); } public Vec4 multiply(Vec4 v) { float x = m00 * v.x + m10 * v.y + m20 * v.z + m30 * v.w; float y = m01 * v.x + m11 * v.y + m21 * v.z + m31 * v.w; float z = m02 * v.x + m12 * v.y + m22 * v.z + m32 * v.w; float w = m03 * v.x + m13 * v.y + m23 * v.z + m33 * v.w; return new Vec4(x, y, z, w); } public String toString() { return String.format("[%.2f %.2f %.2f %.2f]", m00, m10, m20, m30) + '\n' + String.format("[%.2f %.2f %.2f %.2f]", m01, m11, m21, m31) + '\n' + String.format("[%.2f %.2f %.2f %.2f]", m02, m12, m22, m32) + '\n' + String.format("[%.2f %.2f %.2f %.2f]", m03, m13, m23, m33) + '\n'; } }
UTF-8
Java
13,548
java
Matrix4.java
Java
[ { "context": "package fr.hadriel.math;\n\n\n/**\n * Created by glathuiliere on 13/07/2016.\n *\n * inspiration from\n * https://", "end": 57, "score": 0.9997134208679199, "start": 45, "tag": "USERNAME", "value": "glathuiliere" }, { "context": "016.\n *\n * inspiration from\n * https://github.com/gamedev-js/vmath/blob/master/lib/mat4.js\n */\npublic strictfp", "end": 128, "score": 0.9993913173675537, "start": 118, "tag": "USERNAME", "value": "gamedev-js" } ]
null
[]
package fr.hadriel.math; /** * Created by glathuiliere on 13/07/2016. * * inspiration from * https://github.com/gamedev-js/vmath/blob/master/lib/mat4.js */ public strictfp class Matrix4 { private static final float[] IDENTITY = new float[] { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; public static final Matrix4 Identity = new Matrix4(); /* * Matrix Order [M_COL_ROW] : * * [M00 .... M30] * [M01 .... M31] * [M02 .... M32] * [M03 .... M33] * */ //First Row public static final byte M00 = 0; public static final byte M01 = 1; public static final byte M02 = 2; public static final byte M03 = 3; //Second Row public static final byte M10 = 4; public static final byte M11 = 5; public static final byte M12 = 6; public static final byte M13 = 7; //Third Row public static final byte M20 = 8; public static final byte M21 = 9; public static final byte M22 = 10; public static final byte M23 = 11; //Third Row public static final byte M30 = 12; public static final byte M31 = 13; public static final byte M32 = 14; public static final byte M33 = 15; public final float m00, m01, m02, m03; public final float m10, m11, m12, m13; public final float m20, m21, m22, m23; public final float m30, m31, m32, m33; public Matrix4( float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23; this.m30 = m30; this.m31 = m31; this.m32 = m32; this.m33 = m33; } public Matrix4(float[] matrix) { this( matrix[M00], matrix[M01], matrix[M02], matrix[M03], matrix[M10], matrix[M11], matrix[M12], matrix[M13], matrix[M20], matrix[M21], matrix[M22], matrix[M23], matrix[M30], matrix[M31], matrix[M32], matrix[M33]); } public Matrix4(Matrix4 m) { this( m.m00, m.m01, m.m02, m.m03, m.m10, m.m11, m.m12, m.m13, m.m20, m.m21, m.m22, m.m23, m.m30, m.m31, m.m32, m.m33); } public Matrix4() { this(IDENTITY); } public float determinant() { float b00 = m00 * m11 - m01 * m10; float b01 = m00 * m12 - m02 * m10; float b02 = m00 * m13 - m03 * m10; float b03 = m01 * m12 - m02 * m11; float b04 = m01 * m13 - m03 * m11; float b05 = m02 * m13 - m03 * m12; float b06 = m20 * m31 - m21 * m30; float b07 = m20 * m32 - m22 * m30; float b08 = m20 * m33 - m23 * m30; float b09 = m21 * m32 - m22 * m31; float b10 = m21 * m33 - m23 * m31; float b11 = m22 * m33 - m23 * m32; return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; } public Matrix4 invert() { float b00 = m00 * m11 - m01 * m10; float b01 = m00 * m12 - m02 * m10; float b02 = m00 * m13 - m03 * m10; float b03 = m01 * m12 - m02 * m11; float b04 = m01 * m13 - m03 * m11; float b05 = m02 * m13 - m03 * m12; float b06 = m20 * m31 - m21 * m30; float b07 = m20 * m32 - m22 * m30; float b08 = m20 * m33 - m23 * m30; float b09 = m21 * m32 - m22 * m31; float b10 = m21 * m33 - m23 * m31; float b11 = m22 * m33 - m23 * m32; float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if(det == 0) return null; // singular matrix det = 1f / det; float[] elements = new float[16]; elements[M00] = (m11 * b11 - m12 * b10 + m13 * b09) * det; elements[M01] = (m02 * b10 - m01 * b11 - m03 * b09) * det; elements[M02] = (m31 * b05 - m32 * b04 + m33 * b03) * det; elements[M03] = (m22 * b04 - m21 * b05 - m23 * b03) * det; elements[M10] = (m12 * b08 - m10 * b11 - m13 * b07) * det; elements[M11] = (m00 * b11 - m02 * b08 + m03 * b07) * det; elements[M12] = (m32 * b02 - m30 * b05 - m33 * b01) * det; elements[M13] = (m20 * b05 - m22 * b02 + m23 * b01) * det; elements[M20] = (m10 * b10 - m11 * b08 + m13 * b06) * det; elements[M21] = (m01 * b08 - m00 * b10 - m03 * b06) * det; elements[M22] = (m30 * b04 - m31 * b02 + m33 * b00) * det; elements[M23] = (m21 * b02 - m20 * b04 - m23 * b00) * det; elements[M30] = (m11 * b07 - m10 * b09 - m12 * b06) * det; elements[M31] = (m00 * b09 - m01 * b07 + m02 * b06) * det; elements[M32] = (m31 * b01 - m30 * b03 - m32 * b00) * det; elements[M33] = (m20 * b03 - m21 * b01 + m22 * b00) * det; return new Matrix4(elements); } public static Matrix4 Orthographic(float left, float right, float top, float bottom, float near, float far) { float[] elements = new float[16]; elements[M00] = 2f / (right - left); elements[M11] = 2f / (top - bottom); elements[M22] = -2f / (far - near); elements[M33] = 1f; elements[M30] = -(right + left) / (right - left); elements[M31] = -(top + bottom) / (top - bottom); elements[M32] = -(far + near) / (far - near); return new Matrix4(elements); } public Matrix4 Perspective(float fov, float aspectRatio, float near, float far) { float[] elements = new float[16]; elements[M00] = 1f; elements[M11] = 1f; elements[M22] = 1f; elements[M33] = 1f; float q = 1f / (float) Math.tan(Math.toRadians(0.5f * fov)); float a = q / aspectRatio; float b = (near + far) / (near - far); float c = (2f * near * far) / (near - far); elements[M00] = a; elements[M11] = q; elements[M22] = b; elements[M23] = -1f; elements[M32] = c; return new Matrix4(elements); } public Matrix4 LookAt(Vec3 position, Vec3 target, Vec3 up) { float[] elements = new float[16]; elements[M00] = 1f; elements[M11] = 1f; elements[M22] = 1f; elements[M33] = 1f; Vec3 f = position.sub(target).normalize(); Vec3 s = f.cross(up.normalize()); Vec3 u = s.cross(f); elements[M00] = s.x; elements[M01] = s.y; elements[M02] = s.z; elements[M10] = u.x; elements[M11] = u.y; elements[M12] = u.z; elements[M20] = -f.x; elements[M21] = -f.y; elements[M22] = -f.z; return new Matrix4(elements).multiply(Translation(-position.x, -position.y, -position.z)); } public static Matrix4 Scale(float sx, float sy, float sz) { float[] elements = new float[16]; elements[M00] = 1f; elements[M11] = 1f; elements[M22] = 1f; elements[M33] = 1f; elements[M00] *= sx; elements[M11] *= sy; elements[M22] *= sz; return new Matrix4(elements); } public static Matrix4 Rotation(float angle, Vec3 axis) { float[] elements = new float[16]; float r = Mathf.toRadians(angle); float c = Mathf.cos(r); float s = Mathf.sin(r); float t = 1 - c; float x = axis.x; float y = axis.y; float z = axis.z; elements[M00] = x * x * t + c; elements[M01] = y * x * t + z * s; elements[M02] = z * x * t - y * s; // elements[M03] = 0; elements[M10] = x * y * t - z * s; elements[M11] = y * y * t + c; elements[M12] = z * y * t + x * s; // elements[M13] = 0; elements[M20] = x * z * t + y * s; elements[M21] = y * z * t - x * s; elements[M22] = z * z * t + c; // elements[M23] = 0; // elements[M30] = 0; // elements[M31] = 0; // elements[M32] = 0; elements[M33] = 1; return new Matrix4(elements); } public static Matrix4 RotationX(float angle) { float r = Mathf.toRadians(angle); float c = Mathf.cos(r); float s = Mathf.sin(r); float[] elements = new float[16]; elements[M00] = 1; // elements[M01] = 0; // elements[M02] = 0; // elements[M03] = 0; // elements[M10] = 0; elements[M11] = c; elements[M12] = s; // elements[M13] = 0; // elements[M20] = 0; elements[M21] = -s; elements[M22] = c; // elements[M23] = 0; // elements[M30] = 0; // elements[M31] = 0; // elements[M32] = 0; elements[M33] = 1; return new Matrix4(elements); } public static Matrix4 RotationY(float angle) { float r = Mathf.toRadians(angle); float c = Mathf.cos(r); float s = Mathf.sin(r); float[] elements = new float[16]; elements[M00] = c; // elements[M01] = 0; elements[M02] = -s; // elements[M03] = 0; // elements[M10] = 0; elements[M11] = 1; // elements[M12] = 0; // elements[M13] = 0; elements[M20] = s; // elements[M21] = 0; elements[M22] = c; // elements[M23] = 0; // elements[M30] = 0; // elements[M31] = 0; // elements[M32] = 0; elements[M33] = 1; return new Matrix4(elements); } public static Matrix4 RotationZ(float angle) { float r = Mathf.toRadians(angle); float c = Mathf.cos(r); float s = Mathf.sin(r); float[] elements = new float[16]; elements[M00] = c; elements[M01] = s; // elements[M02] = 0; // elements[M03] = 0; elements[M10] = -s; elements[M11] = c; // elements[M12] = 0; // elements[M13] = 0; // elements[M20] = 0; // elements[M21] = 0; elements[M22] = 1; // elements[M23] = 0; // elements[M30] = 0; // elements[M31] = 0; // elements[M32] = 0; elements[M33] = 1; return new Matrix4(elements); } public static Matrix4 Translation(float x, float y, float z) { float[] elements = new float[16]; elements[M00] = 1f; elements[M11] = 1f; elements[M22] = 1f; elements[M33] = 1f; elements[M30] = x; elements[M31] = y; elements[M32] = z; return new Matrix4(elements); } public float[] elements() { return new float[] { m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33 }; } public Matrix4 multiply(Matrix4 m) { float[] elements = new float[16]; //ROW 0 elements[M00] = m.m00 * m00 + m.m01 * m10 + m.m02 * m20 + m.m03 * m30; elements[M01] = m.m00 * m01 + m.m01 * m11 + m.m02 * m21 + m.m03 * m31; elements[M02] = m.m00 * m02 + m.m01 * m12 + m.m02 * m22 + m.m03 * m32; elements[M03] = m.m00 * m03 + m.m01 * m13 + m.m02 * m23 + m.m03 * m33; //ROW 1 elements[M10] = m.m10 * m00 + m.m11 * m10 + m.m12 * m20 + m.m13 * m30; elements[M11] = m.m10 * m01 + m.m11 * m11 + m.m12 * m21 + m.m13 * m31; elements[M12] = m.m10 * m02 + m.m11 * m12 + m.m12 * m22 + m.m13 * m32; elements[M13] = m.m10 * m03 + m.m11 * m13 + m.m12 * m23 + m.m13 * m33; //ROW 2 elements[M20] = m.m20 * m00 + m.m21 * m10 + m.m22 * m20 + m.m23 * m30; elements[M21] = m.m20 * m01 + m.m21 * m11 + m.m22 * m21 + m.m23 * m31; elements[M22] = m.m20 * m02 + m.m21 * m12 + m.m22 * m22 + m.m23 * m32; elements[M23] = m.m20 * m03 + m.m21 * m13 + m.m22 * m23 + m.m23 * m33; //ROW 3 elements[M30] = m.m30 * m00 + m.m31 * m10 + m.m32 * m20 + m.m33 * m30; elements[M31] = m.m30 * m01 + m.m31 * m11 + m.m32 * m21 + m.m33 * m31; elements[M32] = m.m30 * m02 + m.m31 * m12 + m.m32 * m22 + m.m33 * m32; elements[M33] = m.m30 * m03 + m.m31 * m13 + m.m32 * m23 + m.m33 * m33; return new Matrix4(elements); } // assumed Vec4(x, y, 0, 0) public Vec2 multiply(Vec2 v) { float x = m00 * v.x + m10 * v.y; float y = m01 * v.x + m11 * v.y; return new Vec2(x, y); } // assumed Vec4(x, y, z, 0) public Vec3 multiply(Vec3 v) { float x = m00 * v.x + m10 * v.y + m20 * v.z; float y = m01 * v.x + m11 * v.y + m21 * v.z; float z = m02 * v.x + m12 * v.y + m22 * v.z; return new Vec3(x, y, z); } public Vec4 multiply(Vec4 v) { float x = m00 * v.x + m10 * v.y + m20 * v.z + m30 * v.w; float y = m01 * v.x + m11 * v.y + m21 * v.z + m31 * v.w; float z = m02 * v.x + m12 * v.y + m22 * v.z + m32 * v.w; float w = m03 * v.x + m13 * v.y + m23 * v.z + m33 * v.w; return new Vec4(x, y, z, w); } public String toString() { return String.format("[%.2f %.2f %.2f %.2f]", m00, m10, m20, m30) + '\n' + String.format("[%.2f %.2f %.2f %.2f]", m01, m11, m21, m31) + '\n' + String.format("[%.2f %.2f %.2f %.2f]", m02, m12, m22, m32) + '\n' + String.format("[%.2f %.2f %.2f %.2f]", m03, m13, m23, m33) + '\n'; } }
13,548
0.493578
0.376366
397
33.128464
22.225569
113
false
false
0
0
0
0
0
0
1.007557
false
false
9
e0a6fc3ffbd60808da459e03632e8ddfd1e5d334
13,228,499,299,370
6fe9c8fab624731305d659faaceab6684a077d7e
/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/BaseActivity.java
fd7134f930cd963421a981d8be59db625e7b5393
[ "Apache-2.0" ]
permissive
eoinahern/google_mvp_refactor
https://github.com/eoinahern/google_mvp_refactor
c2847749165c80c39fbf14349b2afe4e210617c2
3dd887e47a9880e32513b0a3808431d85353f037
refs/heads/todo-mvp-clean
2021-07-14T00:37:22.720000
2017-10-18T10:56:47
2017-10-18T10:56:47
106,536,332
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.android.architecture.blueprints.todoapp; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import butterknife.BindView; import butterknife.ButterKnife; public abstract class BaseActivity extends AppCompatActivity { protected @BindView(R.id.toolbar) Toolbar toolbar; protected ActionBar ab; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int layout = getChildLayout(); if (layout != 0) { setContentView(layout); ButterKnife.bind(this); } inject(); } protected void setUpToolbar() { //toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ab = getSupportActionBar(); } public abstract int getChildLayout(); public abstract void inject(); }
UTF-8
Java
885
java
BaseActivity.java
Java
[]
null
[]
package com.example.android.architecture.blueprints.todoapp; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import butterknife.BindView; import butterknife.ButterKnife; public abstract class BaseActivity extends AppCompatActivity { protected @BindView(R.id.toolbar) Toolbar toolbar; protected ActionBar ab; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int layout = getChildLayout(); if (layout != 0) { setContentView(layout); ButterKnife.bind(this); } inject(); } protected void setUpToolbar() { //toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ab = getSupportActionBar(); } public abstract int getChildLayout(); public abstract void inject(); }
885
0.766102
0.761582
39
21.692308
19.814724
62
false
false
0
0
0
0
0
0
1.282051
false
false
9
32d5557d458c90bfe703948c59d12c87312d326f
26,233,660,278,095
b21b304b80391491faf4f5f9e717f3e29f745a82
/2016-01/Cristiano/Programacao2/Aula5 - 28.03/Exercicio_Funcionario_1.3/src/classes/Funcionario.java
19750499c7ae470a8251bbaf6bdbcbceb63d3127
[]
no_license
ClarkCouto/IFRS
https://github.com/ClarkCouto/IFRS
4dad7d85597442203671d518ebbe7864a3ad36f5
8813d53796627ab5b72d4c66eeb45039554b8d0c
refs/heads/master
2021-01-10T18:20:06.500000
2017-03-23T23:35:22
2017-03-23T23:35:22
53,939,674
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package classes; public class Funcionario { private String nome; private char sexo; private String cpf; private double salarioBruto; private Endereco endereco; public Funcionario(){} public Funcionario(String nome, char sexo, String cpf, double salario){ setNome(nome); setSexo(sexo); setCpf(cpf); setSalarioBruto(salario); } public Funcionario(String nome, char sexo, String cpf, double salario, Endereco endereco){ setNome(nome); setSexo(sexo); setCpf(cpf); setSalarioBruto(salario); setEndereco(endereco); } public String getNome() { return this.nome; } public void setNome(String nome) { this.nome = nome; } public char getSexo() { return this.sexo; } public void setSexo(char sexo) { this.sexo = sexo; } public String getCpf() { return this.cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public double getSalarioBruto() { return this.salarioBruto; } public void setSalarioBruto(double salarioBruto) { this.salarioBruto = salarioBruto; } public double txINSS(double salario){ if(salario <= 1000){ return 8; } else if(salario > 1000 && salario <= 2000){ return 9; } else if(salario > 1000 && salario <= 2000){ return 10; } else { return 11; } } public double valorINSS(){ double salario = this.getSalarioBruto(); double inss = salario * this.txINSS(salario)/100; if(inss > 900){ inss = 900; } return inss; } public double salarioLiquido(){ return this.getSalarioBruto() - this.valorINSS(); } public String getEndereco(){ return endereco.toString(); } public Endereco getEnderecoObjeto(){ return this.endereco; } public void setEndereco(Endereco endereco){ this.endereco = endereco; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((cpf == null) ? 0 : cpf.hashCode()); result = prime * result + ((endereco == null) ? 0 : endereco.hashCode()); result = prime * result + ((nome == null) ? 0 : nome.hashCode()); long temp; temp = Double.doubleToLongBits(salarioBruto); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + sexo; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Funcionario other = (Funcionario) obj; Endereco e = other.getEnderecoObjeto(); if (cpf == null) { if (other.cpf != null) return false; } else if (!cpf.equals(other.cpf)) return false; if (endereco == null) { if (other.endereco != null) return false; } else if (!endereco.equals(e)) return false; if (nome == null) { if (other.nome != null) return false; } else if (!nome.equals(other.nome)) return false; if (Double.doubleToLongBits(salarioBruto) != Double.doubleToLongBits(other.salarioBruto)) return false; if (sexo != other.sexo) return false; return true; } @Override public String toString() { return "Nome = " + this.getNome() + "\nSexo: " + this.getSexo() + "\nCPF: " + this.getCpf() + "\nSalário: R$ " + this.getSalarioBruto() + "\n"+ this.getEndereco(); } }
WINDOWS-1250
Java
3,227
java
Funcionario.java
Java
[]
null
[]
package classes; public class Funcionario { private String nome; private char sexo; private String cpf; private double salarioBruto; private Endereco endereco; public Funcionario(){} public Funcionario(String nome, char sexo, String cpf, double salario){ setNome(nome); setSexo(sexo); setCpf(cpf); setSalarioBruto(salario); } public Funcionario(String nome, char sexo, String cpf, double salario, Endereco endereco){ setNome(nome); setSexo(sexo); setCpf(cpf); setSalarioBruto(salario); setEndereco(endereco); } public String getNome() { return this.nome; } public void setNome(String nome) { this.nome = nome; } public char getSexo() { return this.sexo; } public void setSexo(char sexo) { this.sexo = sexo; } public String getCpf() { return this.cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public double getSalarioBruto() { return this.salarioBruto; } public void setSalarioBruto(double salarioBruto) { this.salarioBruto = salarioBruto; } public double txINSS(double salario){ if(salario <= 1000){ return 8; } else if(salario > 1000 && salario <= 2000){ return 9; } else if(salario > 1000 && salario <= 2000){ return 10; } else { return 11; } } public double valorINSS(){ double salario = this.getSalarioBruto(); double inss = salario * this.txINSS(salario)/100; if(inss > 900){ inss = 900; } return inss; } public double salarioLiquido(){ return this.getSalarioBruto() - this.valorINSS(); } public String getEndereco(){ return endereco.toString(); } public Endereco getEnderecoObjeto(){ return this.endereco; } public void setEndereco(Endereco endereco){ this.endereco = endereco; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((cpf == null) ? 0 : cpf.hashCode()); result = prime * result + ((endereco == null) ? 0 : endereco.hashCode()); result = prime * result + ((nome == null) ? 0 : nome.hashCode()); long temp; temp = Double.doubleToLongBits(salarioBruto); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + sexo; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Funcionario other = (Funcionario) obj; Endereco e = other.getEnderecoObjeto(); if (cpf == null) { if (other.cpf != null) return false; } else if (!cpf.equals(other.cpf)) return false; if (endereco == null) { if (other.endereco != null) return false; } else if (!endereco.equals(e)) return false; if (nome == null) { if (other.nome != null) return false; } else if (!nome.equals(other.nome)) return false; if (Double.doubleToLongBits(salarioBruto) != Double.doubleToLongBits(other.salarioBruto)) return false; if (sexo != other.sexo) return false; return true; } @Override public String toString() { return "Nome = " + this.getNome() + "\nSexo: " + this.getSexo() + "\nCPF: " + this.getCpf() + "\nSalário: R$ " + this.getSalarioBruto() + "\n"+ this.getEndereco(); } }
3,227
0.651891
0.638562
148
20.797297
20.721434
142
false
false
0
0
0
0
0
0
2.074324
false
false
9
552a138f5a0e724af03aac2a49e1df845e247426
21,766,894,285,804
37fef43963ce2d6b1deb44f181917672f16d2c0f
/Double/IsNaN.java
4ec04656a9e188d6391786d961d7619babfd90a6
[]
no_license
SD-JML-Float/JML-Examples
https://github.com/SD-JML-Float/JML-Examples
47b9b21d7f8b1f0647f3ab8e16cf7bcb1316faaf
c884fe9995d2cfbe427cae37a1e2aec51be19b4d
refs/heads/master
2023-06-30T20:39:48.809000
2021-08-05T04:12:50
2021-08-05T04:12:50
369,027,071
1
1
null
false
2021-08-05T04:12:50
2021-05-19T23:35:12
2021-08-04T19:06:56
2021-08-05T04:12:50
169,851
1
1
0
Java
false
false
public class IsNaN{ //@ requires Double.isFinite(a); public static void isNaNTest(double a) { boolean staticResult = Double.isNaN(a); Double instance = a; boolean instanceResult = instance.isNaN(); //@ assert staticResult == false; //@ assert instanceResult == false; } //@ requires !Double.isFinite(a); public static void isNaNTestAnomalies(double a) { boolean staticResult = Double.isNaN(a); Double instance = a; boolean instanceResult = instance.isNaN(); //@ assert (Double.compare(a, Double.POSITIVE_INFINITY) == 0) ==> (staticResult == false); //@ assert (Double.compare(a, Double.NEGATIVE_INFINITY) == 0) ==> (staticResult == false); //@ assert (Double.compare(a, Double.POSITIVE_INFINITY) == 0) ==> (instanceResult == false); //@ assert (Double.compare(a, Double.NEGATIVE_INFINITY) == 0) ==> (instanceResult == false); // If we've reached this point, a must be NaN //@ assert staticResult == true; //@ assert instanceResult == true; } }
UTF-8
Java
1,021
java
IsNaN.java
Java
[]
null
[]
public class IsNaN{ //@ requires Double.isFinite(a); public static void isNaNTest(double a) { boolean staticResult = Double.isNaN(a); Double instance = a; boolean instanceResult = instance.isNaN(); //@ assert staticResult == false; //@ assert instanceResult == false; } //@ requires !Double.isFinite(a); public static void isNaNTestAnomalies(double a) { boolean staticResult = Double.isNaN(a); Double instance = a; boolean instanceResult = instance.isNaN(); //@ assert (Double.compare(a, Double.POSITIVE_INFINITY) == 0) ==> (staticResult == false); //@ assert (Double.compare(a, Double.NEGATIVE_INFINITY) == 0) ==> (staticResult == false); //@ assert (Double.compare(a, Double.POSITIVE_INFINITY) == 0) ==> (instanceResult == false); //@ assert (Double.compare(a, Double.NEGATIVE_INFINITY) == 0) ==> (instanceResult == false); // If we've reached this point, a must be NaN //@ assert staticResult == true; //@ assert instanceResult == true; } }
1,021
0.651322
0.647404
26
38.26923
29.0352
96
false
false
0
0
0
0
0
0
0.807692
false
false
9
d39afc573d7bb1e166e63876a2df3e232a2e46c2
18,700,287,663,943
e925bae4141804d3c286d41ee702169f718a3943
/GeeksforGeeks/Graph/DetectCycleInADirectedGraph.java
393d422bb5d7798147a73da860c23eef08d5cc74
[]
no_license
dream-achiever/Coding-Questions
https://github.com/dream-achiever/Coding-Questions
dde4b9940f1d955ecbb27afb564e9d01009aaa1b
93aa07efb85255271e980bc5691755c2c2d425c3
refs/heads/master
2021-12-12T00:42:24.687000
2021-12-09T17:54:11
2021-12-09T17:54:11
249,751,290
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Given a Directed Graph with V vertices (Numbered from 0 to V-1) and E edges, check whether it contains any cycle or not. Example 1: Input: Output: 1 Explanation: 3 -> 3 is a cycle Example 2: Input: Output: 0 Explanation: no cycle in the graph Your task: You don’t need to read input or print anything. Your task is to complete the function isCyclic() which takes the integer V denoting the number of vertices and adjacency list as input parameters and returns a boolean value denoting if the given directed graph contains a cycle or not. Expected Time Complexity: O(V + E) Expected Auxiliary Space: O(V) Constraints: 1 ≤ V, E ≤ 105 #####################################################################################Solution####################################################################### */ class Solution { public boolean dfsRec(ArrayList<ArrayList<Integer>> adj,int s,boolean visited[],boolean recSt[]){ visited[s]=true; recSt[s]=true; for(int v : adj.get(s)){ if(!visited[v]){ if(dfsRec(adj,v,visited,recSt)){ return true; } } if(recSt[v]){ return true; } } recSt[s]=false; return false; } //Function to detect cycle in a directed graph. public boolean isCyclic(int V, ArrayList<ArrayList<Integer>> adj) { // code here boolean visited[] = new boolean[V]; boolean recSt[] = new boolean[V]; for(int i=0;i<V;i++){ if(!visited[i]){ if(dfsRec(adj,i,visited,recSt)){ return true; } } } return false; } }
UTF-8
Java
1,866
java
DetectCycleInADirectedGraph.java
Java
[]
null
[]
/* Given a Directed Graph with V vertices (Numbered from 0 to V-1) and E edges, check whether it contains any cycle or not. Example 1: Input: Output: 1 Explanation: 3 -> 3 is a cycle Example 2: Input: Output: 0 Explanation: no cycle in the graph Your task: You don’t need to read input or print anything. Your task is to complete the function isCyclic() which takes the integer V denoting the number of vertices and adjacency list as input parameters and returns a boolean value denoting if the given directed graph contains a cycle or not. Expected Time Complexity: O(V + E) Expected Auxiliary Space: O(V) Constraints: 1 ≤ V, E ≤ 105 #####################################################################################Solution####################################################################### */ class Solution { public boolean dfsRec(ArrayList<ArrayList<Integer>> adj,int s,boolean visited[],boolean recSt[]){ visited[s]=true; recSt[s]=true; for(int v : adj.get(s)){ if(!visited[v]){ if(dfsRec(adj,v,visited,recSt)){ return true; } } if(recSt[v]){ return true; } } recSt[s]=false; return false; } //Function to detect cycle in a directed graph. public boolean isCyclic(int V, ArrayList<ArrayList<Integer>> adj) { // code here boolean visited[] = new boolean[V]; boolean recSt[] = new boolean[V]; for(int i=0;i<V;i++){ if(!visited[i]){ if(dfsRec(adj,i,visited,recSt)){ return true; } } } return false; } }
1,866
0.492473
0.485484
78
22.846153
39.85714
283
false
false
0
0
0
0
0
0
0.307692
false
false
9
f50d6d2a8efb5724d2629e10f38edbf5c608a7d6
34,033,320,903,025
418972d25f6d574bbc019c37b71d0cd93b6d9402
/amazonmapswrapper/src/main/java/de/quist/app/maps/amazon/GroundOverlay.java
c6e68fd963fdbd75f12113eb103ab4d1aa9abc2f
[ "Apache-2.0" ]
permissive
tomquist/android-maps-abstraction
https://github.com/tomquist/android-maps-abstraction
37e950961a85cfa33d97769ac59b78d709f219d4
eb5b133a4ba44cf2aa0a68daf610203a704a3c27
refs/heads/master
2021-01-10T00:53:29.109000
2015-03-21T13:10:59
2015-03-21T13:10:59
31,922,864
2
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.quist.app.maps.amazon; import de.quist.app.maps.utils.Wrapper; class GroundOverlay extends Wrapper<com.amazon.geo.mapsv2.model.GroundOverlay> implements de.quist.app.maps.model.GroundOverlay { static final Mapper<de.quist.app.maps.model.GroundOverlay, GroundOverlay, com.amazon.geo.mapsv2.model.GroundOverlay> MAPPER = new DefaultMapper<de.quist.app.maps.model.GroundOverlay, GroundOverlay, com.amazon.geo.mapsv2.model.GroundOverlay>() { @Override public GroundOverlay createWrapper(com.amazon.geo.mapsv2.model.GroundOverlay original) { return original != null ? new GroundOverlay(original) : null; } }; private GroundOverlay(com.amazon.geo.mapsv2.model.GroundOverlay original) { super(original); } @Override public void remove() { original.remove(); } @Override public String getId() { return original.getId(); } @Override public void setPosition(de.quist.app.maps.model.LatLng latLng) { original.setPosition(LatLng.MAPPER.unwrap(latLng)); } @Override public de.quist.app.maps.model.LatLng getPosition() { return LatLng.MAPPER.wrap(original.getPosition()); } @Override public void setImage(de.quist.app.maps.model.BitmapDescriptor image) { original.setImage(BitmapDescriptor.MAPPER.unwrap(image)); } @Override public void setDimensions(float width) { original.setDimensions(width); } @Override public void setDimensions(float width, float height) { original.setDimensions(width, height); } @Override public float getWidth() { return original.getWidth(); } @Override public float getHeight() { return original.getHeight(); } @Override public void setPositionFromBounds(de.quist.app.maps.model.LatLngBounds bounds) { original.setPositionFromBounds(LatLngBounds.MAPPER.unwrap(bounds)); } @Override public de.quist.app.maps.model.LatLngBounds getBounds() { return LatLngBounds.MAPPER.wrap(original.getBounds()); } @Override public void setBearing(float bearing) { original.setBearing(bearing); } @Override public float getBearing() { return original.getBearing(); } @Override public void setZIndex(float zIndex) { original.setZIndex(zIndex); } @Override public float getZIndex() { return original.getZIndex(); } @Override public void setVisible(boolean visible) { original.setVisible(visible); } @Override public boolean isVisible() { return original.isVisible(); } @Override public void setTransparency(float transparency) { original.setTransparency(transparency); } @Override public float getTransparency() { return original.getTransparency(); } }
UTF-8
Java
2,923
java
GroundOverlay.java
Java
[]
null
[]
package de.quist.app.maps.amazon; import de.quist.app.maps.utils.Wrapper; class GroundOverlay extends Wrapper<com.amazon.geo.mapsv2.model.GroundOverlay> implements de.quist.app.maps.model.GroundOverlay { static final Mapper<de.quist.app.maps.model.GroundOverlay, GroundOverlay, com.amazon.geo.mapsv2.model.GroundOverlay> MAPPER = new DefaultMapper<de.quist.app.maps.model.GroundOverlay, GroundOverlay, com.amazon.geo.mapsv2.model.GroundOverlay>() { @Override public GroundOverlay createWrapper(com.amazon.geo.mapsv2.model.GroundOverlay original) { return original != null ? new GroundOverlay(original) : null; } }; private GroundOverlay(com.amazon.geo.mapsv2.model.GroundOverlay original) { super(original); } @Override public void remove() { original.remove(); } @Override public String getId() { return original.getId(); } @Override public void setPosition(de.quist.app.maps.model.LatLng latLng) { original.setPosition(LatLng.MAPPER.unwrap(latLng)); } @Override public de.quist.app.maps.model.LatLng getPosition() { return LatLng.MAPPER.wrap(original.getPosition()); } @Override public void setImage(de.quist.app.maps.model.BitmapDescriptor image) { original.setImage(BitmapDescriptor.MAPPER.unwrap(image)); } @Override public void setDimensions(float width) { original.setDimensions(width); } @Override public void setDimensions(float width, float height) { original.setDimensions(width, height); } @Override public float getWidth() { return original.getWidth(); } @Override public float getHeight() { return original.getHeight(); } @Override public void setPositionFromBounds(de.quist.app.maps.model.LatLngBounds bounds) { original.setPositionFromBounds(LatLngBounds.MAPPER.unwrap(bounds)); } @Override public de.quist.app.maps.model.LatLngBounds getBounds() { return LatLngBounds.MAPPER.wrap(original.getBounds()); } @Override public void setBearing(float bearing) { original.setBearing(bearing); } @Override public float getBearing() { return original.getBearing(); } @Override public void setZIndex(float zIndex) { original.setZIndex(zIndex); } @Override public float getZIndex() { return original.getZIndex(); } @Override public void setVisible(boolean visible) { original.setVisible(visible); } @Override public boolean isVisible() { return original.isVisible(); } @Override public void setTransparency(float transparency) { original.setTransparency(transparency); } @Override public float getTransparency() { return original.getTransparency(); } }
2,923
0.667465
0.665754
114
24.64035
32.760998
248
false
false
0
0
0
0
0
0
0.263158
false
false
9
423fc29ce89f51bd76dabbad615422ebacc6d758
34,583,076,711,726
f971dabf9d11c14e94eb46c5bf813788cf1f4ee3
/wiki/src/main/java/org/codelibs/stconv/wiki/pukiwiki/pipeline/valve/ConvertPageNameLinkValve.java
bd4ab3a499eea5f838a58a84d833a03439fbd8ee
[]
no_license
codelibs/stconv
https://github.com/codelibs/stconv
4ca07418edbac42abd1de65fcd5dc75c73779af1
61cc057b54d73a2c8b59461251adcadd35954070
refs/heads/master
2023-03-22T03:50:36.389000
2012-12-24T13:28:11
2012-12-24T13:28:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.codelibs.stconv.wiki.pukiwiki.pipeline.valve; import java.io.BufferedWriter; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.codelibs.stconv.storage.StreamStorage; import org.codelibs.stconv.wiki.storage.callback.LinkGeneratorCallback; import org.codelibs.stconv.wiki.storage.impl.CallbackStreamStorageImpl; public class ConvertPageNameLinkValve extends AbstractWikiValve { private String pattern = ".*[A-Z][a-z]+[A-Z][a-z]+.*"; @Override protected String getPattern() { return pattern; } @Override protected void writeMatchLine(final StreamStorage storage, final BufferedWriter writer, final String line) throws IOException { final LinkGeneratorCallback callback = (LinkGeneratorCallback) ((CallbackStreamStorageImpl) storage) .getCallback(LinkGeneratorCallback.LINK_GENERATOR_CALLBACK); if (callback == null) { writeUnmatchLine(writer, line); return; } final Pattern pattern = Pattern.compile("([A-Z][a-z]+([A-Z][a-z]+)+)"); final Matcher matcher = pattern.matcher(line); final StringBuffer buf = new StringBuffer(); while (matcher.find()) { final String pageName = matcher.group(1); callback.init(); callback.addAttribute(LinkGeneratorCallback.PAGE_NAME, pageName); matcher.appendReplacement(buf, "<a href=\"" + callback.getUrl() + "\">" + pageName + "</a>"); } matcher.appendTail(buf); writer.write(buf.toString()); writer.newLine(); } }
UTF-8
Java
1,662
java
ConvertPageNameLinkValve.java
Java
[]
null
[]
package org.codelibs.stconv.wiki.pukiwiki.pipeline.valve; import java.io.BufferedWriter; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.codelibs.stconv.storage.StreamStorage; import org.codelibs.stconv.wiki.storage.callback.LinkGeneratorCallback; import org.codelibs.stconv.wiki.storage.impl.CallbackStreamStorageImpl; public class ConvertPageNameLinkValve extends AbstractWikiValve { private String pattern = ".*[A-Z][a-z]+[A-Z][a-z]+.*"; @Override protected String getPattern() { return pattern; } @Override protected void writeMatchLine(final StreamStorage storage, final BufferedWriter writer, final String line) throws IOException { final LinkGeneratorCallback callback = (LinkGeneratorCallback) ((CallbackStreamStorageImpl) storage) .getCallback(LinkGeneratorCallback.LINK_GENERATOR_CALLBACK); if (callback == null) { writeUnmatchLine(writer, line); return; } final Pattern pattern = Pattern.compile("([A-Z][a-z]+([A-Z][a-z]+)+)"); final Matcher matcher = pattern.matcher(line); final StringBuffer buf = new StringBuffer(); while (matcher.find()) { final String pageName = matcher.group(1); callback.init(); callback.addAttribute(LinkGeneratorCallback.PAGE_NAME, pageName); matcher.appendReplacement(buf, "<a href=\"" + callback.getUrl() + "\">" + pageName + "</a>"); } matcher.appendTail(buf); writer.write(buf.toString()); writer.newLine(); } }
1,662
0.658845
0.658243
47
34.361702
28.430149
108
false
false
0
0
0
0
0
0
0.595745
false
false
9
82a9e687f0f714595e1b8752d40898971c987d54
38,920,993,664,189
46f09910a6440272cc4d24f394870f8e0a732146
/src/Vehicle.java
2d80272e7343fdbfc956e4b3eb41278db4188457
[]
no_license
praveennvs0/reimagined-octo-goggles
https://github.com/praveennvs0/reimagined-octo-goggles
5d9aee57b97f7b71a7981af0ae3b74ff74e1e550
f81da55cf4534aa17600cc0caefc0f57240165c5
refs/heads/master
2023-03-05T18:30:49.914000
2023-02-22T15:34:30
2023-02-22T15:34:30
172,688,231
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public interface Vehicle{ default void drive() { System.out.println("Vehicle is driving"); } default void applyBreaks(){ System.out.println("Vehicle is applying breaks"); } default void applyBreaks2(){ System.out.println("Vehicle is applying breaks"); } }
UTF-8
Java
329
java
Vehicle.java
Java
[]
null
[]
public interface Vehicle{ default void drive() { System.out.println("Vehicle is driving"); } default void applyBreaks(){ System.out.println("Vehicle is applying breaks"); } default void applyBreaks2(){ System.out.println("Vehicle is applying breaks"); } }
329
0.586626
0.583587
15
21
21.740898
61
false
false
0
0
0
0
0
0
0.2
false
false
9
71039d975adff1f03828df38d204d8f188ca6ce6
38,920,993,663,861
cad8773b95fba79a4d78a2970c9ef261b918882c
/src/test/java/org/binarymarshaller/reflect/SuccessMarshallingUnmarshallingPojoClassTest.java
cb6d89ff820e314d364c4393356fa7bf7ba1004b
[]
no_license
sqglobe/BinaryMarshaller
https://github.com/sqglobe/BinaryMarshaller
a66d6dfc7a83d34ae42e526819def33412fb6015
f40d436d495dcd30857127bd74d0118ae4e2d455
refs/heads/master
2020-03-25T03:14:12.909000
2018-08-02T21:45:43
2018-08-02T21:45:43
143,330,303
1
0
null
false
2018-08-02T21:45:44
2018-08-02T18:18:08
2018-08-02T18:18:11
2018-08-02T21:45:44
30
0
0
0
null
false
null
/* * 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 org.binarymarshaller.reflect; import java.nio.ByteBuffer; import org.binarymarshaller.reflect.exception.CallException; import org.binarymarshaller.reflect.exception.InitException; import org.binarymarshaller.reflect.exception.MakeException; import org.binarymarshaller.testutils.research.valid.ValidPojoClass; import org.binarymarshaller.testutils.research.valid.ValidPojoWithGetMethods; import org.binarymarshaller.testutils.research.valid.ValidPojoWithSetMethods; import org.binarymarshaller.testutils.research.valid.ValidPojoWithSkip; import org.junit.Assert; import org.junit.Test; /** * * @author nick */ public class SuccessMarshallingUnmarshallingPojoClassTest { private final byte isok = (byte)0xff; private final short length = (short)0x12a1; private final int type = 0x015f1a12; @Test public void test_unmarshallling_valid_pojo_class_marshalling_Expected_no_error_on_marshalling() throws InitException, MakeException, CallException{ ClassResolver resolver = (new ResolverInitialisator()).init("org.binarymarshaller.testutils.research.valid"); PojoBuilder<ValidPojoClass> wrapper = resolver.getWrapper(0x0000); ByteBuffer buffer = ByteBuffer.allocate(7); buffer.putInt(type); buffer.put(isok); buffer.putShort(length); ValidPojoClass res = wrapper.make(buffer); Assert.assertEquals(isok, res.getIsok() ); Assert.assertEquals(length, res.getLength() ); Assert.assertEquals(type, res.getType()); } @Test public void test_unmarshallling_valid_pojo_with_only_set_methods_Expected_no_erroros() throws InitException, MakeException, CallException{ ClassResolver resolver = (new ResolverInitialisator()).init("org.binarymarshaller.testutils.research.valid"); PojoBuilder<ValidPojoWithSetMethods> wrapper = resolver.getWrapper(0x0003); ByteBuffer buffer = ByteBuffer.allocate(7); buffer.putInt(type); buffer.put(isok); buffer.putShort(length); ValidPojoWithSetMethods res = wrapper.make(buffer); Assert.assertEquals(isok, res.isok ); Assert.assertEquals(length, res.length ); Assert.assertEquals(type, res.type); } @Test public void test_unmarshallling_valid_pojo_with_skip_parameter_Expected_no_errors() throws InitException, MakeException, CallException{ ClassResolver resolver = (new ResolverInitialisator()).init("org.binarymarshaller.testutils.research.valid"); PojoBuilder<ValidPojoWithSkip> wrapper = resolver.getWrapper(0x0001); ByteBuffer buffer = ByteBuffer.allocate(11); buffer.putInt(type); buffer.put(isok); buffer.putShort(length); buffer.putInt(0xffffffff); ValidPojoWithSkip res = wrapper.make(buffer); Assert.assertEquals(isok, res.getIsok() ); Assert.assertEquals(length, res.getLength() ); Assert.assertEquals(type, res.getType()); } @Test public void test_mashalling_valid_pojo_Expected_no_errors() throws InitException, MakeException, CallException{ ClassResolver resolver = (new ResolverInitialisator()).init("org.binarymarshaller.testutils.research.valid"); PojoBuilder<ValidPojoClass> wrapper = resolver.getWrapper(0x0000); ValidPojoClass cls = new ValidPojoClass(); cls.setIsok(isok); cls.setLength(length); cls.setType(type); ByteBuffer buffer = ByteBuffer.allocate(7); buffer.putInt(type); buffer.put(isok); buffer.putShort(length); ByteBuffer res = wrapper.pack(cls); Assert.assertArrayEquals(buffer.array(), res.array()); } @Test public void test_marshalling_valid_pojo_with_get_methods_Expected_no_errors() throws InitException, MakeException, CallException{ ClassResolver resolver = (new ResolverInitialisator()).init("org.binarymarshaller.testutils.research.valid"); PojoBuilder<ValidPojoWithGetMethods> wrapper = resolver.getWrapper(0x0002); ValidPojoWithGetMethods cls = new ValidPojoWithGetMethods(type, isok, length); ByteBuffer buffer = ByteBuffer.allocate(7); buffer.putInt(type); buffer.put(isok); buffer.putShort(length); ByteBuffer res = wrapper.pack(cls); Assert.assertArrayEquals(buffer.array(), res.array()); } public void test_marshalling_valid_pojo_with_skip_Expected_no_errors() throws InitException, MakeException, CallException{ ClassResolver resolver = (new ResolverInitialisator()).init("org.binarymarshaller.testutils.research.valid"); PojoBuilder<ValidPojoWithSkip> wrapper = resolver.getWrapper(0x0001); ValidPojoWithSkip cls = new ValidPojoWithSkip(); cls.setIsok(isok); cls.setLength(length); cls.setType(type); ByteBuffer buffer = ByteBuffer.allocate(11); buffer.putInt(type); buffer.put(isok); buffer.putShort(length); buffer.putInt(0x00000000); ByteBuffer res = wrapper.pack(cls); Assert.assertArrayEquals(buffer.array(), res.array()); } }
UTF-8
Java
5,521
java
SuccessMarshallingUnmarshallingPojoClassTest.java
Java
[ { "context": ".Assert;\nimport org.junit.Test;\n\n/**\n *\n * @author nick\n */\npublic class SuccessMarshallingUnmarshallingPo", "end": 803, "score": 0.8218978643417358, "start": 799, "tag": "USERNAME", "value": "nick" } ]
null
[]
/* * 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 org.binarymarshaller.reflect; import java.nio.ByteBuffer; import org.binarymarshaller.reflect.exception.CallException; import org.binarymarshaller.reflect.exception.InitException; import org.binarymarshaller.reflect.exception.MakeException; import org.binarymarshaller.testutils.research.valid.ValidPojoClass; import org.binarymarshaller.testutils.research.valid.ValidPojoWithGetMethods; import org.binarymarshaller.testutils.research.valid.ValidPojoWithSetMethods; import org.binarymarshaller.testutils.research.valid.ValidPojoWithSkip; import org.junit.Assert; import org.junit.Test; /** * * @author nick */ public class SuccessMarshallingUnmarshallingPojoClassTest { private final byte isok = (byte)0xff; private final short length = (short)0x12a1; private final int type = 0x015f1a12; @Test public void test_unmarshallling_valid_pojo_class_marshalling_Expected_no_error_on_marshalling() throws InitException, MakeException, CallException{ ClassResolver resolver = (new ResolverInitialisator()).init("org.binarymarshaller.testutils.research.valid"); PojoBuilder<ValidPojoClass> wrapper = resolver.getWrapper(0x0000); ByteBuffer buffer = ByteBuffer.allocate(7); buffer.putInt(type); buffer.put(isok); buffer.putShort(length); ValidPojoClass res = wrapper.make(buffer); Assert.assertEquals(isok, res.getIsok() ); Assert.assertEquals(length, res.getLength() ); Assert.assertEquals(type, res.getType()); } @Test public void test_unmarshallling_valid_pojo_with_only_set_methods_Expected_no_erroros() throws InitException, MakeException, CallException{ ClassResolver resolver = (new ResolverInitialisator()).init("org.binarymarshaller.testutils.research.valid"); PojoBuilder<ValidPojoWithSetMethods> wrapper = resolver.getWrapper(0x0003); ByteBuffer buffer = ByteBuffer.allocate(7); buffer.putInt(type); buffer.put(isok); buffer.putShort(length); ValidPojoWithSetMethods res = wrapper.make(buffer); Assert.assertEquals(isok, res.isok ); Assert.assertEquals(length, res.length ); Assert.assertEquals(type, res.type); } @Test public void test_unmarshallling_valid_pojo_with_skip_parameter_Expected_no_errors() throws InitException, MakeException, CallException{ ClassResolver resolver = (new ResolverInitialisator()).init("org.binarymarshaller.testutils.research.valid"); PojoBuilder<ValidPojoWithSkip> wrapper = resolver.getWrapper(0x0001); ByteBuffer buffer = ByteBuffer.allocate(11); buffer.putInt(type); buffer.put(isok); buffer.putShort(length); buffer.putInt(0xffffffff); ValidPojoWithSkip res = wrapper.make(buffer); Assert.assertEquals(isok, res.getIsok() ); Assert.assertEquals(length, res.getLength() ); Assert.assertEquals(type, res.getType()); } @Test public void test_mashalling_valid_pojo_Expected_no_errors() throws InitException, MakeException, CallException{ ClassResolver resolver = (new ResolverInitialisator()).init("org.binarymarshaller.testutils.research.valid"); PojoBuilder<ValidPojoClass> wrapper = resolver.getWrapper(0x0000); ValidPojoClass cls = new ValidPojoClass(); cls.setIsok(isok); cls.setLength(length); cls.setType(type); ByteBuffer buffer = ByteBuffer.allocate(7); buffer.putInt(type); buffer.put(isok); buffer.putShort(length); ByteBuffer res = wrapper.pack(cls); Assert.assertArrayEquals(buffer.array(), res.array()); } @Test public void test_marshalling_valid_pojo_with_get_methods_Expected_no_errors() throws InitException, MakeException, CallException{ ClassResolver resolver = (new ResolverInitialisator()).init("org.binarymarshaller.testutils.research.valid"); PojoBuilder<ValidPojoWithGetMethods> wrapper = resolver.getWrapper(0x0002); ValidPojoWithGetMethods cls = new ValidPojoWithGetMethods(type, isok, length); ByteBuffer buffer = ByteBuffer.allocate(7); buffer.putInt(type); buffer.put(isok); buffer.putShort(length); ByteBuffer res = wrapper.pack(cls); Assert.assertArrayEquals(buffer.array(), res.array()); } public void test_marshalling_valid_pojo_with_skip_Expected_no_errors() throws InitException, MakeException, CallException{ ClassResolver resolver = (new ResolverInitialisator()).init("org.binarymarshaller.testutils.research.valid"); PojoBuilder<ValidPojoWithSkip> wrapper = resolver.getWrapper(0x0001); ValidPojoWithSkip cls = new ValidPojoWithSkip(); cls.setIsok(isok); cls.setLength(length); cls.setType(type); ByteBuffer buffer = ByteBuffer.allocate(11); buffer.putInt(type); buffer.put(isok); buffer.putShort(length); buffer.putInt(0x00000000); ByteBuffer res = wrapper.pack(cls); Assert.assertArrayEquals(buffer.array(), res.array()); } }
5,521
0.686832
0.675964
138
39.007248
35.575291
151
false
false
0
0
0
0
0
0
0.782609
false
false
9
e6523c4b4fadeb081b26465794f879aaac38a62e
37,426,345,039,556
dfb5dffc516d1502b1891e3efac1bd57ab399527
/simplechat1/ClientGUI.java
dc28843c19dd5505e9fe1d265dfa10de1f8d04cd
[]
no_license
ctebbe/simplechat1
https://github.com/ctebbe/simplechat1
b0f95976bb6998f0ec8a0eccd77e74f2d8b0b99c
10e2e75127bcc6775137cd92edf261bf6d68a215
refs/heads/master
2016-08-11T14:55:39.456000
2013-04-23T01:11:44
2013-04-23T01:11:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.IOException; import common.ChatIF; import ocsf.client.ObservableClient; import client.ChatClient; /** * * @author caleb */ public class ClientGUI extends javax.swing.JFrame implements ChatIF { private static final long serialVersionUID = 1L; private javax.swing.JButton btnBlock; private javax.swing.JButton btnChannel; private javax.swing.JButton btnPvtMsg; private javax.swing.JButton btnSend; private javax.swing.JButton btnStatus; private javax.swing.JButton btnUnblock; private javax.swing.JButton btnDraw; private javax.swing.JComboBox cbStatus; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lblUserName; private javax.swing.JTextArea txtDisplay; private javax.swing.JTextField txtEditable; final public static int DEFAULT_PORT = 5555; ChatClient client; public ClientGUI(String host, int port, String loginid) { initLookAndFeel(); initComponents(loginid); try { ObservableClient oc = new ObservableClient(host, port); client = new ChatClient(host, port, this, loginid, oc); } catch (IOException exception) { System.out.println("Error: Can't setup connection!" + " Terminating client."); System.exit(1); } this.setVisible(true); } private void initLookAndFeel() { /* Set the Nimbus look and feel */ /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } } @Override public void display(String message) { txtDisplay.append(message+"\n"); txtDisplay.setCaretPosition(txtDisplay.getDocument().getLength()); // scroll to bottom of new text } private void initComponents(String loginid) { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); txtDisplay = new javax.swing.JTextArea(); jLabel1 = new javax.swing.JLabel(); lblUserName = new javax.swing.JLabel(); cbStatus = new javax.swing.JComboBox(); txtEditable = new javax.swing.JTextField(); btnSend = new javax.swing.JButton(); btnDraw = new javax.swing.JButton(); btnBlock = new javax.swing.JButton(); btnChannel = new javax.swing.JButton(); btnStatus = new javax.swing.JButton(); btnPvtMsg = new javax.swing.JButton(); btnUnblock = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); jPanel1.setBorder(new javax.swing.border.MatteBorder(null)); txtDisplay.setColumns(20); txtDisplay.setRows(5); jScrollPane1.setViewportView(txtDisplay); jLabel1.setText("Logged in as:"); lblUserName.setText(loginid); cbStatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "AVAILABLE", "NOT AVAILABLE" })); cbStatus.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbStatusActionPerformed(evt); } }); txtEditable.setText(""); btnSend.setText("Send"); btnSend.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSendActionPerformed(evt); } }); //TODO btnDraw.setText("Draw"); btnDraw.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDrawActionPerformed(evt); } }); btnBlock.setText("Block"); btnBlock.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnBlockActionPerformed(evt); } }); btnChannel.setText("Channel"); btnChannel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnChannelActionPerformed(evt); } }); btnStatus.setText("Status"); btnStatus.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnStatusActionPerformed(evt); } }); btnPvtMsg.setText("Pvt Msg"); btnPvtMsg.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPvtMsgActionPerformed(evt); } }); btnUnblock.setText("Unblock"); btnUnblock.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnUnblockActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lblUserName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(txtEditable, javax.swing.GroupLayout.PREFERRED_SIZE, 347, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnSend, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btnDraw) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnChannel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnBlock) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnUnblock) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnPvtMsg) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnStatus))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(lblUserName) .addComponent(cbStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSend) .addComponent(txtEditable)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnBlock) .addComponent(btnDraw) .addComponent(btnChannel) .addComponent(btnStatus) .addComponent(btnPvtMsg) .addComponent(btnUnblock)) .addContainerGap(37, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); } private void accept() { } private void send(String message) { client.handleMessageFromClientUI(message); txtEditable.setText(""); } private void btnSendActionPerformed(java.awt.event.ActionEvent evt) { send(txtEditable.getText()); } private void cbStatusActionPerformed(java.awt.event.ActionEvent evt) { if(cbStatus.getSelectedIndex() == 0) { send("#available"); } else { send("#notavailable"); } } private void btnDrawActionPerformed(java.awt.event.ActionEvent evt){ client.openDrawpad(); } private void btnChannelActionPerformed(java.awt.event.ActionEvent evt) { send("#channel " + txtEditable.getText()); } private void btnBlockActionPerformed(java.awt.event.ActionEvent evt) { send("#block " + txtEditable.getText()); } private void btnStatusActionPerformed(java.awt.event.ActionEvent evt) { send("#status " + txtEditable.getText()); } private void btnPvtMsgActionPerformed(java.awt.event.ActionEvent evt) { send("#private " + txtEditable.getText()); } private void btnUnblockActionPerformed(java.awt.event.ActionEvent evt) { send("#unblock " + txtEditable.getText()); } /** * @param args the command line arguments */ public static void main(String args[]) { String host = ""; String loginid = ""; int port = 0; // The port number try { loginid = args[0]; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ERROR - No login ID specified. Connection aborted"); System.exit(0); } try { host = args[1]; } catch (ArrayIndexOutOfBoundsException e) { host = "localhost"; } try { port = Integer.parseInt(args[2]); } catch (ArrayIndexOutOfBoundsException e) { port = DEFAULT_PORT; } ClientGUI chat = new ClientGUI(host, port, loginid); chat.accept(); // Wait for console data } }
UTF-8
Java
13,959
java
ClientGUI.java
Java
[ { "context": "ient;\nimport client.ChatClient;\n\n/**\n *\n * @author caleb\n */\npublic class ClientGUI extends javax.swing.JF", "end": 139, "score": 0.9994516372680664, "start": 134, "tag": "USERNAME", "value": "caleb" } ]
null
[]
import java.io.IOException; import common.ChatIF; import ocsf.client.ObservableClient; import client.ChatClient; /** * * @author caleb */ public class ClientGUI extends javax.swing.JFrame implements ChatIF { private static final long serialVersionUID = 1L; private javax.swing.JButton btnBlock; private javax.swing.JButton btnChannel; private javax.swing.JButton btnPvtMsg; private javax.swing.JButton btnSend; private javax.swing.JButton btnStatus; private javax.swing.JButton btnUnblock; private javax.swing.JButton btnDraw; private javax.swing.JComboBox cbStatus; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lblUserName; private javax.swing.JTextArea txtDisplay; private javax.swing.JTextField txtEditable; final public static int DEFAULT_PORT = 5555; ChatClient client; public ClientGUI(String host, int port, String loginid) { initLookAndFeel(); initComponents(loginid); try { ObservableClient oc = new ObservableClient(host, port); client = new ChatClient(host, port, this, loginid, oc); } catch (IOException exception) { System.out.println("Error: Can't setup connection!" + " Terminating client."); System.exit(1); } this.setVisible(true); } private void initLookAndFeel() { /* Set the Nimbus look and feel */ /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } } @Override public void display(String message) { txtDisplay.append(message+"\n"); txtDisplay.setCaretPosition(txtDisplay.getDocument().getLength()); // scroll to bottom of new text } private void initComponents(String loginid) { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); txtDisplay = new javax.swing.JTextArea(); jLabel1 = new javax.swing.JLabel(); lblUserName = new javax.swing.JLabel(); cbStatus = new javax.swing.JComboBox(); txtEditable = new javax.swing.JTextField(); btnSend = new javax.swing.JButton(); btnDraw = new javax.swing.JButton(); btnBlock = new javax.swing.JButton(); btnChannel = new javax.swing.JButton(); btnStatus = new javax.swing.JButton(); btnPvtMsg = new javax.swing.JButton(); btnUnblock = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); jPanel1.setBorder(new javax.swing.border.MatteBorder(null)); txtDisplay.setColumns(20); txtDisplay.setRows(5); jScrollPane1.setViewportView(txtDisplay); jLabel1.setText("Logged in as:"); lblUserName.setText(loginid); cbStatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "AVAILABLE", "NOT AVAILABLE" })); cbStatus.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbStatusActionPerformed(evt); } }); txtEditable.setText(""); btnSend.setText("Send"); btnSend.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSendActionPerformed(evt); } }); //TODO btnDraw.setText("Draw"); btnDraw.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDrawActionPerformed(evt); } }); btnBlock.setText("Block"); btnBlock.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnBlockActionPerformed(evt); } }); btnChannel.setText("Channel"); btnChannel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnChannelActionPerformed(evt); } }); btnStatus.setText("Status"); btnStatus.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnStatusActionPerformed(evt); } }); btnPvtMsg.setText("Pvt Msg"); btnPvtMsg.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPvtMsgActionPerformed(evt); } }); btnUnblock.setText("Unblock"); btnUnblock.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnUnblockActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lblUserName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(txtEditable, javax.swing.GroupLayout.PREFERRED_SIZE, 347, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnSend, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btnDraw) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnChannel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnBlock) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnUnblock) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnPvtMsg) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnStatus))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(lblUserName) .addComponent(cbStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSend) .addComponent(txtEditable)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnBlock) .addComponent(btnDraw) .addComponent(btnChannel) .addComponent(btnStatus) .addComponent(btnPvtMsg) .addComponent(btnUnblock)) .addContainerGap(37, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); } private void accept() { } private void send(String message) { client.handleMessageFromClientUI(message); txtEditable.setText(""); } private void btnSendActionPerformed(java.awt.event.ActionEvent evt) { send(txtEditable.getText()); } private void cbStatusActionPerformed(java.awt.event.ActionEvent evt) { if(cbStatus.getSelectedIndex() == 0) { send("#available"); } else { send("#notavailable"); } } private void btnDrawActionPerformed(java.awt.event.ActionEvent evt){ client.openDrawpad(); } private void btnChannelActionPerformed(java.awt.event.ActionEvent evt) { send("#channel " + txtEditable.getText()); } private void btnBlockActionPerformed(java.awt.event.ActionEvent evt) { send("#block " + txtEditable.getText()); } private void btnStatusActionPerformed(java.awt.event.ActionEvent evt) { send("#status " + txtEditable.getText()); } private void btnPvtMsgActionPerformed(java.awt.event.ActionEvent evt) { send("#private " + txtEditable.getText()); } private void btnUnblockActionPerformed(java.awt.event.ActionEvent evt) { send("#unblock " + txtEditable.getText()); } /** * @param args the command line arguments */ public static void main(String args[]) { String host = ""; String loginid = ""; int port = 0; // The port number try { loginid = args[0]; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ERROR - No login ID specified. Connection aborted"); System.exit(0); } try { host = args[1]; } catch (ArrayIndexOutOfBoundsException e) { host = "localhost"; } try { port = Integer.parseInt(args[2]); } catch (ArrayIndexOutOfBoundsException e) { port = DEFAULT_PORT; } ClientGUI chat = new ClientGUI(host, port, loginid); chat.accept(); // Wait for console data } }
13,959
0.614012
0.609069
323
42.216717
35.658722
178
false
false
0
0
0
0
0
0
0.897833
false
false
9
84d51c8a365f9f4b0907725f97492f84b953cecf
35,287,451,345,528
ef8b6e05b0604ad9ec8135140d277f34e6534b6b
/src/main/java/com/repository/ArticleData.java
99e341f106ba29dc7f5fa9c45c52c72f1f33f85a
[]
no_license
digital-consulting/graphql-undertow
https://github.com/digital-consulting/graphql-undertow
47f259f03795c533c24e5a02d9b4f5cc817320e7
c16d8431da685824313ae716dbd1d3f7363b7559
refs/heads/master
2020-09-26T18:48:10.215000
2020-03-24T08:38:44
2020-03-24T08:38:44
226,317,180
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.repository; import com.entities.ArticleEntity; import com.entities.AuthorEntity; import com.entities.CommentEntity; import java.time.LocalDate; import java.util.LinkedHashMap; import java.util.Map; import static java.util.Arrays.asList; public class ArticleData { private static ArticleEntity article1; private static ArticleEntity article2; private static ArticleEntity article3; private static AuthorEntity author1; private static AuthorEntity author2; private static CommentEntity comment1 = new CommentEntity( "1", "First comment", "Ion Popescu" ); private static CommentEntity comment2 = new CommentEntity( "2", "Second comment", "Gigel" ); private static CommentEntity comment3 = new CommentEntity( "3", "There are no comments yet.", "Admin" ); static { article1 = new ArticleEntity( "1", "Best Practices for REST API Error Handling", asList("Architecture", "REST"), "REST is a stateless architecture in which clients can access and manipulate resources on a server.", LocalDate.parse("2018-10-22"), LocalDate.parse("2019-01-11"), 3, "https://res.cloudinary.com/fittco/image/upload/w_1920,f_auto/ky8jdsfofdkpolpac2yw.jpg", asList(comment1) ); article2 = new ArticleEntity( "2", "Causes and Avoidance of java.lang.VerifyError", asList("Java", "JVM"), "In this tutorial, we'll look at the cause of java.lang.VerifyError errors and multiple ways to avoid it.", LocalDate.parse("2019-01-12"), LocalDate.parse("2019-11-18"), 2, "https://res.cloudinary.com/fittco/image/upload/w_1920,f_auto/ky8jdsfofdkpolpac2yw.jpg", asList(comment2) ); article3 = new ArticleEntity( "3", "A Guide to Java HashMap", asList("Java"), "Let's first look at what it means that HashMap is a map. " + "A map is a key-value mapping, which means that every key is mapped to exactly " + "one value and that we can use the key to retrieve the corresponding value from a map.", LocalDate.parse("2019-05-22"), LocalDate.parse("2019-11-18"), 4, "https://res.cloudinary.com/fittco/image/upload/w_1920,f_auto/ky8jdsfofdkpolpac2yw.jpg", asList(comment3) ); author1 = new AuthorEntity( "1", "Justin", "Albano", asList(article3, article2), asList("GitHub", "Twitter") ); author2 = new AuthorEntity( "2", "Michael", "Krimgen", asList(article1), asList("GitHub") ); article1.setAuthor(author2); article2.setAuthor(author1); article3.setAuthor(author1); } public static Map<String, ArticleEntity> articles = new LinkedHashMap<>(); public static Map<String, AuthorEntity> authors = new LinkedHashMap<>(); public static Map<String, CommentEntity> comments = new LinkedHashMap<>(); static { articles.put("1", article1); articles.put("2", article2); articles.put("3", article3); authors.put("1", author1); authors.put("2", author2); comments.put("1", comment1); comments.put("2", comment2); comments.put("3", comment3); } public static Object getArticleData(String key) { if (articles.get(key) != null) { return articles.get(key); } return null; } }
UTF-8
Java
3,976
java
ArticleData.java
Java
[ { "context": " \"1\",\n \"First comment\",\n \"Ion Popescu\"\n );\n\n private static CommentEntity comment", "end": 625, "score": 0.9998375177383423, "start": 614, "tag": "NAME", "value": "Ion Popescu" }, { "context": " \"2\",\n \"Second comment\",\n \"Gigel\"\n );\n\n private static CommentEntity comment", "end": 763, "score": 0.994371771812439, "start": 758, "tag": "NAME", "value": "Gigel" }, { "context": "thorEntity(\n \"1\",\n \"Justin\",\n \"Albano\",\n asLis", "end": 2814, "score": 0.9998146295547485, "start": 2808, "tag": "NAME", "value": "Justin" }, { "context": " \"1\",\n \"Justin\",\n \"Albano\",\n asList(article3, article2),\n ", "end": 2840, "score": 0.9998273849487305, "start": 2834, "tag": "NAME", "value": "Albano" }, { "context": "thorEntity(\n \"2\",\n \"Michael\",\n \"Krimgen\",\n asLi", "end": 3024, "score": 0.9998562932014465, "start": 3017, "tag": "NAME", "value": "Michael" }, { "context": " \"2\",\n \"Michael\",\n \"Krimgen\",\n asList(article1),\n ", "end": 3051, "score": 0.999772846698761, "start": 3044, "tag": "NAME", "value": "Krimgen" } ]
null
[]
package com.repository; import com.entities.ArticleEntity; import com.entities.AuthorEntity; import com.entities.CommentEntity; import java.time.LocalDate; import java.util.LinkedHashMap; import java.util.Map; import static java.util.Arrays.asList; public class ArticleData { private static ArticleEntity article1; private static ArticleEntity article2; private static ArticleEntity article3; private static AuthorEntity author1; private static AuthorEntity author2; private static CommentEntity comment1 = new CommentEntity( "1", "First comment", "<NAME>" ); private static CommentEntity comment2 = new CommentEntity( "2", "Second comment", "Gigel" ); private static CommentEntity comment3 = new CommentEntity( "3", "There are no comments yet.", "Admin" ); static { article1 = new ArticleEntity( "1", "Best Practices for REST API Error Handling", asList("Architecture", "REST"), "REST is a stateless architecture in which clients can access and manipulate resources on a server.", LocalDate.parse("2018-10-22"), LocalDate.parse("2019-01-11"), 3, "https://res.cloudinary.com/fittco/image/upload/w_1920,f_auto/ky8jdsfofdkpolpac2yw.jpg", asList(comment1) ); article2 = new ArticleEntity( "2", "Causes and Avoidance of java.lang.VerifyError", asList("Java", "JVM"), "In this tutorial, we'll look at the cause of java.lang.VerifyError errors and multiple ways to avoid it.", LocalDate.parse("2019-01-12"), LocalDate.parse("2019-11-18"), 2, "https://res.cloudinary.com/fittco/image/upload/w_1920,f_auto/ky8jdsfofdkpolpac2yw.jpg", asList(comment2) ); article3 = new ArticleEntity( "3", "A Guide to Java HashMap", asList("Java"), "Let's first look at what it means that HashMap is a map. " + "A map is a key-value mapping, which means that every key is mapped to exactly " + "one value and that we can use the key to retrieve the corresponding value from a map.", LocalDate.parse("2019-05-22"), LocalDate.parse("2019-11-18"), 4, "https://res.cloudinary.com/fittco/image/upload/w_1920,f_auto/ky8jdsfofdkpolpac2yw.jpg", asList(comment3) ); author1 = new AuthorEntity( "1", "Justin", "Albano", asList(article3, article2), asList("GitHub", "Twitter") ); author2 = new AuthorEntity( "2", "Michael", "Krimgen", asList(article1), asList("GitHub") ); article1.setAuthor(author2); article2.setAuthor(author1); article3.setAuthor(author1); } public static Map<String, ArticleEntity> articles = new LinkedHashMap<>(); public static Map<String, AuthorEntity> authors = new LinkedHashMap<>(); public static Map<String, CommentEntity> comments = new LinkedHashMap<>(); static { articles.put("1", article1); articles.put("2", article2); articles.put("3", article3); authors.put("1", author1); authors.put("2", author2); comments.put("1", comment1); comments.put("2", comment2); comments.put("3", comment3); } public static Object getArticleData(String key) { if (articles.get(key) != null) { return articles.get(key); } return null; } }
3,971
0.552817
0.523139
127
30.307087
27.350887
123
false
false
0
0
0
0
0
0
0.748031
false
false
9
1d01c1e44aedfdc87e9cb2b0c2374a70c9e3a6dd
34,789,235,138,576
24c95c3ecb4fc95a72da692d2da5a597810d36fa
/src/stringQuestions/stringPracTwo.java
0a0a1ad197a0b8e2dffcea2797ad963f5988c1b3
[]
no_license
umangsv/JavaSessions
https://github.com/umangsv/JavaSessions
f9898bf8c56980646ca19f44d948debf8442c86e
61799b1eacd2277607147eaa9b96be238b107f32
refs/heads/master
2020-12-26T09:57:56.913000
2020-02-01T06:27:36
2020-02-01T06:27:36
237,474,721
0
0
null
false
2020-02-01T06:27:37
2020-01-31T16:53:10
2020-01-31T16:54:35
2020-02-01T06:27:37
77
0
0
0
Java
false
false
package stringQuestions; public class stringPracTwo { public static void main(String[] args) { String abc = "TestingXperts"; String reverse = ""; for (int i = abc.length()-1 ; i >= 0; i--) { reverse = reverse + abc.charAt(i); } System.out.println("lets print the reversed string : " + reverse); } }
UTF-8
Java
334
java
stringPracTwo.java
Java
[ { "context": "tatic void main(String[] args) {\n\n\t\tString abc = \"TestingXperts\";\n\t\t\n\t\tString reverse = \"\";\n\t\t\n\t\tfor (int i = abc", "end": 128, "score": 0.7143039107322693, "start": 115, "tag": "USERNAME", "value": "TestingXperts" } ]
null
[]
package stringQuestions; public class stringPracTwo { public static void main(String[] args) { String abc = "TestingXperts"; String reverse = ""; for (int i = abc.length()-1 ; i >= 0; i--) { reverse = reverse + abc.charAt(i); } System.out.println("lets print the reversed string : " + reverse); } }
334
0.610778
0.60479
20
15.7
19.626768
68
false
false
0
0
0
0
0
0
1.65
false
false
9
8c3dddc4573c01012d5c6f1a46ed1431380ad833
14,714,558,025,061
819418d67358421b2c3b0826fa0cc409c0354f37
/huate-manage/src/main/java/com/wuguan/huate/bean/entity/Worker.java
293ee77d5b5b2c7f343accc08c71e1da0cb6fa23
[]
no_license
346058210/huate
https://github.com/346058210/huate
93761c1bc36bcc29819b5c77daa7d4eba8c1e0b3
815abb33390ffe02c82a4b66cca5e213e2ca0cc8
refs/heads/master
2022-06-26T07:23:15.791000
2020-05-12T13:47:28
2020-05-12T13:47:28
252,397,007
0
2
null
false
2022-06-21T03:07:19
2020-04-02T08:24:10
2020-05-12T13:47:54
2022-06-21T03:07:16
299
0
1
7
Java
false
false
/** * @Title: Worker.java * @Package com.wuguan.huate.bean.entity * @Description: TODO(用一句话描述该文件做什么) * @author LiuYanHong * @date 2020年3月17日 下午3:31:37 * @version V1.0 */ package com.wuguan.huate.bean.entity; import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * @ClassName: Worker * @Description: TODO(这里用一句话描述这个类的作用) * @author LiuYanHong * @date 2020年3月17日 下午3:31:37 * */ @Data @NoArgsConstructor @EqualsAndHashCode(callSuper = false) public class Worker implements Serializable { private static final long serialVersionUID = 1L; private Integer id; // private String name; //姓名 private String phone; //電話 private String address; //地址 private Integer isDel; //是否刪除 1 是 2 否 private String createTime; //註冊時間 private String updateTime; //修改時間 private String sex; //性別 private String birthDate; //出生日期 private String nickname; //暱稱 private String openid; //微信upenId private String password; //微信密码 private Integer isUse; //1 启用 0 禁用 private String tokenPc; //出生年月 private String tokenMobile; //出生年月 private Integer roleId; private Role role; }
UTF-8
Java
1,680
java
Worker.java
Java
[ { "context": "ity \n* @Description: TODO(用一句话描述该文件做什么) \n* @author LiuYanHong\n* @date 2020年3月17日 下午3:31:37 \n* @version V1.0 \n", "end": 127, "score": 0.9998674392700195, "start": 117, "tag": "NAME", "value": "LiuYanHong" }, { "context": "r \n* @Description: TODO(这里用一句话描述这个类的作用) \n* @author LiuYanHong\n* @date 2020年3月17日 下午3:31:37 \n* \n*/\n@Data\n@NoArg", "end": 421, "score": 0.9998790621757507, "start": 411, "tag": "NAME", "value": "LiuYanHong" }, { "context": "rivate String password; //微信密码\n\tprivate Integer isUse; /", "end": 1293, "score": 0.9778164029121399, "start": 1289, "tag": "PASSWORD", "value": "微信密码" } ]
null
[]
/** * @Title: Worker.java * @Package com.wuguan.huate.bean.entity * @Description: TODO(用一句话描述该文件做什么) * @author LiuYanHong * @date 2020年3月17日 下午3:31:37 * @version V1.0 */ package com.wuguan.huate.bean.entity; import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * @ClassName: Worker * @Description: TODO(这里用一句话描述这个类的作用) * @author LiuYanHong * @date 2020年3月17日 下午3:31:37 * */ @Data @NoArgsConstructor @EqualsAndHashCode(callSuper = false) public class Worker implements Serializable { private static final long serialVersionUID = 1L; private Integer id; // private String name; //姓名 private String phone; //電話 private String address; //地址 private Integer isDel; //是否刪除 1 是 2 否 private String createTime; //註冊時間 private String updateTime; //修改時間 private String sex; //性別 private String birthDate; //出生日期 private String nickname; //暱稱 private String openid; //微信upenId private String password; //<PASSWORD> private Integer isUse; //1 启用 0 禁用 private String tokenPc; //出生年月 private String tokenMobile; //出生年月 private Integer roleId; private Role role; }
1,678
0.560686
0.540237
47
31.25532
20.782017
63
false
false
0
0
0
0
0
0
0.87234
false
false
9
6d61ce1e1223efb64696daaa0230c85c912e258f
32,615,981,691,480
c9934da3d7f13ce46bf48102350d03f827f458b4
/src/main/java/tp/web/mbean/ProduitMBean.java
1934bee09944fb2bd361df4412f5332ae0411f8f
[]
no_license
didier-tp/ca-jsf2
https://github.com/didier-tp/ca-jsf2
607b139aa6d17d569b8bfc61bf35b2a6f95bf4f8
e92fc280103ca717b069aaa5a0dc70afb5b07df2
refs/heads/master
2020-07-11T03:54:10.360000
2019-08-28T14:45:03
2019-08-28T14:45:03
204,439,305
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tp.web.mbean; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.SessionScoped; import javax.faces.event.ValueChangeEvent; import tp.web.data.Produit; import tp.web.service.ServiceProduits; @ManagedBean @SessionScoped public class ProduitMBean { private List<String> categories; //liste de categorie (à choisir) private String categorie;//catégorie selectionnée private List<Produit> produits = new ArrayList<Produit>(); //liste des produits de la catégorie sélectionnée private Long idProduit; //id produit selectionné (avec get/Set) private Date date;//java.util.Date; (avec get/set) public List<String> completeCategorie(String cat){ List<String> suggestions = new ArrayList<String>(); for(String s : categories){ if(s.toLowerCase().startsWith(cat.toLowerCase())) suggestions.add(s); } return suggestions; } //appelé par commandButton de testPrimefaces.xhtml : public String recupChoix() { System.out.println("date choisie :" + date); System.out.println("categorie choisie :" + categorie); return null;//rester sur meme page } private Produit produit; //produit sélectionné à détailler //@Autowired @ManagedProperty("#{serviceProduits}") private ServiceProduits serviceProduits /*=null*/; public ProduitMBean(){ //this.categories = serviceProduits.getCategories(); System.out.println("dans constructeur de ProduitMBean , serviceProduits"+serviceProduits); } @PostConstruct public void init() { this.categories = serviceProduits.getCategories(); System.out.println("categories="+categories); } public void onCategorieChange(ValueChangeEvent event){ this.categorie = (String) event.getNewValue(); this.produits = serviceProduits.getProduitsCategorie(categorie); this.idProduit = null; this.produit = null; } public void onProduitChange(ValueChangeEvent event){ this.idProduit = (Long) event.getNewValue(); System.out.println("id produit selectionne:" + idProduit); for(Produit p : this.produits) { if(p.getNumero() == this.idProduit) { this.produit = p; break; } } //this.produit = (Produit) event.getNewValue(); //System.out.println("Produit selectionne:" + produit); } public List<String> getCategories() { return categories; } public void setCategories(List<String> categories) { this.categories = categories; } public String getCategorie() { return categorie; } public void setCategorie(String categorie) { this.categorie = categorie; } public List<Produit> getProduits() { return produits; } public void setProduits(List<Produit> produits) { this.produits = produits; } public Produit getProduit() { return produit; } public void setProduit(Produit produit) { this.produit = produit; } public ServiceProduits getServiceProduits() { return serviceProduits; } public void setServiceProduits(ServiceProduits serviceProduits) { this.serviceProduits = serviceProduits; } public Long getIdProduit() { return idProduit; } public void setIdProduit(Long idProduit) { this.idProduit = idProduit; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
UTF-8
Java
3,423
java
ProduitMBean.java
Java
[]
null
[]
package tp.web.mbean; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.SessionScoped; import javax.faces.event.ValueChangeEvent; import tp.web.data.Produit; import tp.web.service.ServiceProduits; @ManagedBean @SessionScoped public class ProduitMBean { private List<String> categories; //liste de categorie (à choisir) private String categorie;//catégorie selectionnée private List<Produit> produits = new ArrayList<Produit>(); //liste des produits de la catégorie sélectionnée private Long idProduit; //id produit selectionné (avec get/Set) private Date date;//java.util.Date; (avec get/set) public List<String> completeCategorie(String cat){ List<String> suggestions = new ArrayList<String>(); for(String s : categories){ if(s.toLowerCase().startsWith(cat.toLowerCase())) suggestions.add(s); } return suggestions; } //appelé par commandButton de testPrimefaces.xhtml : public String recupChoix() { System.out.println("date choisie :" + date); System.out.println("categorie choisie :" + categorie); return null;//rester sur meme page } private Produit produit; //produit sélectionné à détailler //@Autowired @ManagedProperty("#{serviceProduits}") private ServiceProduits serviceProduits /*=null*/; public ProduitMBean(){ //this.categories = serviceProduits.getCategories(); System.out.println("dans constructeur de ProduitMBean , serviceProduits"+serviceProduits); } @PostConstruct public void init() { this.categories = serviceProduits.getCategories(); System.out.println("categories="+categories); } public void onCategorieChange(ValueChangeEvent event){ this.categorie = (String) event.getNewValue(); this.produits = serviceProduits.getProduitsCategorie(categorie); this.idProduit = null; this.produit = null; } public void onProduitChange(ValueChangeEvent event){ this.idProduit = (Long) event.getNewValue(); System.out.println("id produit selectionne:" + idProduit); for(Produit p : this.produits) { if(p.getNumero() == this.idProduit) { this.produit = p; break; } } //this.produit = (Produit) event.getNewValue(); //System.out.println("Produit selectionne:" + produit); } public List<String> getCategories() { return categories; } public void setCategories(List<String> categories) { this.categories = categories; } public String getCategorie() { return categorie; } public void setCategorie(String categorie) { this.categorie = categorie; } public List<Produit> getProduits() { return produits; } public void setProduits(List<Produit> produits) { this.produits = produits; } public Produit getProduit() { return produit; } public void setProduit(Produit produit) { this.produit = produit; } public ServiceProduits getServiceProduits() { return serviceProduits; } public void setServiceProduits(ServiceProduits serviceProduits) { this.serviceProduits = serviceProduits; } public Long getIdProduit() { return idProduit; } public void setIdProduit(Long idProduit) { this.idProduit = idProduit; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
3,423
0.722662
0.722662
137
23.89781
22.954504
109
false
false
0
0
0
0
0
0
1.343066
false
false
9
9dfc6ec71e96af38a3ca1e383945d15390258b11
17,970,143,222,467
a26453212a2a41b96dbaa6286aecb05a377abcef
/gameServer/src/com/bw/application/action/UploadBattleResultAction.java
b9d23bf5d99f44b61d4f4132eab941ab0f9c0ca7
[]
no_license
dq-dq/bl-server
https://github.com/dq-dq/bl-server
959cf9b2541d46f9315ce5dbd948da1f37b1a18c
0dcb1bfc1108a136a236506e66ddedb437ee2683
refs/heads/master
2021-01-10T12:19:17.967000
2016-02-05T03:18:17
2016-02-05T03:18:17
51,122,776
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bw.application.action; import com.bw.application.manager.IBattleManager; import com.bw.application.message.UploadBattleResult.UploadBattleResultRequest; import com.bw.application.message.UploadBattleResult.UploadBattleResultResponse; import com.commonSocket.net.action.Action; import com.commonSocket.net.action.Request; import com.commonSocket.net.action.Response; public class UploadBattleResultAction implements Action { public IBattleManager battleManagerImpl; @Override public String execute(Request paramRequest, Response paramResponse) throws Exception { UploadBattleResultRequest request=UploadBattleResultRequest.parseFrom(paramRequest.getMessage()); UploadBattleResultResponse.Builder builder=UploadBattleResultResponse.newBuilder(); try { int result=battleManagerImpl.saveBattleResult(request); builder.setResult(result); } catch (Exception e) { e.printStackTrace(); builder.setResult(1); builder.setInfo(e.getMessage()); } finally { paramResponse.write(builder.build()); } return null; } public IBattleManager getBattleManagerImpl() { return battleManagerImpl; } public void setBattleManagerImpl(IBattleManager battleManagerImpl) { this.battleManagerImpl = battleManagerImpl; } }
UTF-8
Java
1,296
java
UploadBattleResultAction.java
Java
[]
null
[]
package com.bw.application.action; import com.bw.application.manager.IBattleManager; import com.bw.application.message.UploadBattleResult.UploadBattleResultRequest; import com.bw.application.message.UploadBattleResult.UploadBattleResultResponse; import com.commonSocket.net.action.Action; import com.commonSocket.net.action.Request; import com.commonSocket.net.action.Response; public class UploadBattleResultAction implements Action { public IBattleManager battleManagerImpl; @Override public String execute(Request paramRequest, Response paramResponse) throws Exception { UploadBattleResultRequest request=UploadBattleResultRequest.parseFrom(paramRequest.getMessage()); UploadBattleResultResponse.Builder builder=UploadBattleResultResponse.newBuilder(); try { int result=battleManagerImpl.saveBattleResult(request); builder.setResult(result); } catch (Exception e) { e.printStackTrace(); builder.setResult(1); builder.setInfo(e.getMessage()); } finally { paramResponse.write(builder.build()); } return null; } public IBattleManager getBattleManagerImpl() { return battleManagerImpl; } public void setBattleManagerImpl(IBattleManager battleManagerImpl) { this.battleManagerImpl = battleManagerImpl; } }
1,296
0.785494
0.784722
37
33.027027
27.272882
99
false
false
0
0
0
0
0
0
1.891892
false
false
9
40ab78f61ecf814ddf6fb64e89933caa3ac22759
17,970,143,220,747
075b5280a7daee0ddf50bc9d37f5167f0805a421
/src/Tree/RedBlackTree.java
236c644ec17e87ffb636debf80a3e59f0e4541d0
[]
no_license
errrror/Algorithms
https://github.com/errrror/Algorithms
224c00c4172b722807655810c5355e76f177044f
7c1a5ab83adab99d6640c9a157be67a45216f92f
refs/heads/master
2020-04-06T06:58:34.278000
2018-02-04T14:25:16
2018-02-04T14:25:16
56,747,199
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Tree; /** * Created by YGZ on 2016/4/26. * My email : errrrorer@foxmail.com */ /* * 红黑树是一棵二叉搜索树,它在每个节点上增加了一个存储位来表示节点的颜色,可以是RED或BLACK。 * 红黑树的性质: * 1、每个节点或者是红色的,或者是黑色的。 * 2、根节点是黑色的。 * 3、每个叶节点(NIL)是黑色的。 * 4、如果一个节点是红色的,则它的两个子节点都是黑色的。 * 5、对每个节点,从该节点到其所有后代叶节点的简单路径上,均包含相同数目的黑色节点。*/ public class RedBlackTree { public static void leftRotate(TreeNode T,TreeNode x){ TreeNode y = x.right; x.right = y.left; if (y.left!=null){ y.left.parent = x; } y.parent = x.parent; if (x.parent == T){ T = y; }else if (x == x.parent.left){ x.parent.left = y; }else { x.parent.right = y; } y.left = x; x.parent = y; } public static void rightRotate(TreeNode T,TreeNode x){ TreeNode y = x.parent; y.left = x.right; if (x.right!=null){ x.right.parent = y; } if (T==y){ x = T; }else if (y == y.parent.left){ y.parent.left = x; }else { y.parent.right = x; } x.parent = y.parent; x.right = y; } }
UTF-8
Java
1,471
java
RedBlackTree.java
Java
[ { "context": "package Tree;\n\n/**\n * Created by YGZ on 2016/4/26.\n * My email : errrrorer@foxmail.com", "end": 36, "score": 0.9985809326171875, "start": 33, "tag": "USERNAME", "value": "YGZ" }, { "context": "\n/**\n * Created by YGZ on 2016/4/26.\n * My email : errrrorer@foxmail.com\n */\n\n/*\n* 红黑树是一棵二叉搜索树,它在每个节点上增加了一个存储位来表示节点的颜色,可以是", "end": 86, "score": 0.9999293088912964, "start": 65, "tag": "EMAIL", "value": "errrrorer@foxmail.com" } ]
null
[]
package Tree; /** * Created by YGZ on 2016/4/26. * My email : <EMAIL> */ /* * 红黑树是一棵二叉搜索树,它在每个节点上增加了一个存储位来表示节点的颜色,可以是RED或BLACK。 * 红黑树的性质: * 1、每个节点或者是红色的,或者是黑色的。 * 2、根节点是黑色的。 * 3、每个叶节点(NIL)是黑色的。 * 4、如果一个节点是红色的,则它的两个子节点都是黑色的。 * 5、对每个节点,从该节点到其所有后代叶节点的简单路径上,均包含相同数目的黑色节点。*/ public class RedBlackTree { public static void leftRotate(TreeNode T,TreeNode x){ TreeNode y = x.right; x.right = y.left; if (y.left!=null){ y.left.parent = x; } y.parent = x.parent; if (x.parent == T){ T = y; }else if (x == x.parent.left){ x.parent.left = y; }else { x.parent.right = y; } y.left = x; x.parent = y; } public static void rightRotate(TreeNode T,TreeNode x){ TreeNode y = x.parent; y.left = x.right; if (x.right!=null){ x.right.parent = y; } if (T==y){ x = T; }else if (y == y.parent.left){ y.parent.left = x; }else { y.parent.right = x; } x.parent = y.parent; x.right = y; } }
1,457
0.502153
0.491817
50
22.219999
13.951759
58
false
false
0
0
0
0
0
0
0.4
false
false
9
13671fe12361e8100ce6435831b098ad8c065ee7
10,299,331,632,721
633ac65158309f1578ae637a4ec640fcb68544f0
/spring-boot-microservices-saga-choreography/payment-service/src/main/java/com/franktran/paymentservice/service/PaymentService.java
84da637c8e4135ff868c963da8b293928c63a365
[]
no_license
franktranvantu/spring-boot
https://github.com/franktranvantu/spring-boot
c78df3116c658c201e2655332d97e2c915572db4
00c25eab59fe2945449644fd972fb3b95443d85e
refs/heads/master
2021-07-08T03:40:29.080000
2021-05-14T10:29:40
2021-05-14T10:29:40
241,910,724
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.franktran.paymentservice.service; import com.franktran.commondto.dto.OrderDto; import com.franktran.commondto.dto.PaymentDto; import com.franktran.commondto.event.order.OrderEvent; import com.franktran.commondto.event.payment.PaymentEvent; import com.franktran.commondto.event.payment.PaymentStatus; import com.franktran.paymentservice.entity.UserTransaction; import com.franktran.paymentservice.repository.UserBalanceRepository; import com.franktran.paymentservice.repository.UserTransactionRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class PaymentService { private final UserBalanceRepository userBalanceRepository; private final UserTransactionRepository userTransactionRepository; public PaymentService(UserBalanceRepository userBalanceRepository, UserTransactionRepository userTransactionRepository) { this.userBalanceRepository = userBalanceRepository; this.userTransactionRepository = userTransactionRepository; } @Transactional public PaymentEvent newOrderEvent(OrderEvent orderEvent) { OrderDto order = orderEvent.getOrder(); PaymentDto paymentDto = PaymentDto.of(order.getOrderId(), order.getUserId(), order.getPrice()); return userBalanceRepository.findById(order.getUserId()) .filter(userBalance -> userBalance.getBalance() >= order.getPrice()) .map(userBalance -> { userBalance.setBalance(userBalance.getBalance() - order.getPrice()); userTransactionRepository.save(UserTransaction.of(order.getOrderId(), order.getUserId(), order.getPrice())); return new PaymentEvent(paymentDto, PaymentStatus.RESERVED); }) .orElse(new PaymentEvent(paymentDto, PaymentStatus.REJECTED)); } @Transactional public void cancelOrderEvent(OrderEvent orderEvent) { userTransactionRepository.findById(orderEvent.getEventId()) .ifPresent(userTransaction -> { userTransactionRepository.delete(userTransaction); userBalanceRepository.findById(userTransaction.getUserId()) .ifPresent(userBalance -> userBalance.setBalance(userBalance.getBalance() + userTransaction.getAmount())); }); } }
UTF-8
Java
2,243
java
PaymentService.java
Java
[]
null
[]
package com.franktran.paymentservice.service; import com.franktran.commondto.dto.OrderDto; import com.franktran.commondto.dto.PaymentDto; import com.franktran.commondto.event.order.OrderEvent; import com.franktran.commondto.event.payment.PaymentEvent; import com.franktran.commondto.event.payment.PaymentStatus; import com.franktran.paymentservice.entity.UserTransaction; import com.franktran.paymentservice.repository.UserBalanceRepository; import com.franktran.paymentservice.repository.UserTransactionRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class PaymentService { private final UserBalanceRepository userBalanceRepository; private final UserTransactionRepository userTransactionRepository; public PaymentService(UserBalanceRepository userBalanceRepository, UserTransactionRepository userTransactionRepository) { this.userBalanceRepository = userBalanceRepository; this.userTransactionRepository = userTransactionRepository; } @Transactional public PaymentEvent newOrderEvent(OrderEvent orderEvent) { OrderDto order = orderEvent.getOrder(); PaymentDto paymentDto = PaymentDto.of(order.getOrderId(), order.getUserId(), order.getPrice()); return userBalanceRepository.findById(order.getUserId()) .filter(userBalance -> userBalance.getBalance() >= order.getPrice()) .map(userBalance -> { userBalance.setBalance(userBalance.getBalance() - order.getPrice()); userTransactionRepository.save(UserTransaction.of(order.getOrderId(), order.getUserId(), order.getPrice())); return new PaymentEvent(paymentDto, PaymentStatus.RESERVED); }) .orElse(new PaymentEvent(paymentDto, PaymentStatus.REJECTED)); } @Transactional public void cancelOrderEvent(OrderEvent orderEvent) { userTransactionRepository.findById(orderEvent.getEventId()) .ifPresent(userTransaction -> { userTransactionRepository.delete(userTransaction); userBalanceRepository.findById(userTransaction.getUserId()) .ifPresent(userBalance -> userBalance.setBalance(userBalance.getBalance() + userTransaction.getAmount())); }); } }
2,243
0.785109
0.785109
48
45.729168
33.4818
123
false
false
0
0
0
0
0
0
0.645833
false
false
9
8297f7146cc357031f724e034f8dd6204a7243f8
16,664,473,175,800
562a9d996a449bbe97c159fbfbdbcc1462209f00
/app/src/main/java/com/mobiotic/videoplay/demo/main_activity/MainPresenterImpl.java
80cf00d17ff9adf181e59805626b9e64d120e4c2
[]
no_license
krdhiraj03/VideoMobiotics
https://github.com/krdhiraj03/VideoMobiotics
3aa44df8dec0a9fc2167dd7be8937f01e84ff3a4
84f06400cb96baaea8db2b31b2f1251f5ce27a78
refs/heads/master
2022-08-26T08:03:15.550000
2022-08-16T17:12:08
2022-08-16T17:12:08
163,415,055
0
0
null
false
2022-08-16T17:17:03
2018-12-28T13:45:21
2022-08-16T17:03:02
2022-08-16T17:12:08
6,122
0
0
1
Java
false
false
package com.mobiotic.videoplay.demo.main_activity; import com.mobiotic.videoplay.demo.model.VideosListModel; import java.util.List; public class MainPresenterImpl implements MainContract.presenter, MainContract.videoIntractor.OnFinishedListener { private MainContract.MainView mainView; private MainContract.videoIntractor getVideoIntractor; public MainPresenterImpl(MainContract.MainView mainView, MainContract.videoIntractor getNoticeIntractor) { this.mainView = mainView; this.getVideoIntractor = getNoticeIntractor; } @Override public void onDestroy() { mainView = null; } @Override public void onRefreshButtonClick() { if(mainView != null){ mainView.showProgress(); } getVideoIntractor.getVideoArrayList(this); } @Override public void requestDataFromServer() { getVideoIntractor.getVideoArrayList(this); } @Override public void onFinished(List<VideosListModel> noticeArrayList) { if(mainView != null){ mainView.setDataToRecyclerView(noticeArrayList); mainView.hideProgress(); } } @Override public void onFailure(Throwable t) { if(mainView != null){ mainView.onResponseFailure(t); mainView.hideProgress(); } } }
UTF-8
Java
1,356
java
MainPresenterImpl.java
Java
[]
null
[]
package com.mobiotic.videoplay.demo.main_activity; import com.mobiotic.videoplay.demo.model.VideosListModel; import java.util.List; public class MainPresenterImpl implements MainContract.presenter, MainContract.videoIntractor.OnFinishedListener { private MainContract.MainView mainView; private MainContract.videoIntractor getVideoIntractor; public MainPresenterImpl(MainContract.MainView mainView, MainContract.videoIntractor getNoticeIntractor) { this.mainView = mainView; this.getVideoIntractor = getNoticeIntractor; } @Override public void onDestroy() { mainView = null; } @Override public void onRefreshButtonClick() { if(mainView != null){ mainView.showProgress(); } getVideoIntractor.getVideoArrayList(this); } @Override public void requestDataFromServer() { getVideoIntractor.getVideoArrayList(this); } @Override public void onFinished(List<VideosListModel> noticeArrayList) { if(mainView != null){ mainView.setDataToRecyclerView(noticeArrayList); mainView.hideProgress(); } } @Override public void onFailure(Throwable t) { if(mainView != null){ mainView.onResponseFailure(t); mainView.hideProgress(); } } }
1,356
0.675516
0.675516
56
23.214285
26.375526
114
false
false
0
0
0
0
0
0
0.303571
false
false
9
2d28ce8a17053e19075599c55d5f8ff6a4f343b3
26,156,350,835,180
2b7671d9c10e83f5d8804791e8c54d6c89dfa7d0
/custSuptMaven/src/main/java/com/prod/custSuptMaven/site/repositories/TicketRepositoryImpl.java
8eab984395ca53f27d5b4ad7286a5cc975285997
[]
no_license
sgf14/custSuptMaven
https://github.com/sgf14/custSuptMaven
de8d91fe79fe70f22cb097b9727c39b9ceca246a
751db82a415beaac155034ead1fcffbd6ab1acf1
refs/heads/master
2020-04-12T09:32:18.308000
2017-03-07T00:12:27
2017-03-07T00:12:27
63,117,464
0
0
null
false
2017-03-07T00:12:28
2016-07-12T02:08:57
2016-07-17T19:48:35
2017-03-07T00:12:27
167
0
0
0
Java
null
null
package com.prod.custSuptMaven.site.repositories; /*class notes- chap 23, pg 681. implementation of full text search criteria * w/ custom SQL script. looks for matches in both ticket and ticketComment. * returns total count, matches themselves w/ relevance score, in a pageable format * as directed by .jsp ui script * */ import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import com.prod.custSuptMaven.site.entities.Ticket; public class TicketRepositoryImpl implements SearchableRepository<Ticket> { //using TicketEntity as base for entityManager in this case @PersistenceContext EntityManager entityManager; @Override public Page<SearchResult<Ticket>> search(String query, boolean useBooleanMode, Pageable pageable) { //vars for use in methods- custom SQL script via TicketEntity SqlResultSetMapping annotation //note use of compact if/then/else since there are only two choices /* MySql boolean mode. in FULLTEXT search multi element text string entry here are some of the common functions: * 1) + = AND * 2) - = NOT * 3) [no symbol] = implied OR * 4) * = wildcard. at end of text. in manuals may be referred to as Truncation character * 5) it inlcude STOPWORDS function. see Mysql manual (google search on 'mysql in boolean mode') * * there is a UI checkbox for this. it really isnt described in JWA book, above is based on web search. * note there isnt a description of wildcard characters, and entry of partial text strings * dont return any results. if has to be the full word separated by space characters * this is not the way a typical google search works, where partial strings do produce results * a little more research needed on this. it may be that FULLTEXT searches in MySQL dont really * work this way, that it is intended to bring back matching full words. */ String mode = useBooleanMode ? "IN BOOLEAN MODE" : "IN NATURAL LANGUAGE MODE"; String matchTicket = "MATCH(t.subject, t.body) AGAINST(?1 " + mode + ")"; String matchComment = "MATCH(c.body) AGAINST(?1 " + mode + ")"; //total count of matches- in either table (using outer join) long total = ((Number)this.entityManager.createNativeQuery( "SELECT COUNT(DISTINCT t.TicketId) FROM Ticket t " + "LEFT OUTER JOIN TicketComment c ON c.TicketId = "+ "t.TicketId WHERE " + matchTicket + " OR " + matchComment ).setParameter(1, query).getSingleResult()).longValue(); //list the results in pageable format @SuppressWarnings("unchecked") List<Object[]> results = this.entityManager.createNativeQuery( "SELECT DISTINCT t.*, (" + matchTicket + " + " + matchComment + ") AS _ft_scoreColumn " + "FROM Ticket t LEFT OUTER JOIN TicketComment c " + "ON c.TicketId = t.TicketId "+ "WHERE " + matchTicket + " OR " + matchComment + " " + "ORDER BY _ft_scoreColumn DESC, TicketId DESC", "searchResultMapping.ticket" ).setParameter(1, query) .setFirstResult(pageable.getOffset()) .setMaxResults(pageable.getPageSize()) .getResultList(); //Object var results cast to Array list via lambda expression. see pg 682. result 1st, relevance 2nd //(zero based array = 0,1) List<SearchResult<Ticket>> list = new ArrayList<>(); results.forEach(o -> list.add( new SearchResult<>((Ticket)o[0], (Double)o[1]) )); return new PageImpl<>(list, pageable, total); } }
UTF-8
Java
3,730
java
TicketRepositoryImpl.java
Java
[]
null
[]
package com.prod.custSuptMaven.site.repositories; /*class notes- chap 23, pg 681. implementation of full text search criteria * w/ custom SQL script. looks for matches in both ticket and ticketComment. * returns total count, matches themselves w/ relevance score, in a pageable format * as directed by .jsp ui script * */ import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import com.prod.custSuptMaven.site.entities.Ticket; public class TicketRepositoryImpl implements SearchableRepository<Ticket> { //using TicketEntity as base for entityManager in this case @PersistenceContext EntityManager entityManager; @Override public Page<SearchResult<Ticket>> search(String query, boolean useBooleanMode, Pageable pageable) { //vars for use in methods- custom SQL script via TicketEntity SqlResultSetMapping annotation //note use of compact if/then/else since there are only two choices /* MySql boolean mode. in FULLTEXT search multi element text string entry here are some of the common functions: * 1) + = AND * 2) - = NOT * 3) [no symbol] = implied OR * 4) * = wildcard. at end of text. in manuals may be referred to as Truncation character * 5) it inlcude STOPWORDS function. see Mysql manual (google search on 'mysql in boolean mode') * * there is a UI checkbox for this. it really isnt described in JWA book, above is based on web search. * note there isnt a description of wildcard characters, and entry of partial text strings * dont return any results. if has to be the full word separated by space characters * this is not the way a typical google search works, where partial strings do produce results * a little more research needed on this. it may be that FULLTEXT searches in MySQL dont really * work this way, that it is intended to bring back matching full words. */ String mode = useBooleanMode ? "IN BOOLEAN MODE" : "IN NATURAL LANGUAGE MODE"; String matchTicket = "MATCH(t.subject, t.body) AGAINST(?1 " + mode + ")"; String matchComment = "MATCH(c.body) AGAINST(?1 " + mode + ")"; //total count of matches- in either table (using outer join) long total = ((Number)this.entityManager.createNativeQuery( "SELECT COUNT(DISTINCT t.TicketId) FROM Ticket t " + "LEFT OUTER JOIN TicketComment c ON c.TicketId = "+ "t.TicketId WHERE " + matchTicket + " OR " + matchComment ).setParameter(1, query).getSingleResult()).longValue(); //list the results in pageable format @SuppressWarnings("unchecked") List<Object[]> results = this.entityManager.createNativeQuery( "SELECT DISTINCT t.*, (" + matchTicket + " + " + matchComment + ") AS _ft_scoreColumn " + "FROM Ticket t LEFT OUTER JOIN TicketComment c " + "ON c.TicketId = t.TicketId "+ "WHERE " + matchTicket + " OR " + matchComment + " " + "ORDER BY _ft_scoreColumn DESC, TicketId DESC", "searchResultMapping.ticket" ).setParameter(1, query) .setFirstResult(pageable.getOffset()) .setMaxResults(pageable.getPageSize()) .getResultList(); //Object var results cast to Array list via lambda expression. see pg 682. result 1st, relevance 2nd //(zero based array = 0,1) List<SearchResult<Ticket>> list = new ArrayList<>(); results.forEach(o -> list.add( new SearchResult<>((Ticket)o[0], (Double)o[1]) )); return new PageImpl<>(list, pageable, total); } }
3,730
0.699464
0.693298
81
44.049381
31.475996
115
false
false
0
0
0
0
0
0
2.580247
false
false
9
cc0e6a99e8e1613bae90cd09d99be018b7b256cc
13,975,823,646,753
badeddf34a28b6b019c38a3c1ceb0eb97446d56b
/app/src/main/java/com/app/tigerpay/Adapter/ServicesAdapter.java
6faa4c35c9ee977a125848dc20f38c78cee6b5f2
[]
no_license
ravinakapila55/bok
https://github.com/ravinakapila55/bok
1f1250c3f4a8e54bd12b860554fe6152d783b1ee
71b954e387737082725a875329aca4e975ecc215
refs/heads/master
2023-04-26T03:12:32.443000
2021-05-23T12:45:21
2021-05-23T12:45:21
370,022,714
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.app.tigerpay.Adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.app.tigerpay.Model.ServiceModel; import com.app.tigerpay.R; import java.util.ArrayList; public class ServicesAdapter extends RecyclerView.Adapter<ServicesAdapter.MyViewHolder> { Context context; ArrayList<ServiceModel> list; public ServicesAdapter(Context context, ArrayList<ServiceModel> list) { this.context = context; this.list = list; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.custom_service,viewGroup,false); return new ServicesAdapter.MyViewHolder(view); } @Override public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) { myViewHolder.tvService.setText(list.get(i).getName()); if (i==0) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.mobile_recharge)); } if (i==1) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.dth)); } if (i==2) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.electricity)); } if (i==3) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.credidcard)); } if (i==4) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.postpaid)); } if (i==5) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.donate_something)); } if (i==6) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.book_cylinder)); } if (i==7) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.broadband)); } if (i==8) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.landline)); } if (i==9) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.waterbill)); } } @Override public int getItemCount() { return list.size() ; } public class MyViewHolder extends RecyclerView.ViewHolder { ImageView ivService; TextView tvService; public MyViewHolder(@NonNull View itemView) { super(itemView); ivService=(ImageView)itemView.findViewById(R.id.ivService); tvService=(TextView) itemView.findViewById(R.id.tvService); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listner.onItemClick(getAdapterPosition(),v); } }); } } onCLickListner listner; public void onItemSelectedListener(onCLickListner cLickListner) { this.listner=cLickListner; } public interface onCLickListner{ public void onItemClick(int layoutPosition,View view); } }
UTF-8
Java
3,531
java
ServicesAdapter.java
Java
[]
null
[]
package com.app.tigerpay.Adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.app.tigerpay.Model.ServiceModel; import com.app.tigerpay.R; import java.util.ArrayList; public class ServicesAdapter extends RecyclerView.Adapter<ServicesAdapter.MyViewHolder> { Context context; ArrayList<ServiceModel> list; public ServicesAdapter(Context context, ArrayList<ServiceModel> list) { this.context = context; this.list = list; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.custom_service,viewGroup,false); return new ServicesAdapter.MyViewHolder(view); } @Override public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) { myViewHolder.tvService.setText(list.get(i).getName()); if (i==0) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.mobile_recharge)); } if (i==1) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.dth)); } if (i==2) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.electricity)); } if (i==3) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.credidcard)); } if (i==4) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.postpaid)); } if (i==5) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.donate_something)); } if (i==6) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.book_cylinder)); } if (i==7) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.broadband)); } if (i==8) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.landline)); } if (i==9) { myViewHolder.ivService.setImageDrawable(context.getResources().getDrawable(R.drawable.waterbill)); } } @Override public int getItemCount() { return list.size() ; } public class MyViewHolder extends RecyclerView.ViewHolder { ImageView ivService; TextView tvService; public MyViewHolder(@NonNull View itemView) { super(itemView); ivService=(ImageView)itemView.findViewById(R.id.ivService); tvService=(TextView) itemView.findViewById(R.id.tvService); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listner.onItemClick(getAdapterPosition(),v); } }); } } onCLickListner listner; public void onItemSelectedListener(onCLickListner cLickListner) { this.listner=cLickListner; } public interface onCLickListner{ public void onItemClick(int layoutPosition,View view); } }
3,531
0.663268
0.660153
109
31.394495
34.230469
117
false
false
0
0
0
0
0
0
0.431193
false
false
9
0d27152aaba77b13e232f6ff07a7f0e198102553
8,976,481,714,878
b9f8fd6a51b91a2abb8bbb18ecdf3c89589508fc
/src/main/java/dycmaster/rysiek/triggers2/IInputTrigger.java
43c9c48864535d40eeb4bc2a7a319b83b96b3d6f
[]
no_license
fredmajor/rysiek
https://github.com/fredmajor/rysiek
46de3363ca60ca9491e55a8bb47f3d0c82c5314f
35ee50fb1168eef4b8bb99f806f9489779f772fb
refs/heads/master
2021-05-28T00:09:14.025000
2014-09-21T18:20:50
2014-09-21T18:20:50
16,852,027
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dycmaster.rysiek.triggers2; /** * Created by frs on 7/19/14. */ public interface IInputTrigger { void setInputState(String inputName, boolean state); void setInputState(int inputNumber, boolean state); }
UTF-8
Java
224
java
IInputTrigger.java
Java
[ { "context": "age dycmaster.rysiek.triggers2;\n\n/**\n * Created by frs on 7/19/14.\n */\npublic interface IInputTrigger {\n", "end": 58, "score": 0.9995937347412109, "start": 55, "tag": "USERNAME", "value": "frs" } ]
null
[]
package dycmaster.rysiek.triggers2; /** * Created by frs on 7/19/14. */ public interface IInputTrigger { void setInputState(String inputName, boolean state); void setInputState(int inputNumber, boolean state); }
224
0.736607
0.709821
10
21.4
21.657331
56
false
false
0
0
0
0
0
0
0.5
false
false
9
12b2434e74596a453e454075efd8befab4bf39d3
27,977,417,018,995
992212c75d44c039879bb1f2b7b2196c9cd87624
/src/java/smallGroup/P1_SumOfDoubleFromStr.java
8328d85e486f5bf4297567cfbb377531ae76fc46
[]
no_license
NozaM8/G11
https://github.com/NozaM8/G11
f41997d8c58c51e6eefbc375831314c31768e76f
e216264eb6e7dd1f9186685da471d53092c4d6f2
refs/heads/master
2022-12-11T06:55:22.497000
2020-09-04T00:48:09
2020-09-04T00:48:09
284,342,802
0
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package java.smallGroup; import java.text.DecimalFormat; public class P1_SumOfDoubleFromStr { public static void main(String[] args) { String str = "aaa1.1bbb2.2ccc4.4fff1.5"; // 9.20 String temp = ""; // 12.4 double sum = 0; for (int i=0; i<str.length(); i++){ if (Character.isDigit(str.charAt(i))){ temp += str.charAt(i); } if (str.charAt(i)=='.'){ temp += str.charAt(i); } if (Character.isDigit(str.charAt(i))) { if (!temp.equals("")){ sum += Double.parseDouble(temp); temp = ""; } } } DecimalFormat df = new DecimalFormat("0.00"); System.out.println(df.format(sum)); } }
UTF-8
Java
796
java
P1_SumOfDoubleFromStr.java
Java
[]
null
[]
package java.smallGroup; import java.text.DecimalFormat; public class P1_SumOfDoubleFromStr { public static void main(String[] args) { String str = "aaa1.1bbb2.2ccc4.4fff1.5"; // 9.20 String temp = ""; // 12.4 double sum = 0; for (int i=0; i<str.length(); i++){ if (Character.isDigit(str.charAt(i))){ temp += str.charAt(i); } if (str.charAt(i)=='.'){ temp += str.charAt(i); } if (Character.isDigit(str.charAt(i))) { if (!temp.equals("")){ sum += Double.parseDouble(temp); temp = ""; } } } DecimalFormat df = new DecimalFormat("0.00"); System.out.println(df.format(sum)); } }
796
0.477387
0.452261
27
28.481482
18.752522
57
false
false
0
0
0
0
0
0
0.481481
false
false
9
2984b922b815c0fa6312b531ff5d87336908f4cc
25,718,264,179,190
18e2eae3fb8d937ee6a6df30c3ccd97f328e84d3
/generatorSqlmapCustom/src/com/eshop/mapper/EshopOrderItemMapper.java
dfabcbba088eacd760a0988b62f00f938b356052
[]
no_license
JorgenPan/generatorSqlmapCustom
https://github.com/JorgenPan/generatorSqlmapCustom
7f77e37624100dc9232305f1fcc25afb3771cf41
0e86f1d096346a1d1cf3abc6b3fc3a3b8752970c
refs/heads/master
2020-03-31T15:53:00.950000
2018-10-10T03:18:07
2018-10-10T03:18:07
152,354,961
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.eshop.mapper; import com.eshop.pojo.EshopOrderItem; import com.eshop.pojo.EshopOrderItemExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface EshopOrderItemMapper { int countByExample(EshopOrderItemExample example); int deleteByExample(EshopOrderItemExample example); int deleteByPrimaryKey(String id); int insert(EshopOrderItem record); int insertSelective(EshopOrderItem record); List<EshopOrderItem> selectByExample(EshopOrderItemExample example); EshopOrderItem selectByPrimaryKey(String id); int updateByExampleSelective(@Param("record") EshopOrderItem record, @Param("example") EshopOrderItemExample example); int updateByExample(@Param("record") EshopOrderItem record, @Param("example") EshopOrderItemExample example); int updateByPrimaryKeySelective(EshopOrderItem record); int updateByPrimaryKey(EshopOrderItem record); }
UTF-8
Java
937
java
EshopOrderItemMapper.java
Java
[]
null
[]
package com.eshop.mapper; import com.eshop.pojo.EshopOrderItem; import com.eshop.pojo.EshopOrderItemExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface EshopOrderItemMapper { int countByExample(EshopOrderItemExample example); int deleteByExample(EshopOrderItemExample example); int deleteByPrimaryKey(String id); int insert(EshopOrderItem record); int insertSelective(EshopOrderItem record); List<EshopOrderItem> selectByExample(EshopOrderItemExample example); EshopOrderItem selectByPrimaryKey(String id); int updateByExampleSelective(@Param("record") EshopOrderItem record, @Param("example") EshopOrderItemExample example); int updateByExample(@Param("record") EshopOrderItem record, @Param("example") EshopOrderItemExample example); int updateByPrimaryKeySelective(EshopOrderItem record); int updateByPrimaryKey(EshopOrderItem record); }
937
0.798292
0.798292
30
30.266666
32.944328
122
false
false
0
0
0
0
0
0
0.6
false
false
9
790ea7d319c2bf09ef0b004535d63324c84ab724
7,911,329,761,572
e98d1862f614c0945d0d2556b6324a708b4bd811
/Hush b4/org/lwjgl/util/vector/Vector.java
8b4daea4279602ef67ce6635bb5eb4ce690cb782
[]
no_license
chocopie69/Minecraft-Modifications-Codes
https://github.com/chocopie69/Minecraft-Modifications-Codes
946f7fd2b431b1e3c4272cf96d75460883468917
a843aa9163e9e508e74dad10572d68477e5e38bf
refs/heads/main
2023-08-27T08:46:06.036000
2022-06-25T14:35:06
2022-06-25T14:35:06
412,120,508
71
54
null
false
2022-01-11T15:55:25
2021-09-30T15:30:35
2022-01-10T04:52:49
2022-01-09T16:44:51
331,436
4
2
3
null
false
false
// // Decompiled by Procyon v0.5.36 // package org.lwjgl.util.vector; import java.nio.FloatBuffer; import java.io.Serializable; public abstract class Vector implements Serializable, ReadableVector { protected Vector() { } public final float length() { return (float)Math.sqrt(this.lengthSquared()); } public abstract float lengthSquared(); public abstract Vector load(final FloatBuffer p0); public abstract Vector negate(); public final Vector normalise() { final float len = this.length(); if (len != 0.0f) { final float l = 1.0f / len; return this.scale(l); } throw new IllegalStateException("Zero length vector"); } public abstract Vector store(final FloatBuffer p0); public abstract Vector scale(final float p0); }
UTF-8
Java
867
java
Vector.java
Java
[]
null
[]
// // Decompiled by Procyon v0.5.36 // package org.lwjgl.util.vector; import java.nio.FloatBuffer; import java.io.Serializable; public abstract class Vector implements Serializable, ReadableVector { protected Vector() { } public final float length() { return (float)Math.sqrt(this.lengthSquared()); } public abstract float lengthSquared(); public abstract Vector load(final FloatBuffer p0); public abstract Vector negate(); public final Vector normalise() { final float len = this.length(); if (len != 0.0f) { final float l = 1.0f / len; return this.scale(l); } throw new IllegalStateException("Zero length vector"); } public abstract Vector store(final FloatBuffer p0); public abstract Vector scale(final float p0); }
867
0.629758
0.61707
37
22.432432
20.708452
68
false
false
0
0
0
0
0
0
0.378378
false
false
9
97cef89fc2c089c6c50be26a04a225685834841e
15,436,112,512,900
4a1ce68d37302104fcddbd99180726b972c50d4b
/src/SetsAndMaps/TestTreeSet.java
7221b373f6a1854ba2e2c571b662192d67751c52
[]
no_license
grknylmz/IntroductionToJava
https://github.com/grknylmz/IntroductionToJava
af8453aa85756bbe04e088f24cbaf65b5a74db62
98b88a8ab0508daddae08d7d57c92e653eb132ea
refs/heads/master
2021-01-10T20:57:01.341000
2015-03-28T09:32:29
2015-03-28T09:32:38
32,075,883
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package SetsAndMaps; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; /** * Created by Gurkan on 12.03.2015. */ public class TestTreeSet { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("London"); set.add("Paris"); set.add("New York"); set.add("San Francisco"); set.add("Beijing"); TreeSet treeSet = new TreeSet(set); ///TreeSets are sorted sets! No duplicates! System.out.println("Sorted tree set : " + treeSet); System.out.println("first () : " + treeSet.first()); System.out.println("last () : " + treeSet.last()); System.out.println("headSet (\"New York\") : " + treeSet.headSet("New York")); System.out.println("tailSet (\"New York\") : " + treeSet.tailSet("New York")); System.out.println("lower ( \"P\" )" + treeSet.lower("P")); System.out.println("higher ( \"P\" )" + treeSet.higher("P")); System.out.println("floor ( \"P\" )" + treeSet.floor("P")); System.out.println("ceiling ( \"P\" )" + treeSet.ceiling("P")); System.out.println("pollFirst():" + treeSet.pollFirst()); System.out.println("pollLast():" + treeSet.pollLast()); System.out.println("treeset" + treeSet); } }
UTF-8
Java
1,318
java
TestTreeSet.java
Java
[ { "context": ".Set;\nimport java.util.TreeSet;\n\n/**\n * Created by Gurkan on 12.03.2015.\n */\npublic class TestTreeSet {\n ", "end": 121, "score": 0.9982160925865173, "start": 115, "tag": "NAME", "value": "Gurkan" } ]
null
[]
package SetsAndMaps; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; /** * Created by Gurkan on 12.03.2015. */ public class TestTreeSet { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("London"); set.add("Paris"); set.add("New York"); set.add("San Francisco"); set.add("Beijing"); TreeSet treeSet = new TreeSet(set); ///TreeSets are sorted sets! No duplicates! System.out.println("Sorted tree set : " + treeSet); System.out.println("first () : " + treeSet.first()); System.out.println("last () : " + treeSet.last()); System.out.println("headSet (\"New York\") : " + treeSet.headSet("New York")); System.out.println("tailSet (\"New York\") : " + treeSet.tailSet("New York")); System.out.println("lower ( \"P\" )" + treeSet.lower("P")); System.out.println("higher ( \"P\" )" + treeSet.higher("P")); System.out.println("floor ( \"P\" )" + treeSet.floor("P")); System.out.println("ceiling ( \"P\" )" + treeSet.ceiling("P")); System.out.println("pollFirst():" + treeSet.pollFirst()); System.out.println("pollLast():" + treeSet.pollLast()); System.out.println("treeset" + treeSet); } }
1,318
0.57739
0.57132
42
30.380953
28.92186
88
false
false
0
0
0
0
0
0
0.547619
false
false
9
31a6819c681804d6ab21949c90f2ee11ec072df0
12,103,217,887,850
690e53cd3f142827641dd05b99ac2b8d61555433
/app/src/main/java/com/darkweb/genesisvpn/application/promotionManager/promotionViewController.java
c3ca9d543d4e7c8cb7dee041ef873d3a21bc7366
[]
no_license
msmannan00/Genesis-VPN-Android
https://github.com/msmannan00/Genesis-VPN-Android
d3f1054bb3318c084b5b312d413335257efb8702
395364352347c4ee6a582025babbb89afcc2a0f7
refs/heads/master
2023-06-23T11:29:13.301000
2021-01-16T15:13:15
2021-01-16T15:13:15
199,302,033
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.darkweb.genesisvpn.application.promotionManager; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.EditText; import android.widget.TextView; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.fragment.app.FragmentActivity; import com.darkweb.genesisvpn.R; import com.darkweb.genesisvpn.application.constants.strings; import com.darkweb.genesisvpn.application.helperManager.eventObserver; import com.darkweb.genesisvpn.application.helperManager.helperMethods; class promotionViewController { /*LOCAL VARIABLE DECLARATION*/ private FragmentActivity m_context; private eventObserver.eventListener m_event; private EditText m_promotion_edit_text; private ConstraintLayout m_alert_dialog; private TextView m_alert_title; private TextView m_alert_description; /*INITIALIZATIONS*/ public promotionViewController(FragmentActivity p_context, eventObserver.eventListener p_event, EditText p_promotion_edit_text, ConstraintLayout p_alert_dialog, TextView p_alert_title, TextView p_alert_description) { this.m_context = p_context; this.m_event = p_event; this.m_promotion_edit_text = p_promotion_edit_text; this.m_alert_dialog = p_alert_dialog; this.m_alert_title = p_alert_title; this.m_alert_description = p_alert_description; onInitializeView(); } private void onInitializeView(){ Window window = this.m_context.getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.setStatusBarColor(m_context.getResources().getColor(R.color.colorPrimary)); } public void onClearPromotionEditText(){ m_promotion_edit_text.clearFocus(); helperMethods.hideKeyboard(m_context); } public void onAlertDismiss() { m_promotion_edit_text.setText(strings.EMPTY_STR); m_context.runOnUiThread(() -> { m_alert_dialog.animate().cancel(); m_alert_dialog.setClickable(false); ((ConstraintLayout)m_alert_dialog.getChildAt(0)).getChildAt(1).setClickable(false); ((ConstraintLayout)m_alert_dialog.getChildAt(0)).getChildAt(2).setClickable(false); m_alert_dialog.animate().setDuration(200).alpha(0).withEndAction(() -> { m_alert_dialog.setVisibility(View.GONE); m_alert_description.setText(""); m_alert_title.setText(""); }); }); } public void onShowAlert(String p_error_message,String p_error_title, boolean p_is_forced){ String m_error = p_error_message; m_alert_dialog.setVisibility(View.VISIBLE); if(p_is_forced || !m_alert_description.getText().equals(m_error) && !m_alert_title.getText().equals(strings.AF_NO_APPLICATION_HEADER)){ m_context.runOnUiThread(() -> { if(m_alert_dialog.getAlpha()<1){ m_alert_dialog.animate().cancel(); m_alert_dialog.setAlpha(0); }else { m_alert_description.animate().cancel(); m_alert_title.animate().cancel(); m_alert_description.setAlpha(0.0f); m_alert_title.setAlpha(0.0f); m_alert_description.animate().alpha(1); m_alert_title.animate().alpha(1); m_alert_description.setText(m_error); m_alert_title.setText(p_error_title); return; } m_alert_dialog.animate().setDuration(200).alpha(1).withEndAction(() -> { m_alert_dialog.setClickable(true); ((ConstraintLayout)m_alert_dialog.getChildAt(0)).getChildAt(1).setClickable(true); ((ConstraintLayout)m_alert_dialog.getChildAt(0)).getChildAt(2).setClickable(true); }); m_alert_description.setText(m_error); m_alert_title.setText(p_error_title); m_alert_dialog.setVisibility(View.VISIBLE); }); } } public boolean isAlertViewShwoing(){ return m_alert_dialog.getAlpha() > 0; } /*HELPER METHODS*/ }
UTF-8
Java
4,368
java
promotionViewController.java
Java
[]
null
[]
package com.darkweb.genesisvpn.application.promotionManager; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.EditText; import android.widget.TextView; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.fragment.app.FragmentActivity; import com.darkweb.genesisvpn.R; import com.darkweb.genesisvpn.application.constants.strings; import com.darkweb.genesisvpn.application.helperManager.eventObserver; import com.darkweb.genesisvpn.application.helperManager.helperMethods; class promotionViewController { /*LOCAL VARIABLE DECLARATION*/ private FragmentActivity m_context; private eventObserver.eventListener m_event; private EditText m_promotion_edit_text; private ConstraintLayout m_alert_dialog; private TextView m_alert_title; private TextView m_alert_description; /*INITIALIZATIONS*/ public promotionViewController(FragmentActivity p_context, eventObserver.eventListener p_event, EditText p_promotion_edit_text, ConstraintLayout p_alert_dialog, TextView p_alert_title, TextView p_alert_description) { this.m_context = p_context; this.m_event = p_event; this.m_promotion_edit_text = p_promotion_edit_text; this.m_alert_dialog = p_alert_dialog; this.m_alert_title = p_alert_title; this.m_alert_description = p_alert_description; onInitializeView(); } private void onInitializeView(){ Window window = this.m_context.getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.setStatusBarColor(m_context.getResources().getColor(R.color.colorPrimary)); } public void onClearPromotionEditText(){ m_promotion_edit_text.clearFocus(); helperMethods.hideKeyboard(m_context); } public void onAlertDismiss() { m_promotion_edit_text.setText(strings.EMPTY_STR); m_context.runOnUiThread(() -> { m_alert_dialog.animate().cancel(); m_alert_dialog.setClickable(false); ((ConstraintLayout)m_alert_dialog.getChildAt(0)).getChildAt(1).setClickable(false); ((ConstraintLayout)m_alert_dialog.getChildAt(0)).getChildAt(2).setClickable(false); m_alert_dialog.animate().setDuration(200).alpha(0).withEndAction(() -> { m_alert_dialog.setVisibility(View.GONE); m_alert_description.setText(""); m_alert_title.setText(""); }); }); } public void onShowAlert(String p_error_message,String p_error_title, boolean p_is_forced){ String m_error = p_error_message; m_alert_dialog.setVisibility(View.VISIBLE); if(p_is_forced || !m_alert_description.getText().equals(m_error) && !m_alert_title.getText().equals(strings.AF_NO_APPLICATION_HEADER)){ m_context.runOnUiThread(() -> { if(m_alert_dialog.getAlpha()<1){ m_alert_dialog.animate().cancel(); m_alert_dialog.setAlpha(0); }else { m_alert_description.animate().cancel(); m_alert_title.animate().cancel(); m_alert_description.setAlpha(0.0f); m_alert_title.setAlpha(0.0f); m_alert_description.animate().alpha(1); m_alert_title.animate().alpha(1); m_alert_description.setText(m_error); m_alert_title.setText(p_error_title); return; } m_alert_dialog.animate().setDuration(200).alpha(1).withEndAction(() -> { m_alert_dialog.setClickable(true); ((ConstraintLayout)m_alert_dialog.getChildAt(0)).getChildAt(1).setClickable(true); ((ConstraintLayout)m_alert_dialog.getChildAt(0)).getChildAt(2).setClickable(true); }); m_alert_description.setText(m_error); m_alert_title.setText(p_error_title); m_alert_dialog.setVisibility(View.VISIBLE); }); } } public boolean isAlertViewShwoing(){ return m_alert_dialog.getAlpha() > 0; } /*HELPER METHODS*/ }
4,368
0.639423
0.6337
105
40.599998
33.428986
218
false
false
0
0
0
0
0
0
0.685714
false
false
9
72c4a0c323638c8dcd850806e0ff96b220d1e5bc
5,703,716,627,765
e429600de9066ea10e2f53d938315c4c16753936
/nakadi-java-client/src/main/java/nakadi/SubscriptionCollection.java
ea2d38c7aaa314c321d46cbbf26cb6a8e44c472c
[ "MIT" ]
permissive
adyach/nakadi-java
https://github.com/adyach/nakadi-java
97a4a929fd2f65817064d0bd55f2b677a48064a4
edcda6d82583f6d9a2c6b0ad210c173193ff6886
refs/heads/main
2023-03-24T07:50:52.937000
2022-12-15T15:27:32
2022-12-15T15:27:32
207,280,286
0
0
MIT
true
2019-09-09T10:06:38
2019-09-09T10:06:37
2019-08-27T19:22:05
2019-03-28T05:35:31
818
0
0
0
null
false
false
package nakadi; import java.util.List; /** * Represents a collection of subscriptions. * * @see nakadi.Subscription */ public class SubscriptionCollection extends ResourceCollection<Subscription> { private final SubscriptionResourceReal subscriptionResource; SubscriptionCollection(List<Subscription> items, List<ResourceLink> links, SubscriptionResourceReal subscriptionResource, NakadiClient client) { super(items, links, client); this.subscriptionResource = subscriptionResource; } public ResourceCollection<Subscription> fetchPage(String url) { return subscriptionResource.loadPage(url); } }
UTF-8
Java
633
java
SubscriptionCollection.java
Java
[]
null
[]
package nakadi; import java.util.List; /** * Represents a collection of subscriptions. * * @see nakadi.Subscription */ public class SubscriptionCollection extends ResourceCollection<Subscription> { private final SubscriptionResourceReal subscriptionResource; SubscriptionCollection(List<Subscription> items, List<ResourceLink> links, SubscriptionResourceReal subscriptionResource, NakadiClient client) { super(items, links, client); this.subscriptionResource = subscriptionResource; } public ResourceCollection<Subscription> fetchPage(String url) { return subscriptionResource.loadPage(url); } }
633
0.78357
0.78357
23
26.52174
28.544199
78
false
false
0
0
0
0
0
0
0.478261
false
false
9
1fd5b0039712813b2a27ed1a382db3ca22281fe6
17,781,164,648,521
6e3951760ba02eb5e18461c5aa639a97e0e7aa5a
/app/src/main/java/com/yy/sorter/ui/SenseUi.java
1927d570adeed8483328f4521503ca4d92466a1c
[]
no_license
yu-yang-halo/sorter
https://github.com/yu-yang-halo/sorter
a77ee655bbe16bc5f77796879d025029053a1bab
3925dcc639dcea2c997749feeb7760414c1a4e78
refs/heads/master
2020-03-28T10:20:53.481000
2019-11-03T01:25:43
2019-11-03T01:25:43
148,101,645
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yy.sorter.ui; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.RelativeLayout; import com.yy.sorter.activity.R; import com.yy.sorter.manager.FileManager; import com.yy.sorter.ui.base.BaseUi; import com.yy.sorter.ui.base.ConstantValues; import com.yy.sorter.ui.page.PageBaseUi; import com.yy.sorter.utils.StringUtils; import com.yy.sorter.version.PageVersionManager; import com.yy.sorter.view.PageSwitchView; import com.yy.sorter.view.ThAutoLayout; import com.yy.sorter.view.ThGroupView; import com.yy.sorter.view.ThSegmentView; import java.util.ArrayList; import java.util.List; import th.service.core.AbstractDataServiceFactory; import th.service.data.MachineData; import th.service.helper.YYPackage; public class SenseUi extends BaseUi { private ThSegmentView segmentView; private ThAutoLayout groupLayout; private RelativeLayout container; private PageSwitchView pageSwitchView; private PageBaseUi rgbIrPage,svmPage,hsvPage,shapePage; private PageBaseUi currentPage; public SenseUi(Context ctx) { super(ctx); } @Override protected View onInitView() { if(view == null) { view = LayoutInflater.from(ctx).inflate(R.layout.ui_sense,null); segmentView = (ThSegmentView) view.findViewById(R.id.segmentView); groupLayout = (ThAutoLayout) view.findViewById(R.id.groupLayout); container = (RelativeLayout) view.findViewById(R.id.container); pageSwitchView = (PageSwitchView) view.findViewById(R.id.pageSwitchView); segmentView.setOnSelectedListenser(new ThSegmentView.OnSelectedListenser() { @Override public void onSelected(int pos, ThSegmentView.TSegmentItem tSegmentItem) { loadChildPage(); } }); groupLayout.setOnSelectedListenser(new ThGroupView.OnSelectedListenser() { @Override public void onSelected(int pos) { AbstractDataServiceFactory.getInstance().getCurrentDevice().setCurrentGroup((byte) pos); if(currentPage != null) { currentPage.onGroupChanged(); } pageSwitchView.setmCurrentIndex(pos); } }); pageSwitchView.setPageSwitchListenser(new PageSwitchView.PageSwitchListenser() { @Override public void onPageSwitch(int pageIndex, int flag) { AbstractDataServiceFactory.getInstance().getCurrentDevice().setCurrentGroup((byte) pageIndex); if(currentPage != null) { currentPage.onGroupChanged(); } groupLayout.setSelectPos(pageIndex); } }); } return view; } private void loadChildPage() { if(segmentView.getSelectItem() != null) { int tag = segmentView.getSelectItem().getItemTag(); if(tag == 0) { loadPageToContainer(rgbIrPage,ConstantValues.VIEW_PAGE_RGB_IR,tag); }else if(tag == 1) { loadPageToContainer(svmPage,ConstantValues.VIEW_PAGE_SVM,tag); }else if(tag == 2) { loadPageToContainer(hsvPage,ConstantValues.VIEW_PAGE_HSV,tag); }else if(tag == 3) { loadPageToContainer(shapePage,ConstantValues.VIEW_PAGE_SHAPE,tag); } } } private void loadPageToContainer(PageBaseUi page,int pageId,int tag) { if(page == null) { page = PageVersionManager.getInstance().createPage(pageId,ctx); System.out.println("create page "+pageId+" "+page.getClass()); }else { Class targetClzz = PageVersionManager.getInstance().getPageClass(pageId); if(page.getClass() != targetClzz) { System.out.println("change page "+pageId+" "+page.getClass()+" to "+targetClzz); page = PageVersionManager.getInstance().createPage(pageId,ctx); }else { System.out.println("page "+pageId+" "+page.getClass()+" cache bingo"); } } page.loadToContainer(container); switch (tag) { case 0: rgbIrPage = page; break; case 1: svmPage = page; break; case 2: hsvPage = page; break; case 3: shapePage = page; break; } if(currentPage != null) { currentPage.onViewStop(); } currentPage = page; currentPage.onViewStart(); } @Override public void onViewStart() { super.onViewStart(); MachineData machineData = AbstractDataServiceFactory.getInstance().getCurrentDevice().getMachineData(); List<ThSegmentView.TSegmentItem> items=new ArrayList<>(); if(machineData.getUserColor() == 0x01) { ThSegmentView.TSegmentItem item0 = new ThSegmentView.TSegmentItem(FileManager.getInstance().getString(94),0);// 94#色选 items.add(item0); } if(machineData.getUseSvm() == 0x01) { ThSegmentView.TSegmentItem item1 = new ThSegmentView.TSegmentItem(FileManager.getInstance().getString(95),1);// 95#智能分选 items.add(item1); } if(machineData.getUseHsv() == 0x01) { ThSegmentView.TSegmentItem item2 = new ThSegmentView.TSegmentItem(FileManager.getInstance().getString(96),2);// 96#色度分选 items.add(item2); } if(machineData.getUseShape() == 0x01) { ThSegmentView.TSegmentItem item3 = new ThSegmentView.TSegmentItem(FileManager.getInstance().getString(97),3);// 97#形选 items.add(item3); } // if(machineData.getUseIR() == 0x01) // { // ThSegmentView.TSegmentItem item4 = new ThSegmentView.TSegmentItem(FileManager.getInstance().getString(98),4);//98#红外 // items.add(item4); // } segmentView.setContents(items); List<ThAutoLayout.Item> itemList = StringUtils.getGroupItem(); currentGroup = AbstractDataServiceFactory.getInstance().getCurrentDevice().getCurrentGroup(); groupLayout.setContents(itemList,currentGroup,0); pageSwitchView.setmNumbers(machineData.getGroupNumbers()); pageSwitchView.setmCurrentIndex(currentGroup); loadChildPage(); if(items==null || items.size()<=0) { segmentView.setVisibility(View.GONE); groupLayout.setVisibility(View.GONE); pageSwitchView.setVisibility(View.GONE); }else { segmentView.setVisibility(View.VISIBLE); groupLayout.setVisibility(View.VISIBLE); pageSwitchView.setVisibility(View.VISIBLE); } if(machineData.getGroupNumbers()<=1) { groupLayout.setVisibility(View.GONE); } } @Override public void onViewStop() { super.onViewStop(); if(currentPage != null) { currentPage.onViewStop(); } } @Override public int getID() { return ConstantValues.VIEW_SENSE; } @Override public int getLeaver() { return ConstantValues.LEAVER_TAB; } @Override public void receivePacketData(YYPackage packet) { if(currentPage != null) { currentPage.receivePacketData(packet); } } }
UTF-8
Java
7,877
java
SenseUi.java
Java
[]
null
[]
package com.yy.sorter.ui; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.RelativeLayout; import com.yy.sorter.activity.R; import com.yy.sorter.manager.FileManager; import com.yy.sorter.ui.base.BaseUi; import com.yy.sorter.ui.base.ConstantValues; import com.yy.sorter.ui.page.PageBaseUi; import com.yy.sorter.utils.StringUtils; import com.yy.sorter.version.PageVersionManager; import com.yy.sorter.view.PageSwitchView; import com.yy.sorter.view.ThAutoLayout; import com.yy.sorter.view.ThGroupView; import com.yy.sorter.view.ThSegmentView; import java.util.ArrayList; import java.util.List; import th.service.core.AbstractDataServiceFactory; import th.service.data.MachineData; import th.service.helper.YYPackage; public class SenseUi extends BaseUi { private ThSegmentView segmentView; private ThAutoLayout groupLayout; private RelativeLayout container; private PageSwitchView pageSwitchView; private PageBaseUi rgbIrPage,svmPage,hsvPage,shapePage; private PageBaseUi currentPage; public SenseUi(Context ctx) { super(ctx); } @Override protected View onInitView() { if(view == null) { view = LayoutInflater.from(ctx).inflate(R.layout.ui_sense,null); segmentView = (ThSegmentView) view.findViewById(R.id.segmentView); groupLayout = (ThAutoLayout) view.findViewById(R.id.groupLayout); container = (RelativeLayout) view.findViewById(R.id.container); pageSwitchView = (PageSwitchView) view.findViewById(R.id.pageSwitchView); segmentView.setOnSelectedListenser(new ThSegmentView.OnSelectedListenser() { @Override public void onSelected(int pos, ThSegmentView.TSegmentItem tSegmentItem) { loadChildPage(); } }); groupLayout.setOnSelectedListenser(new ThGroupView.OnSelectedListenser() { @Override public void onSelected(int pos) { AbstractDataServiceFactory.getInstance().getCurrentDevice().setCurrentGroup((byte) pos); if(currentPage != null) { currentPage.onGroupChanged(); } pageSwitchView.setmCurrentIndex(pos); } }); pageSwitchView.setPageSwitchListenser(new PageSwitchView.PageSwitchListenser() { @Override public void onPageSwitch(int pageIndex, int flag) { AbstractDataServiceFactory.getInstance().getCurrentDevice().setCurrentGroup((byte) pageIndex); if(currentPage != null) { currentPage.onGroupChanged(); } groupLayout.setSelectPos(pageIndex); } }); } return view; } private void loadChildPage() { if(segmentView.getSelectItem() != null) { int tag = segmentView.getSelectItem().getItemTag(); if(tag == 0) { loadPageToContainer(rgbIrPage,ConstantValues.VIEW_PAGE_RGB_IR,tag); }else if(tag == 1) { loadPageToContainer(svmPage,ConstantValues.VIEW_PAGE_SVM,tag); }else if(tag == 2) { loadPageToContainer(hsvPage,ConstantValues.VIEW_PAGE_HSV,tag); }else if(tag == 3) { loadPageToContainer(shapePage,ConstantValues.VIEW_PAGE_SHAPE,tag); } } } private void loadPageToContainer(PageBaseUi page,int pageId,int tag) { if(page == null) { page = PageVersionManager.getInstance().createPage(pageId,ctx); System.out.println("create page "+pageId+" "+page.getClass()); }else { Class targetClzz = PageVersionManager.getInstance().getPageClass(pageId); if(page.getClass() != targetClzz) { System.out.println("change page "+pageId+" "+page.getClass()+" to "+targetClzz); page = PageVersionManager.getInstance().createPage(pageId,ctx); }else { System.out.println("page "+pageId+" "+page.getClass()+" cache bingo"); } } page.loadToContainer(container); switch (tag) { case 0: rgbIrPage = page; break; case 1: svmPage = page; break; case 2: hsvPage = page; break; case 3: shapePage = page; break; } if(currentPage != null) { currentPage.onViewStop(); } currentPage = page; currentPage.onViewStart(); } @Override public void onViewStart() { super.onViewStart(); MachineData machineData = AbstractDataServiceFactory.getInstance().getCurrentDevice().getMachineData(); List<ThSegmentView.TSegmentItem> items=new ArrayList<>(); if(machineData.getUserColor() == 0x01) { ThSegmentView.TSegmentItem item0 = new ThSegmentView.TSegmentItem(FileManager.getInstance().getString(94),0);// 94#色选 items.add(item0); } if(machineData.getUseSvm() == 0x01) { ThSegmentView.TSegmentItem item1 = new ThSegmentView.TSegmentItem(FileManager.getInstance().getString(95),1);// 95#智能分选 items.add(item1); } if(machineData.getUseHsv() == 0x01) { ThSegmentView.TSegmentItem item2 = new ThSegmentView.TSegmentItem(FileManager.getInstance().getString(96),2);// 96#色度分选 items.add(item2); } if(machineData.getUseShape() == 0x01) { ThSegmentView.TSegmentItem item3 = new ThSegmentView.TSegmentItem(FileManager.getInstance().getString(97),3);// 97#形选 items.add(item3); } // if(machineData.getUseIR() == 0x01) // { // ThSegmentView.TSegmentItem item4 = new ThSegmentView.TSegmentItem(FileManager.getInstance().getString(98),4);//98#红外 // items.add(item4); // } segmentView.setContents(items); List<ThAutoLayout.Item> itemList = StringUtils.getGroupItem(); currentGroup = AbstractDataServiceFactory.getInstance().getCurrentDevice().getCurrentGroup(); groupLayout.setContents(itemList,currentGroup,0); pageSwitchView.setmNumbers(machineData.getGroupNumbers()); pageSwitchView.setmCurrentIndex(currentGroup); loadChildPage(); if(items==null || items.size()<=0) { segmentView.setVisibility(View.GONE); groupLayout.setVisibility(View.GONE); pageSwitchView.setVisibility(View.GONE); }else { segmentView.setVisibility(View.VISIBLE); groupLayout.setVisibility(View.VISIBLE); pageSwitchView.setVisibility(View.VISIBLE); } if(machineData.getGroupNumbers()<=1) { groupLayout.setVisibility(View.GONE); } } @Override public void onViewStop() { super.onViewStop(); if(currentPage != null) { currentPage.onViewStop(); } } @Override public int getID() { return ConstantValues.VIEW_SENSE; } @Override public int getLeaver() { return ConstantValues.LEAVER_TAB; } @Override public void receivePacketData(YYPackage packet) { if(currentPage != null) { currentPage.receivePacketData(packet); } } }
7,877
0.589884
0.582112
244
31.168034
29.320873
131
false
false
0
0
0
0
0
0
0.516393
false
false
9
f56128fab147e427fa45a05ce88811f8d5411406
4,655,744,587,144
357081fbefed19cff19db5a45c85c4de2743d31c
/src/main/java/com/xinchen/ssh/core/utils/Crypt.java
a342991cf71f7c00858fa07de55f24ad3e0a4298
[]
no_license
melodyfff/ssh
https://github.com/melodyfff/ssh
f68d74d36eb1dd1acfbd4d0daa5e4a043a29d15b
5e7e6c773adf47d087ca08bfcd29c38a0bdd37e3
refs/heads/master
2021-01-13T08:50:23.261000
2018-05-28T15:23:00
2018-05-28T15:23:00
71,897,695
0
0
null
false
2017-10-02T10:33:23
2016-10-25T13:04:07
2016-10-27T06:15:11
2017-10-02T10:33:23
65
0
0
0
Java
null
null
package com.xinchen.ssh.core.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; /** * 简单加密/解密方法包装 */ public class Crypt { private static final String PASSWORD_CRYPT_KEY = "xinchen_password"; private static final String DATA_CRYPT_KEY = "xinchen_data"; private final static String DES = "DES"; // 日志对象 private final static transient Logger logger = LoggerFactory.getLogger(Crypt.class); /** * 加密 * * @param src 数据源 * @param key 密钥,长度必须是8的倍数 * @return byte[] 返回加密后的数据 * @throws Exception 异常 */ public static byte[] encrypt(byte[] src, byte[] key) throws Exception { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom(); // 从原始密匙数据创建DESKeySpec对象 DESKeySpec dks = new DESKeySpec(key); // 创建一个密匙工厂,然后用它把DESKeySpec转换成 // 一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance(DES); // 用密匙初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, securekey, sr); // 现在,获取数据并加密 // 正式执行加密操作 return cipher.doFinal(src); } /** * 解密 * * @param src 数据源 * @param key 密钥,长度必须是8的倍数 * @return byte[] 返回解密后的原始数据 * @throws Exception 异常 */ public static byte[] decrypt(byte[] src, byte[] key) throws Exception { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom(); // 从原始密匙数据创建一个DESKeySpec对象 DESKeySpec dks = new DESKeySpec(key); // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成 // 一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher对象实际完成解密操作 Cipher cipher = Cipher.getInstance(DES); // 用密匙初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE, securekey, sr); // 现在,获取数据并解密 // 正式执行解密操作 return cipher.doFinal(src); } /** * 密码解密 * * @param data 字符串 * @return String 加密字符串 */ public final static String decrypt(String data) { try { return new String(decrypt(hex2byte(data.getBytes(Charset.forName("UTF-8"))), PASSWORD_CRYPT_KEY.getBytes(Charset.forName("UTF-8"))),StandardCharsets.UTF_8); } catch (Exception e) { logger.error(e.getMessage()); } return null; } /** * 密码加密 * * @param password 密码 * @return String 加密密码 */ public final static String encrypt(String password) { try { return byte2hex(encrypt(password.getBytes(Charset.forName("UTF-8")), PASSWORD_CRYPT_KEY.getBytes(Charset.forName("UTF-8")))); } catch (Exception e) { logger.error(e.getMessage()); } return null; } /** * 密码解密 * * @param data 字符串 * @param key key * @return String 加密字符串 */ public final static String decrypt(String data, String key) { try { return new String( decrypt(hex2byte(data.getBytes(Charset.forName("UTF-8"))), key.getBytes(Charset.forName("UTF-8"))),StandardCharsets.UTF_8); } catch (Exception e) { logger.error(e.getMessage()); } return null; } /** * 密码加密 * * @param password 密码 * @param key key * @return String 加密密码 */ public final static String encrypt(String password, String key) { try { return byte2hex(encrypt(password.getBytes(Charset.forName("UTF-8")), key.getBytes(Charset.forName("UTF-8")))); } catch (Exception e) { logger.error(e.getMessage()); } return null; } /** * 密码解密 * * @param data 待加密数据 * @return String 加密字符串 */ public final static String decryptData(String data) { try { return new String(decrypt(hex2byte(data.getBytes(Charset.forName("UTF-8"))), DATA_CRYPT_KEY.getBytes(Charset.forName("UTF-8"))),StandardCharsets.UTF_8); } catch (Exception e) { logger.error(e.getMessage()); } return null; } /** * 密码加密 * * @param password 密码 * @return String 加密密码 */ public final static String encryptData(String password) { try { return byte2hex(encrypt(password.getBytes(Charset.forName("UTF-8")), DATA_CRYPT_KEY.getBytes(Charset.forName("UTF-8")))); } catch (Exception e) { logger.error(e.getMessage()); } return null; } /** * 二行制转字符串 * * @param b 字节数组 * @return String 结果 */ public static String byte2hex(byte[] b) { StringBuilder hs = new StringBuilder(""); String stmp; for (int n = 0; n < b.length; n++) { stmp = (Integer.toHexString(b[n] & 0XFF)); if (stmp.length() == 1) { hs.append("0").append(stmp); } else { hs.append(stmp); } } return hs.toString().toUpperCase(); } /** * * 16位转换字节 * * @param b 字节数组 * @return byte[] 数组 */ public static byte[] hex2byte(byte[] b) { if ((b.length % 2) != 0) { throw new IllegalArgumentException("length is not even number!"); } byte[] b2 = new byte[b.length / 2]; for (int n = 0; n < b.length; n += 2) { String item = new String(b, n, 2,StandardCharsets.UTF_8); b2[n / 2] = (byte) Integer.parseInt(item, 16); } return b2; } }
UTF-8
Java
6,690
java
Crypt.java
Java
[ { "context": "private static final String PASSWORD_CRYPT_KEY = \"xinchen_password\";\n private static final String DATA_CRYPT_KEY ", "end": 457, "score": 0.9968582987785339, "start": 441, "tag": "KEY", "value": "xinchen_password" }, { "context": " private static final String DATA_CRYPT_KEY = \"xinchen_data\";\n private final static String DES = \"DES\";\n\n ", "end": 522, "score": 0.9972695112228394, "start": 510, "tag": "KEY", "value": "xinchen_data" }, { "context": " /**\n * 密码加密\n *\n * @param password 密码\n * @return String 加密密码\n */\n public fin", "end": 2826, "score": 0.9986856579780579, "start": 2824, "tag": "PASSWORD", "value": "密码" }, { "context": " /**\n * 密码加密\n *\n * @param password 密码\n * @return String 加密密码\n */\n public fin", "end": 4617, "score": 0.9933116436004639, "start": 4615, "tag": "PASSWORD", "value": "密码" } ]
null
[]
package com.xinchen.ssh.core.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; /** * 简单加密/解密方法包装 */ public class Crypt { private static final String PASSWORD_CRYPT_KEY = "xinchen_password"; private static final String DATA_CRYPT_KEY = "xinchen_data"; private final static String DES = "DES"; // 日志对象 private final static transient Logger logger = LoggerFactory.getLogger(Crypt.class); /** * 加密 * * @param src 数据源 * @param key 密钥,长度必须是8的倍数 * @return byte[] 返回加密后的数据 * @throws Exception 异常 */ public static byte[] encrypt(byte[] src, byte[] key) throws Exception { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom(); // 从原始密匙数据创建DESKeySpec对象 DESKeySpec dks = new DESKeySpec(key); // 创建一个密匙工厂,然后用它把DESKeySpec转换成 // 一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance(DES); // 用密匙初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, securekey, sr); // 现在,获取数据并加密 // 正式执行加密操作 return cipher.doFinal(src); } /** * 解密 * * @param src 数据源 * @param key 密钥,长度必须是8的倍数 * @return byte[] 返回解密后的原始数据 * @throws Exception 异常 */ public static byte[] decrypt(byte[] src, byte[] key) throws Exception { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom(); // 从原始密匙数据创建一个DESKeySpec对象 DESKeySpec dks = new DESKeySpec(key); // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成 // 一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher对象实际完成解密操作 Cipher cipher = Cipher.getInstance(DES); // 用密匙初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE, securekey, sr); // 现在,获取数据并解密 // 正式执行解密操作 return cipher.doFinal(src); } /** * 密码解密 * * @param data 字符串 * @return String 加密字符串 */ public final static String decrypt(String data) { try { return new String(decrypt(hex2byte(data.getBytes(Charset.forName("UTF-8"))), PASSWORD_CRYPT_KEY.getBytes(Charset.forName("UTF-8"))),StandardCharsets.UTF_8); } catch (Exception e) { logger.error(e.getMessage()); } return null; } /** * 密码加密 * * @param password 密码 * @return String 加密密码 */ public final static String encrypt(String password) { try { return byte2hex(encrypt(password.getBytes(Charset.forName("UTF-8")), PASSWORD_CRYPT_KEY.getBytes(Charset.forName("UTF-8")))); } catch (Exception e) { logger.error(e.getMessage()); } return null; } /** * 密码解密 * * @param data 字符串 * @param key key * @return String 加密字符串 */ public final static String decrypt(String data, String key) { try { return new String( decrypt(hex2byte(data.getBytes(Charset.forName("UTF-8"))), key.getBytes(Charset.forName("UTF-8"))),StandardCharsets.UTF_8); } catch (Exception e) { logger.error(e.getMessage()); } return null; } /** * 密码加密 * * @param password 密码 * @param key key * @return String 加密密码 */ public final static String encrypt(String password, String key) { try { return byte2hex(encrypt(password.getBytes(Charset.forName("UTF-8")), key.getBytes(Charset.forName("UTF-8")))); } catch (Exception e) { logger.error(e.getMessage()); } return null; } /** * 密码解密 * * @param data 待加密数据 * @return String 加密字符串 */ public final static String decryptData(String data) { try { return new String(decrypt(hex2byte(data.getBytes(Charset.forName("UTF-8"))), DATA_CRYPT_KEY.getBytes(Charset.forName("UTF-8"))),StandardCharsets.UTF_8); } catch (Exception e) { logger.error(e.getMessage()); } return null; } /** * 密码加密 * * @param password 密码 * @return String 加密密码 */ public final static String encryptData(String password) { try { return byte2hex(encrypt(password.getBytes(Charset.forName("UTF-8")), DATA_CRYPT_KEY.getBytes(Charset.forName("UTF-8")))); } catch (Exception e) { logger.error(e.getMessage()); } return null; } /** * 二行制转字符串 * * @param b 字节数组 * @return String 结果 */ public static String byte2hex(byte[] b) { StringBuilder hs = new StringBuilder(""); String stmp; for (int n = 0; n < b.length; n++) { stmp = (Integer.toHexString(b[n] & 0XFF)); if (stmp.length() == 1) { hs.append("0").append(stmp); } else { hs.append(stmp); } } return hs.toString().toUpperCase(); } /** * * 16位转换字节 * * @param b 字节数组 * @return byte[] 数组 */ public static byte[] hex2byte(byte[] b) { if ((b.length % 2) != 0) { throw new IllegalArgumentException("length is not even number!"); } byte[] b2 = new byte[b.length / 2]; for (int n = 0; n < b.length; n += 2) { String item = new String(b, n, 2,StandardCharsets.UTF_8); b2[n / 2] = (byte) Integer.parseInt(item, 16); } return b2; } }
6,690
0.564345
0.556716
219
26.534246
24.647144
143
false
false
0
0
0
0
0
0
0.374429
false
false
9
1899cc8e3c6aa0d52580f02a17157248185931cc
4,655,744,583,068
eabd4bb5c557f9532ad1314a6cc00e316dbec41f
/SimpleStroe2.0/src/com/iLoong/launcher/MList/MainActivity.java
86a590f937ce4e0e7538cef52960ee4e8da8d3e9
[]
no_license
hugoYe/HybridLockerEclipse
https://github.com/hugoYe/HybridLockerEclipse
50c191bcba67c596e43f974744cdd1594420c00d
9c5ac68d23d00c9fd932ef6ddacaa736808f1164
refs/heads/master
2021-01-21T13:57:56.148000
2016-05-19T10:25:29
2016-05-19T10:25:29
46,117,678
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.iLoong.launcher.MList; import java.lang.reflect.Field; import android.annotation.SuppressLint; import android.app.Activity; import android.app.WallpaperManager; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.KeyEvent; import android.view.View; import android.view.View.OnLongClickListener; import android.view.WindowManager; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import cool.sdk.MicroEntry.MicroEntryHelper; /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. * * @see SystemUiHider */ public class MainActivity extends Activity { private static boolean isNeedClearHistory = false; String reloadUrl = null; boolean flag = false; boolean flagError = false; JSClass mainJsClass = null; JSClass subJsCalss = null; WebView mainWebView = null; WebView subWebView = null; View MainFrameWebview = null; View SubFrameWebview = null; // static MyFloatView myFV; boolean isenable1 = true; boolean isenable2 = true; boolean isenable3 = true; boolean isenable4 = true; int app_id = 10009; public static MainActivity instance = null; byte[] UPath = { 80, 17, 86, -2, -9, 6, 110, -48, 88, 47, 124, -61, -2, 104, 67, -56, -75, -81, -31, 26, 66, 34, -57, -92, 26, 23, -73, 71, 5, 61, 24, -15, -72, 125, 110, -1, 6, -121, 77, -88, -21, 36, 85, 62, 35, 5, -95, -31, -99, 10, 2, -64, -88, -33, 105, -31, -7, 39, 26, 85, -54, 73, 35, -94 }; public boolean isExit = false; public String url; public int getId() { return app_id; } private String strAction = null; MyR R; @Override protected void onCreate(Bundle savedInstanceState) { MELOG.v("ME_RTFSC", "==== MainActivity onCreate ===="); // MeGeneralMethod.CanelKillProcess(); instance = this; super.onCreate(savedInstanceState); R = MyR.getMyR(this); if (R == null) { finish(); return; } Intent intent = getIntent(); app_id = intent.getIntExtra("APP_ID", 1); strAction = intent.getStringExtra("Action"); String strActionDescription = intent .getStringExtra("ActionDescription"); setContentView(R.layout.cool_ml_activity_main); MainFrameWebview = findViewById(R.id.cool_ml_mainwebviewframe); mainWebView = (WebView) findViewById(R.id.cool_ml_webView1); SubFrameWebview = findViewById(R.id.cool_ml_subwebviewframe); subWebView = (WebView) findViewById(R.id.cool_ml_webView2); if (getId() >= 800 && getId() <= 808) { mainJsClass = new JSClass(mainWebView, "M", 0, getId(), mHandler, R, MeApkDLShowType.WebviewMain); } else { mainJsClass = new JSClass(mainWebView, "M", getId(), getId(), mHandler, R, MeApkDLShowType.WebviewMain); } MeApkDownloadManager.MeAddActiveCallBackMap.put( MeApkDLShowType.WebviewMain, new MeActiveCallback() { @Override public void NotifyUninstallApkAction(String pkgName) { // TODO Auto-generated method stub mainJsClass.appInstallInfoChange( getApplicationContext(), pkgName, 0); mainJsClass.invokeJSMethod("reloadDownstate", pkgName); } @Override public void NotifyInstallSucessAction(String pkgName) { // TODO Auto-generated method stub mainJsClass.appInstallInfoChange( getApplicationContext(), pkgName, 1); mainJsClass .invokeJSMethod("AppInstallSuccess", pkgName); } @Override public void NotifyDelAction(String pkgName) { // TODO Auto-generated method stub MELOG.v("ME_RTFSC", "WebviewMain MeActiveCallback NotifyDelAction"); mainJsClass.invokeJSMethod("reloadDownstate", pkgName); } @Override public void NoifySatrtAction(String pkgName) { // TODO Auto-generated method stub mainJsClass.invokeJSMethod("reloadDownstate", pkgName); } }); bindJsClass(mainJsClass, mainWebView); SubFrameWebview.setVisibility(View.INVISIBLE); if (getId() >= 800 && getId() <= 808) { subJsCalss = new JSClass(subWebView, "M", 0, getId(), mHandler, R, MeApkDLShowType.WebviewSub); } else { subJsCalss = new JSClass(subWebView, "M", getId(), getId(), mHandler, R, MeApkDLShowType.WebviewSub); } MeApkDownloadManager.MeAddActiveCallBackMap.put( MeApkDLShowType.WebviewSub, new MeActiveCallback() { @Override public void NotifyUninstallApkAction(String pkgName) { // TODO Auto-generated method stub subJsCalss.appInstallInfoChange( getApplicationContext(), pkgName, 0); subJsCalss.invokeJSMethod("reloadDownstate", pkgName); } @Override public void NotifyInstallSucessAction(String pkgName) { // TODO Auto-generated method stub subJsCalss.invokeJSMethod("AppInstallSuccess", pkgName); subJsCalss.appInstallInfoChange( getApplicationContext(), pkgName, 1); } @Override public void NotifyDelAction(String pkgName) { // TODO Auto-generated method stub MELOG.v("ME_RTFSC", "subJsCalss MeActiveCallback NotifyDelAction"); subJsCalss.invokeJSMethod("reloadDownstate", pkgName); } @Override public void NoifySatrtAction(String pkgName) { // TODO Auto-generated method stub subJsCalss.invokeJSMethod("reloadDownstate", pkgName); } }); bindJsClass(subJsCalss, subWebView); MELOG.v("ME_RTFSC", "id:" + getId() + " strAction:" + strAction + ", strActionDescription:" + strActionDescription); if (null == strAction || strAction.isEmpty() || null == strActionDescription || strActionDescription.isEmpty()) { MELOG.v("ME_RTFSC", "1111111111111111111111111"); MainFrameWebview.setVisibility(View.VISIBLE); LoadMiroEntryUrl(null, true); } // 增加 detailbox_pkgname 入口方式 else if (strAction.equals("detailbox_pkgname")) { MELOG.v("ME_RTFSC", "detailbox_pkgname detailbox_pkgname detailbox_pkgname "); SubFrameWebview.setVisibility(View.VISIBLE); MainFrameWebview.setVisibility(View.INVISIBLE); subWebView.clearView(); subJsCalss.setDialog(); isNeedClearHistory = true; subWebView .loadUrl(" http://uifolder.coolauncher.com.cn/qqkhd/detailbox.htm?pkgname=" + strActionDescription); LoadMiroEntryUrl(null, false); } else if (strAction.equals("detailfolder_pkgname")) { MELOG.v("ME_RTFSC", "detailfolder_pkgname detailfolder_pkgname detailfolder_pkgname "); SubFrameWebview.setVisibility(View.VISIBLE); MainFrameWebview.setVisibility(View.INVISIBLE); subWebView.clearView(); subJsCalss.setDialog(); isNeedClearHistory = true; subWebView .loadUrl("http://uifolder.coolauncher.com.cn/qqkhd/detail.php?p=" + LoadURL.BaseDetalFolder64Str(this, strActionDescription)); LoadMiroEntryUrl(null, false); } else if (strAction.equals("pkgname")) { MELOG.v("ME_RTFSC", "pkgname pkgname pkgname "); SubFrameWebview.setVisibility(View.VISIBLE); MainFrameWebview.setVisibility(View.INVISIBLE); subWebView.clearView(); subJsCalss.setDialog(); isNeedClearHistory = true; subWebView .loadUrl(" http://uifolder.coolauncher.com.cn/qqkhd/detailpush.htm?pkgname=" + strActionDescription); LoadMiroEntryUrl(null, false); } else if (strAction.equals("url")) { MELOG.v("ME_RTFSC", "url url url "); SubFrameWebview.setVisibility(View.VISIBLE); MainFrameWebview.setVisibility(View.INVISIBLE); subWebView.clearView(); subJsCalss.setDialog(); isNeedClearHistory = true; subWebView.loadUrl(strActionDescription); LoadMiroEntryUrl(null, false); } else if ((strAction.equals("anchor"))) { MELOG.v("ME_RTFSC", "anchor anchor anchor "); MainFrameWebview.setVisibility(View.VISIBLE); LoadMiroEntryUrl(strActionDescription, true); } mainJsClass.DownloadApkNeedDownload(); } private void LoadMiroEntryUrl(String tableIndex, boolean isNeedShowPregressDlg) { // TODO Auto-generated method stub LoadURL.initPhoneInfoma(getApplicationContext()); String url = MicroEntryHelper.getInstance(this).getEntryUrl(getId()); if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) { url = url + "?" + "p=" + LoadURL.Base64Str(MainActivity.this, getId()); // MELOG.v( "ME_RTFSC" , "1111 mainWebView.loadUrl" + url ); } else { RijndaelCrypt aes = new RijndaelCrypt(RijndaelCrypt.PWD, RijndaelCrypt.IV); url = aes.decrypt(UPath) + "?p=" + LoadURL.Base64Str(MainActivity.this, getId()); // MELOG.v( "ME_RTFSC" , "2222 mainWebView.loadUrl" + url ); } // String url = "http://192.168.1.225/shl/test_goto.php" + // LoadURL.Base64Str( MainActivity.this , getId() ); // MELOG.v( "ME_RTFSC" , "2222 mainWebView.loadUrl" ); if (null != tableIndex && !tableIndex.isEmpty()) { url = url + "&tab=" + tableIndex; } MELOG.v("ME_RTFSC", "mainWebView.loadUrl" + url); if (isNeedShowPregressDlg) { mainJsClass.setDialog(); } mainWebView.loadUrl(url); } @Override protected void onRestart() { // TODO Auto-generated method stub super.onRestart(); } @Override protected void onStop() { // TODO Auto-generated method stub MELOG.v("ME_RTFSC", "==== MainActivity onStop ===="); super.onStop(); } public void onDestroy() { MELOG.v("ME_RTFSC", "==== MainActivity onDestroy ===="); super.onDestroy(); // instance = null; if (mainWebView != null) { // Utils3D.showPidMemoryInfo( MainActivity.this , "MainActivity" ); } // if( true == isExit ) // { // android.os.Process.killProcess( android.os.Process.myPid() ); // } // 在微入口activity销毁前,需要先把可能显示的dialog 销毁掉 mainJsClass.canelDialog(); subJsCalss.canelDialog(); // MeGeneralMethod.KillProcessIfNeed( getApplicationContext() ) ; // if( !MeGeneralMethod.IsDownloadTaskRunning( getApplicationContext() ) // && !MeGeneralMethod.IsForegroundRunning( getApplicationContext() ) ) // { // MeGeneralMethod.stopMeDLProtectionService( getApplicationContext() ); // android.os.Process.killProcess( android.os.Process.myPid() ); // } } @Override protected void onResume() { super.onResume(); MELOG.v("ME_RTFSC", "==== MainActivity onResume ===="); // jsClass.Init(); if (true == flag) { mainWebView.goBack(); flag = false; } }; @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); // 这里要退出,否则会导致界面还乱,原因未知,bug11952 // finish(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { MELOG.v("ME_RTFSC", " onKeyDown "); if (KeyEvent.KEYCODE_BACK == keyCode) { if (View.VISIBLE == MainFrameWebview.getVisibility()) { return MainWebViewOnBackListener(); } else { return SubWebViewOnBackListener(); } } return super.onKeyDown(keyCode, event); // 不会回到 home 页面 } private boolean SubWebViewOnBackListener() { MELOG.v("ME_RTFSC", " SubWebViewOnBackListener "); // WebBackForwardList Weblist = subWebView.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , " WebViewOnBackListener Weblist size:" + // Weblist.getSize() + "Webview Cur:" + Weblist.getCurrentIndex() ); flag = false; if (subWebView.canGoBack()) { subWebView.goBack(); // Weblist = subWebView.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , " WebViewOnBackListener Weblist size:" + // Weblist.getSize() + "Webview Cur:" + Weblist.getCurrentIndex() ); } else if ("detailfolder_pkgname".equals(strAction)) { finish(); } else { SubFrameWebview.setVisibility(View.INVISIBLE); MainFrameWebview.setVisibility(View.VISIBLE); } return true; } private boolean MainWebViewOnBackListener() { MELOG.v("ME_RTFSC", " MainWebViewOnBackListener "); // TODO Auto-generated method stub // WebBackForwardList Weblist = mainWebView.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , " WebViewOnBackListener Weblist size:" + // Weblist.getSize() + "Webview Cur:" + Weblist.getCurrentIndex() ); flag = false; if (mainWebView.canGoBack()) { mainWebView.goBack(); // Weblist = mainWebView.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , " WebViewOnBackListener Weblist size:" + // Weblist.getSize() + "Webview Cur:" + Weblist.getCurrentIndex() ); return true; } else { if (!isExit) { isExit = true; Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); mHandler.sendEmptyMessageDelayed(0, 2000); } else { finish(); } return false; } } @SuppressLint("JavascriptInterface") private void bindJsClass(final JSClass jsClass, WebView webView) { webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); webView.setBackgroundColor(Color.parseColor("#e0e0df")); WebSettings webSettings = webView.getSettings(); webSettings.setLoadWithOverviewMode(true); webSettings.setJavaScriptEnabled(true); webSettings.setAllowFileAccess(true); webSettings.setDomStorageEnabled(true); webSettings.setAppCacheEnabled(true); webSettings.setAppCacheMaxSize(16 * 1024 * 1024); webSettings.setAppCachePath(PathUtil .getPathDBSdcard(getApplicationContext())); // webSettings.set // HTML5地理位置服务在Android中的应用,因为用不着,所有注释掉 // webSettings.setGeolocationEnabled( true ); // webSettings.setGeolocationDatabasePath( PathUtil.getPathDBSdcard() ); webSettings.setDatabaseEnabled(true); webSettings.setDatabasePath(PathUtil .getPathDBSdcard(getApplicationContext())); if ("detailfolder_pkgname".equals(strAction)) { webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); } else if (true == JSClass .IsNetworkAvailableLocal(getApplicationContext())) { webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); } else { webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); } webView.addJavascriptInterface((Object) jsClass, "JSClass"); webView.setWebViewClient(new WebViewClient() { @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // TODO Auto-generated method stub MELOG.v("ME_RTFSC", "=== onReceivedError === failingUrl: " + failingUrl); // view.loadUrl( "javascript:document.body.innerHTML= '' " ); // view.loadUrl( // "javascript:window.location.replace('file:///android_asset/cool_ml_NoNet.htm');" // ); view.loadUrl("file:///android_asset/cool_ml_NoNet.htm"); jsClass.failingUrl = failingUrl; jsClass.canelDialog(); // if( jsClass.builder != null ) // { // jsClass.builder.dismiss(); // } // WebBackForwardList Weblist = view.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , " onReceivedError Weblist size:" + // Weblist.getSize() + "Webview Cur:" + // Weblist.getCurrentIndex() ); flagError = true; flag = true; } public boolean shouldOverrideUrlLoading(WebView view, String url) {// 网页覆盖 MELOG.v("ME_RTFSC", "=== shouldOverrideUrlLoading === url: " + url); // WebBackForwardList Weblist = view.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , // " shouldOverrideUrlLoading Weblist size:" + Weblist.getSize() // + "Webview Cur:" + Weblist.getCurrentIndex() ); return super.shouldOverrideUrlLoading(view, url); } public void onPageFinished(WebView view, String url) {// 网页加载完毕 MELOG.v("ME_RTFSC", "=== onPageFinished === url: " + url); // WebBackForwardList Weblist = view.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , " onPageFinished Weblist size:" + // Weblist.getSize() + "Webview Cur:" + // Weblist.getCurrentIndex() ); super.onPageFinished(view, url); if (flagError == true && "file:///android_asset/cool_ml_NoNet.htm" .equals(url)) { // view.loadUrl( "javascript:document.body.innerHTML= ' ' " // ); // view.loadUrl( // "javascript:window.location.replace('file:///android_asset/cool_ml_NoNet.htm');" // ); // view.goBack(); view.clearHistory(); flagError = false; } if (true == isNeedClearHistory) { view.clearHistory(); isNeedClearHistory = false; } jsClass.canelDialog(); // Weblist = view.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , " onPageFinished Weblist size:" + // Weblist.getSize() + "Webview Cur:" + // Weblist.getCurrentIndex() ); } public void onPageStarted(WebView view, String url, Bitmap favicon) {// 网页开始加载 MELOG.v("ME_RTFSC", "=== onPageStarted === url: " + url); super.onPageStarted(view, url, favicon); // WebBackForwardList Weblist = view.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , " onPageStarted Weblist size:" + // Weblist.getSize() + "Webview Cur:" + // Weblist.getCurrentIndex() ); } }); webView.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { return true; } }); } public void setConfigCallback(WindowManager windowManager) { try { Field field = WebView.class.getDeclaredField("mWebViewCore"); field = field.getType().getDeclaredField("mBrowserFrame"); field = field.getType().getDeclaredField("sConfigCallback"); field.setAccessible(true); Object configCallback = field.get(null); if (null == configCallback) { return; } field = field.getType().getDeclaredField("mWindowManager"); field.setAccessible(true); field.set(configCallback, windowManager); } catch (Exception e) { } } // MainActivity的mHandler handleMaessge 的处理项 public static final int openSubWebView = 1; public static final int subWebViewBackSoftKey = 2; public static final int mainWebViewBackSoftKey = 3; public static final int setBackgroundWithWallpaper = 4; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub // 0 --退出 ; 1--下载失败 switch (msg.what) { // 从MainView跳转到SubView case openSubWebView: { SubFrameWebview.setVisibility(View.VISIBLE); MainFrameWebview.setVisibility(View.INVISIBLE); String subUrl = (String) msg.obj; subWebView.clearView(); subJsCalss.setDialog(); isNeedClearHistory = true; subWebView.loadUrl(subUrl); } break; // MainWebView中返回软按键响应函数 case mainWebViewBackSoftKey: { MainWebViewOnBackListener(); } break; // subWebView中返回软按键响应函数 case subWebViewBackSoftKey: { SubWebViewOnBackListener(); } break; // 使用系统当前壁纸做为WEB页壁纸 case setBackgroundWithWallpaper: { WebView curWebview = (WebView) msg.obj; WallpaperManager wallpaperManager = WallpaperManager .getInstance(getApplicationContext()); // 获取壁纸管理器 Drawable wallpaperDrawable = wallpaperManager.getDrawable();// 获取当前壁纸 curWebview.setBackgroundColor(0); curWebview.setBackgroundDrawable(wallpaperDrawable); // curWebview.refreshDrawableState(); } break; default: break; } } }; }
UTF-8
Java
19,321
java
MainActivity.java
Java
[]
null
[]
package com.iLoong.launcher.MList; import java.lang.reflect.Field; import android.annotation.SuppressLint; import android.app.Activity; import android.app.WallpaperManager; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.KeyEvent; import android.view.View; import android.view.View.OnLongClickListener; import android.view.WindowManager; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import cool.sdk.MicroEntry.MicroEntryHelper; /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. * * @see SystemUiHider */ public class MainActivity extends Activity { private static boolean isNeedClearHistory = false; String reloadUrl = null; boolean flag = false; boolean flagError = false; JSClass mainJsClass = null; JSClass subJsCalss = null; WebView mainWebView = null; WebView subWebView = null; View MainFrameWebview = null; View SubFrameWebview = null; // static MyFloatView myFV; boolean isenable1 = true; boolean isenable2 = true; boolean isenable3 = true; boolean isenable4 = true; int app_id = 10009; public static MainActivity instance = null; byte[] UPath = { 80, 17, 86, -2, -9, 6, 110, -48, 88, 47, 124, -61, -2, 104, 67, -56, -75, -81, -31, 26, 66, 34, -57, -92, 26, 23, -73, 71, 5, 61, 24, -15, -72, 125, 110, -1, 6, -121, 77, -88, -21, 36, 85, 62, 35, 5, -95, -31, -99, 10, 2, -64, -88, -33, 105, -31, -7, 39, 26, 85, -54, 73, 35, -94 }; public boolean isExit = false; public String url; public int getId() { return app_id; } private String strAction = null; MyR R; @Override protected void onCreate(Bundle savedInstanceState) { MELOG.v("ME_RTFSC", "==== MainActivity onCreate ===="); // MeGeneralMethod.CanelKillProcess(); instance = this; super.onCreate(savedInstanceState); R = MyR.getMyR(this); if (R == null) { finish(); return; } Intent intent = getIntent(); app_id = intent.getIntExtra("APP_ID", 1); strAction = intent.getStringExtra("Action"); String strActionDescription = intent .getStringExtra("ActionDescription"); setContentView(R.layout.cool_ml_activity_main); MainFrameWebview = findViewById(R.id.cool_ml_mainwebviewframe); mainWebView = (WebView) findViewById(R.id.cool_ml_webView1); SubFrameWebview = findViewById(R.id.cool_ml_subwebviewframe); subWebView = (WebView) findViewById(R.id.cool_ml_webView2); if (getId() >= 800 && getId() <= 808) { mainJsClass = new JSClass(mainWebView, "M", 0, getId(), mHandler, R, MeApkDLShowType.WebviewMain); } else { mainJsClass = new JSClass(mainWebView, "M", getId(), getId(), mHandler, R, MeApkDLShowType.WebviewMain); } MeApkDownloadManager.MeAddActiveCallBackMap.put( MeApkDLShowType.WebviewMain, new MeActiveCallback() { @Override public void NotifyUninstallApkAction(String pkgName) { // TODO Auto-generated method stub mainJsClass.appInstallInfoChange( getApplicationContext(), pkgName, 0); mainJsClass.invokeJSMethod("reloadDownstate", pkgName); } @Override public void NotifyInstallSucessAction(String pkgName) { // TODO Auto-generated method stub mainJsClass.appInstallInfoChange( getApplicationContext(), pkgName, 1); mainJsClass .invokeJSMethod("AppInstallSuccess", pkgName); } @Override public void NotifyDelAction(String pkgName) { // TODO Auto-generated method stub MELOG.v("ME_RTFSC", "WebviewMain MeActiveCallback NotifyDelAction"); mainJsClass.invokeJSMethod("reloadDownstate", pkgName); } @Override public void NoifySatrtAction(String pkgName) { // TODO Auto-generated method stub mainJsClass.invokeJSMethod("reloadDownstate", pkgName); } }); bindJsClass(mainJsClass, mainWebView); SubFrameWebview.setVisibility(View.INVISIBLE); if (getId() >= 800 && getId() <= 808) { subJsCalss = new JSClass(subWebView, "M", 0, getId(), mHandler, R, MeApkDLShowType.WebviewSub); } else { subJsCalss = new JSClass(subWebView, "M", getId(), getId(), mHandler, R, MeApkDLShowType.WebviewSub); } MeApkDownloadManager.MeAddActiveCallBackMap.put( MeApkDLShowType.WebviewSub, new MeActiveCallback() { @Override public void NotifyUninstallApkAction(String pkgName) { // TODO Auto-generated method stub subJsCalss.appInstallInfoChange( getApplicationContext(), pkgName, 0); subJsCalss.invokeJSMethod("reloadDownstate", pkgName); } @Override public void NotifyInstallSucessAction(String pkgName) { // TODO Auto-generated method stub subJsCalss.invokeJSMethod("AppInstallSuccess", pkgName); subJsCalss.appInstallInfoChange( getApplicationContext(), pkgName, 1); } @Override public void NotifyDelAction(String pkgName) { // TODO Auto-generated method stub MELOG.v("ME_RTFSC", "subJsCalss MeActiveCallback NotifyDelAction"); subJsCalss.invokeJSMethod("reloadDownstate", pkgName); } @Override public void NoifySatrtAction(String pkgName) { // TODO Auto-generated method stub subJsCalss.invokeJSMethod("reloadDownstate", pkgName); } }); bindJsClass(subJsCalss, subWebView); MELOG.v("ME_RTFSC", "id:" + getId() + " strAction:" + strAction + ", strActionDescription:" + strActionDescription); if (null == strAction || strAction.isEmpty() || null == strActionDescription || strActionDescription.isEmpty()) { MELOG.v("ME_RTFSC", "1111111111111111111111111"); MainFrameWebview.setVisibility(View.VISIBLE); LoadMiroEntryUrl(null, true); } // 增加 detailbox_pkgname 入口方式 else if (strAction.equals("detailbox_pkgname")) { MELOG.v("ME_RTFSC", "detailbox_pkgname detailbox_pkgname detailbox_pkgname "); SubFrameWebview.setVisibility(View.VISIBLE); MainFrameWebview.setVisibility(View.INVISIBLE); subWebView.clearView(); subJsCalss.setDialog(); isNeedClearHistory = true; subWebView .loadUrl(" http://uifolder.coolauncher.com.cn/qqkhd/detailbox.htm?pkgname=" + strActionDescription); LoadMiroEntryUrl(null, false); } else if (strAction.equals("detailfolder_pkgname")) { MELOG.v("ME_RTFSC", "detailfolder_pkgname detailfolder_pkgname detailfolder_pkgname "); SubFrameWebview.setVisibility(View.VISIBLE); MainFrameWebview.setVisibility(View.INVISIBLE); subWebView.clearView(); subJsCalss.setDialog(); isNeedClearHistory = true; subWebView .loadUrl("http://uifolder.coolauncher.com.cn/qqkhd/detail.php?p=" + LoadURL.BaseDetalFolder64Str(this, strActionDescription)); LoadMiroEntryUrl(null, false); } else if (strAction.equals("pkgname")) { MELOG.v("ME_RTFSC", "pkgname pkgname pkgname "); SubFrameWebview.setVisibility(View.VISIBLE); MainFrameWebview.setVisibility(View.INVISIBLE); subWebView.clearView(); subJsCalss.setDialog(); isNeedClearHistory = true; subWebView .loadUrl(" http://uifolder.coolauncher.com.cn/qqkhd/detailpush.htm?pkgname=" + strActionDescription); LoadMiroEntryUrl(null, false); } else if (strAction.equals("url")) { MELOG.v("ME_RTFSC", "url url url "); SubFrameWebview.setVisibility(View.VISIBLE); MainFrameWebview.setVisibility(View.INVISIBLE); subWebView.clearView(); subJsCalss.setDialog(); isNeedClearHistory = true; subWebView.loadUrl(strActionDescription); LoadMiroEntryUrl(null, false); } else if ((strAction.equals("anchor"))) { MELOG.v("ME_RTFSC", "anchor anchor anchor "); MainFrameWebview.setVisibility(View.VISIBLE); LoadMiroEntryUrl(strActionDescription, true); } mainJsClass.DownloadApkNeedDownload(); } private void LoadMiroEntryUrl(String tableIndex, boolean isNeedShowPregressDlg) { // TODO Auto-generated method stub LoadURL.initPhoneInfoma(getApplicationContext()); String url = MicroEntryHelper.getInstance(this).getEntryUrl(getId()); if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) { url = url + "?" + "p=" + LoadURL.Base64Str(MainActivity.this, getId()); // MELOG.v( "ME_RTFSC" , "1111 mainWebView.loadUrl" + url ); } else { RijndaelCrypt aes = new RijndaelCrypt(RijndaelCrypt.PWD, RijndaelCrypt.IV); url = aes.decrypt(UPath) + "?p=" + LoadURL.Base64Str(MainActivity.this, getId()); // MELOG.v( "ME_RTFSC" , "2222 mainWebView.loadUrl" + url ); } // String url = "http://192.168.1.225/shl/test_goto.php" + // LoadURL.Base64Str( MainActivity.this , getId() ); // MELOG.v( "ME_RTFSC" , "2222 mainWebView.loadUrl" ); if (null != tableIndex && !tableIndex.isEmpty()) { url = url + "&tab=" + tableIndex; } MELOG.v("ME_RTFSC", "mainWebView.loadUrl" + url); if (isNeedShowPregressDlg) { mainJsClass.setDialog(); } mainWebView.loadUrl(url); } @Override protected void onRestart() { // TODO Auto-generated method stub super.onRestart(); } @Override protected void onStop() { // TODO Auto-generated method stub MELOG.v("ME_RTFSC", "==== MainActivity onStop ===="); super.onStop(); } public void onDestroy() { MELOG.v("ME_RTFSC", "==== MainActivity onDestroy ===="); super.onDestroy(); // instance = null; if (mainWebView != null) { // Utils3D.showPidMemoryInfo( MainActivity.this , "MainActivity" ); } // if( true == isExit ) // { // android.os.Process.killProcess( android.os.Process.myPid() ); // } // 在微入口activity销毁前,需要先把可能显示的dialog 销毁掉 mainJsClass.canelDialog(); subJsCalss.canelDialog(); // MeGeneralMethod.KillProcessIfNeed( getApplicationContext() ) ; // if( !MeGeneralMethod.IsDownloadTaskRunning( getApplicationContext() ) // && !MeGeneralMethod.IsForegroundRunning( getApplicationContext() ) ) // { // MeGeneralMethod.stopMeDLProtectionService( getApplicationContext() ); // android.os.Process.killProcess( android.os.Process.myPid() ); // } } @Override protected void onResume() { super.onResume(); MELOG.v("ME_RTFSC", "==== MainActivity onResume ===="); // jsClass.Init(); if (true == flag) { mainWebView.goBack(); flag = false; } }; @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); // 这里要退出,否则会导致界面还乱,原因未知,bug11952 // finish(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { MELOG.v("ME_RTFSC", " onKeyDown "); if (KeyEvent.KEYCODE_BACK == keyCode) { if (View.VISIBLE == MainFrameWebview.getVisibility()) { return MainWebViewOnBackListener(); } else { return SubWebViewOnBackListener(); } } return super.onKeyDown(keyCode, event); // 不会回到 home 页面 } private boolean SubWebViewOnBackListener() { MELOG.v("ME_RTFSC", " SubWebViewOnBackListener "); // WebBackForwardList Weblist = subWebView.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , " WebViewOnBackListener Weblist size:" + // Weblist.getSize() + "Webview Cur:" + Weblist.getCurrentIndex() ); flag = false; if (subWebView.canGoBack()) { subWebView.goBack(); // Weblist = subWebView.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , " WebViewOnBackListener Weblist size:" + // Weblist.getSize() + "Webview Cur:" + Weblist.getCurrentIndex() ); } else if ("detailfolder_pkgname".equals(strAction)) { finish(); } else { SubFrameWebview.setVisibility(View.INVISIBLE); MainFrameWebview.setVisibility(View.VISIBLE); } return true; } private boolean MainWebViewOnBackListener() { MELOG.v("ME_RTFSC", " MainWebViewOnBackListener "); // TODO Auto-generated method stub // WebBackForwardList Weblist = mainWebView.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , " WebViewOnBackListener Weblist size:" + // Weblist.getSize() + "Webview Cur:" + Weblist.getCurrentIndex() ); flag = false; if (mainWebView.canGoBack()) { mainWebView.goBack(); // Weblist = mainWebView.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , " WebViewOnBackListener Weblist size:" + // Weblist.getSize() + "Webview Cur:" + Weblist.getCurrentIndex() ); return true; } else { if (!isExit) { isExit = true; Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); mHandler.sendEmptyMessageDelayed(0, 2000); } else { finish(); } return false; } } @SuppressLint("JavascriptInterface") private void bindJsClass(final JSClass jsClass, WebView webView) { webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); webView.setBackgroundColor(Color.parseColor("#e0e0df")); WebSettings webSettings = webView.getSettings(); webSettings.setLoadWithOverviewMode(true); webSettings.setJavaScriptEnabled(true); webSettings.setAllowFileAccess(true); webSettings.setDomStorageEnabled(true); webSettings.setAppCacheEnabled(true); webSettings.setAppCacheMaxSize(16 * 1024 * 1024); webSettings.setAppCachePath(PathUtil .getPathDBSdcard(getApplicationContext())); // webSettings.set // HTML5地理位置服务在Android中的应用,因为用不着,所有注释掉 // webSettings.setGeolocationEnabled( true ); // webSettings.setGeolocationDatabasePath( PathUtil.getPathDBSdcard() ); webSettings.setDatabaseEnabled(true); webSettings.setDatabasePath(PathUtil .getPathDBSdcard(getApplicationContext())); if ("detailfolder_pkgname".equals(strAction)) { webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); } else if (true == JSClass .IsNetworkAvailableLocal(getApplicationContext())) { webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); } else { webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); } webView.addJavascriptInterface((Object) jsClass, "JSClass"); webView.setWebViewClient(new WebViewClient() { @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // TODO Auto-generated method stub MELOG.v("ME_RTFSC", "=== onReceivedError === failingUrl: " + failingUrl); // view.loadUrl( "javascript:document.body.innerHTML= '' " ); // view.loadUrl( // "javascript:window.location.replace('file:///android_asset/cool_ml_NoNet.htm');" // ); view.loadUrl("file:///android_asset/cool_ml_NoNet.htm"); jsClass.failingUrl = failingUrl; jsClass.canelDialog(); // if( jsClass.builder != null ) // { // jsClass.builder.dismiss(); // } // WebBackForwardList Weblist = view.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , " onReceivedError Weblist size:" + // Weblist.getSize() + "Webview Cur:" + // Weblist.getCurrentIndex() ); flagError = true; flag = true; } public boolean shouldOverrideUrlLoading(WebView view, String url) {// 网页覆盖 MELOG.v("ME_RTFSC", "=== shouldOverrideUrlLoading === url: " + url); // WebBackForwardList Weblist = view.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , // " shouldOverrideUrlLoading Weblist size:" + Weblist.getSize() // + "Webview Cur:" + Weblist.getCurrentIndex() ); return super.shouldOverrideUrlLoading(view, url); } public void onPageFinished(WebView view, String url) {// 网页加载完毕 MELOG.v("ME_RTFSC", "=== onPageFinished === url: " + url); // WebBackForwardList Weblist = view.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , " onPageFinished Weblist size:" + // Weblist.getSize() + "Webview Cur:" + // Weblist.getCurrentIndex() ); super.onPageFinished(view, url); if (flagError == true && "file:///android_asset/cool_ml_NoNet.htm" .equals(url)) { // view.loadUrl( "javascript:document.body.innerHTML= ' ' " // ); // view.loadUrl( // "javascript:window.location.replace('file:///android_asset/cool_ml_NoNet.htm');" // ); // view.goBack(); view.clearHistory(); flagError = false; } if (true == isNeedClearHistory) { view.clearHistory(); isNeedClearHistory = false; } jsClass.canelDialog(); // Weblist = view.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , " onPageFinished Weblist size:" + // Weblist.getSize() + "Webview Cur:" + // Weblist.getCurrentIndex() ); } public void onPageStarted(WebView view, String url, Bitmap favicon) {// 网页开始加载 MELOG.v("ME_RTFSC", "=== onPageStarted === url: " + url); super.onPageStarted(view, url, favicon); // WebBackForwardList Weblist = view.copyBackForwardList(); // MELOG.v( "ME_RTFSC" , " onPageStarted Weblist size:" + // Weblist.getSize() + "Webview Cur:" + // Weblist.getCurrentIndex() ); } }); webView.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { return true; } }); } public void setConfigCallback(WindowManager windowManager) { try { Field field = WebView.class.getDeclaredField("mWebViewCore"); field = field.getType().getDeclaredField("mBrowserFrame"); field = field.getType().getDeclaredField("sConfigCallback"); field.setAccessible(true); Object configCallback = field.get(null); if (null == configCallback) { return; } field = field.getType().getDeclaredField("mWindowManager"); field.setAccessible(true); field.set(configCallback, windowManager); } catch (Exception e) { } } // MainActivity的mHandler handleMaessge 的处理项 public static final int openSubWebView = 1; public static final int subWebViewBackSoftKey = 2; public static final int mainWebViewBackSoftKey = 3; public static final int setBackgroundWithWallpaper = 4; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub // 0 --退出 ; 1--下载失败 switch (msg.what) { // 从MainView跳转到SubView case openSubWebView: { SubFrameWebview.setVisibility(View.VISIBLE); MainFrameWebview.setVisibility(View.INVISIBLE); String subUrl = (String) msg.obj; subWebView.clearView(); subJsCalss.setDialog(); isNeedClearHistory = true; subWebView.loadUrl(subUrl); } break; // MainWebView中返回软按键响应函数 case mainWebViewBackSoftKey: { MainWebViewOnBackListener(); } break; // subWebView中返回软按键响应函数 case subWebViewBackSoftKey: { SubWebViewOnBackListener(); } break; // 使用系统当前壁纸做为WEB页壁纸 case setBackgroundWithWallpaper: { WebView curWebview = (WebView) msg.obj; WallpaperManager wallpaperManager = WallpaperManager .getInstance(getApplicationContext()); // 获取壁纸管理器 Drawable wallpaperDrawable = wallpaperManager.getDrawable();// 获取当前壁纸 curWebview.setBackgroundColor(0); curWebview.setBackgroundDrawable(wallpaperDrawable); // curWebview.refreshDrawableState(); } break; default: break; } } }; }
19,321
0.690372
0.677686
557
33.105923
21.728649
88
false
false
0
0
0
0
0
0
3.583483
false
false
9
db82818380b372ad822de7aeee5e97e9f9fac988
26,456,998,577,899
d5d2d0214b961d58012c3faeeda46e7f44aa4b9c
/src/main/java/org/albertyu/service/ApiRequest.java
29992efd06b5fadb5b83946e628e5607a12d8b2f
[]
no_license
kbalbertyu/ArticleCrawler
https://github.com/kbalbertyu/ArticleCrawler
55f53ce25ed985f6809d6ae0ac021362e092339e
9ef95ecbcb1c2b21ac6809dd2472001b9251fec8
refs/heads/master
2021-12-27T10:26:32.611000
2019-08-11T23:44:42
2019-08-11T23:44:42
187,906,638
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.albertyu.service; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import org.albertyu.model.ApiResult; import org.albertyu.utils.Tools; import org.apache.commons.lang3.StringUtils; import org.jsoup.Connection; import org.jsoup.Connection.Method; import org.jsoup.Jsoup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * Api request handler communicates with remote server * @author <a href="mailto:kbalbertyu@gmail.com">Albert Yu</a> 2019/5/13 3:13 */ public class ApiRequest { private static final Logger LOGGER = LoggerFactory.getLogger(ApiRequest.class); private static final int MAX_REPEAT_TIMES = 3; public ApiResult get(String path) { return this.send(path, Method.GET, ""); } public ApiResult post(String path, String dataText) { return this.send(path, Method.POST, dataText); } private ApiResult send(String url, Method method, String dataText) { for (int i = 0; i < MAX_REPEAT_TIMES; i++) { try { Connection conn = Jsoup.connect(url).ignoreContentType(true) .method(method).timeout(60).maxBodySize(0); if (StringUtils.isNotBlank(dataText)) { conn.data("data", dataText); } String result = conn.execute().body(); ApiResult resultObj = JSON.parseObject(result, ApiResult.class); if (resultObj.getCode() == 1) { return resultObj; } LOGGER.error("Request result failed: {} -> {}", url, resultObj.getMessage()); break; } catch (IOException e) { LOGGER.error("Request result failed: {}", url, e); if (i < MAX_REPEAT_TIMES - 1) { Tools.sleep(5); } } catch (JSONException e) { LOGGER.error("Invalid json response: {}", url); } catch (Exception e) { LOGGER.error("Unexpected exception occurred while requesting: {}", url, e); return null; } } return null; } }
UTF-8
Java
2,204
java
ApiRequest.java
Java
[ { "context": "tes with remote server\n * @author <a href=\"mailto:kbalbertyu@gmail.com\">Albert Yu</a> 2019/5/13 3:13\n */\npublic class Ap", "end": 505, "score": 0.999929666519165, "start": 485, "tag": "EMAIL", "value": "kbalbertyu@gmail.com" }, { "context": "\n * @author <a href=\"mailto:kbalbertyu@gmail.com\">Albert Yu</a> 2019/5/13 3:13\n */\npublic class ApiRequest {\n", "end": 516, "score": 0.9998835921287537, "start": 507, "tag": "NAME", "value": "Albert Yu" } ]
null
[]
package org.albertyu.service; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import org.albertyu.model.ApiResult; import org.albertyu.utils.Tools; import org.apache.commons.lang3.StringUtils; import org.jsoup.Connection; import org.jsoup.Connection.Method; import org.jsoup.Jsoup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * Api request handler communicates with remote server * @author <a href="mailto:<EMAIL>"><NAME></a> 2019/5/13 3:13 */ public class ApiRequest { private static final Logger LOGGER = LoggerFactory.getLogger(ApiRequest.class); private static final int MAX_REPEAT_TIMES = 3; public ApiResult get(String path) { return this.send(path, Method.GET, ""); } public ApiResult post(String path, String dataText) { return this.send(path, Method.POST, dataText); } private ApiResult send(String url, Method method, String dataText) { for (int i = 0; i < MAX_REPEAT_TIMES; i++) { try { Connection conn = Jsoup.connect(url).ignoreContentType(true) .method(method).timeout(60).maxBodySize(0); if (StringUtils.isNotBlank(dataText)) { conn.data("data", dataText); } String result = conn.execute().body(); ApiResult resultObj = JSON.parseObject(result, ApiResult.class); if (resultObj.getCode() == 1) { return resultObj; } LOGGER.error("Request result failed: {} -> {}", url, resultObj.getMessage()); break; } catch (IOException e) { LOGGER.error("Request result failed: {}", url, e); if (i < MAX_REPEAT_TIMES - 1) { Tools.sleep(5); } } catch (JSONException e) { LOGGER.error("Invalid json response: {}", url); } catch (Exception e) { LOGGER.error("Unexpected exception occurred while requesting: {}", url, e); return null; } } return null; } }
2,188
0.588476
0.578947
62
34.548386
25.187475
93
false
false
0
0
0
0
0
0
0.758065
false
false
9
800b5165737eb954cb242cbb2e0ad8c62d8a49f7
7,756,711,002,018
ecc79aa0a64984f0fe3230dff1e3d0ccbb57616a
/src/xmlconverter/ui/components/MenuBar.java
e51bf05784ace3d8604cf3915674384f1ea85ef1
[]
no_license
carl-pagels/taxtableconverter
https://github.com/carl-pagels/taxtableconverter
ff82a260d7286338759c357a78ab4370d08f1898
1e70d75ed1ae24532c451dcc48142a79fe9badd2
refs/heads/master
2021-07-13T12:51:16.672000
2020-12-10T12:58:19
2020-12-10T12:58:19
227,064,598
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package xmlconverter.ui.components; import javax.swing.*; public class MenuBar extends JComponent { public MenuBar(ExitButton exitButton) { final Menu menu = new Menu(exitButton); this.setBounds(0, 0, 300, 20); this.add(menu); } }
UTF-8
Java
265
java
MenuBar.java
Java
[]
null
[]
package xmlconverter.ui.components; import javax.swing.*; public class MenuBar extends JComponent { public MenuBar(ExitButton exitButton) { final Menu menu = new Menu(exitButton); this.setBounds(0, 0, 300, 20); this.add(menu); } }
265
0.664151
0.637736
11
23.09091
17.936527
47
false
false
0
0
0
0
0
0
0.727273
false
false
9
b835d5b0e3d005cb327ddffb73a2d7fc8a127d9e
27,333,171,917,475
44b4e9d014ac42948eb05e5d8f13eac72bd8eb89
/src/isep/hem/servlets/package-info.java
e9dc97b03253d2ef867200558af58cd9faa03e36
[]
no_license
deadgoa7/WebTech
https://github.com/deadgoa7/WebTech
e6b7bc467186ffad4976d1aa66feb51bc05c739b
9c3e0a1753d81293d550425e89a8f519c1ab2dbc
refs/heads/master
2022-09-14T06:42:57.781000
2020-06-02T09:06:23
2020-06-02T09:06:23
266,779,712
0
1
null
false
2020-06-02T09:06:25
2020-05-25T12:58:17
2020-06-01T19:32:28
2020-06-02T09:06:24
3,066
0
1
0
Java
false
false
package isep.hem.servlets;
UTF-8
Java
26
java
package-info.java
Java
[]
null
[]
package isep.hem.servlets;
26
0.846154
0.846154
1
26
0
26
false
false
0
0
0
0
0
0
1
false
false
9
2a17fba0692d31b1075d980518b5e017711e2a76
31,250,182,060,674
8c84291cb5f785166df547b665c6b491772c05c7
/ps2_2.java
2c4b791876797441d15f44295e8f643899542a70
[]
no_license
amishapandey/p-h-a-codekatta-
https://github.com/amishapandey/p-h-a-codekatta-
ccce9295d0966e463e3d6cb57ffd32ea0f818bf6
42700d8a2e82735f3a394b3a0a71dba37ab52f49
refs/heads/master
2020-04-28T05:28:42.978000
2019-06-12T19:31:40
2019-06-12T19:31:40
175,021,862
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); int arr[]=new int[n]; int i; for(i=0;i<n;i++) arr[i]=sc.nextInt(); while(m>0){ int temp=arr[n-1]; for(i=n-2;i>=0;i--) { arr[i+1]=arr[i]; }arr[0]=temp; m--; } for(i=0;i<n;i++){ System.out.print(arr[i]); System.out.print(' '); } } }
UTF-8
Java
454
java
ps2_2.java
Java
[]
null
[]
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); int arr[]=new int[n]; int i; for(i=0;i<n;i++) arr[i]=sc.nextInt(); while(m>0){ int temp=arr[n-1]; for(i=n-2;i>=0;i--) { arr[i+1]=arr[i]; }arr[0]=temp; m--; } for(i=0;i<n;i++){ System.out.print(arr[i]); System.out.print(' '); } } }
454
0.519824
0.502203
26
16.461538
11.372134
41
false
false
0
0
0
0
0
0
1.884615
false
false
9
0a6e97a50ef731ac1ead174de1af0616475de608
8,890,582,304,092
3d49980a4766237462919859e21bdde6fa98ac8e
/src/playNestedClass/ShadowTest.java
f16dffa37a687693ff6fefa3758dcef60487de21
[]
no_license
sehramadhvi88/JavaExamplePractice
https://github.com/sehramadhvi88/JavaExamplePractice
2401d0f675b53722944acef97f2b44f65b9ebf20
bb67c5a9eb45ade03f120a2b866e292d4f4178bb
refs/heads/master
2020-04-28T08:01:30.696000
2019-03-12T01:29:10
2019-03-12T01:29:10
175,111,895
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package playNestedClass; public class ShadowTest { public static void main(String[] args) { // TODO Auto-generated method stub OuterClass outer=new OuterClass(); OuterClass.InnerClass inner=outer.new InnerClass(); inner.innerDisplayParamterize(); } }
UTF-8
Java
271
java
ShadowTest.java
Java
[]
null
[]
package playNestedClass; public class ShadowTest { public static void main(String[] args) { // TODO Auto-generated method stub OuterClass outer=new OuterClass(); OuterClass.InnerClass inner=outer.new InnerClass(); inner.innerDisplayParamterize(); } }
271
0.734317
0.734317
15
17.066668
18.408211
53
false
false
0
0
0
0
0
0
1.2
false
false
9
be13e6d4a6e461be34e379c47ad1cbe55a4c30fa
15,401,752,779,556
a78a4bb1457b30f1d4be065e79346bcfbea8d071
/javaPractice/src/main/java/test2/MasterClass.java
e89c9bd42bb45ca1ea159aa753ced1c54f3bb8ed
[]
no_license
pspawar18/javaPractice
https://github.com/pspawar18/javaPractice
14a9c1b34c2734d1880db2b0ab343d27207da7e6
c7716fdd4edd46462ed10e5c86265cb46298070c
refs/heads/master
2023-04-12T05:06:44.683000
2021-05-09T08:58:17
2021-05-09T08:58:17
365,708,678
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test2; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MasterClass { public static void main(String[] args) { Employee emp1 = new Employee(202, "Suraj", 12, "ABC"); Employee emp2 = new Employee(101, "Amol", 20, "PQR"); Employee emp3 = new Employee(506, "Pramod", 18, "XYZ"); List<Employee> empList = new ArrayList<Employee>(); empList.add(emp1); empList.add(emp2); empList.add(emp3); Collections.sort(empList); for (Employee employee : empList) { System.out.println(employee); } NameCompare nc = new NameCompare(); Collections.sort(empList, nc); System.out.println("---"); for (Employee employee : empList) { System.out.println(employee); } //System.out.println(empList); } }
UTF-8
Java
824
java
MasterClass.java
Java
[ { "context": "args) {\r\n\t\t\r\n\t\tEmployee emp1 = new Employee(202, \"Suraj\", 12, \"ABC\");\r\n\t\tEmployee emp2 = new Employee(101", "end": 221, "score": 0.9996635913848877, "start": 216, "tag": "NAME", "value": "Suraj" }, { "context": "12, \"ABC\");\r\n\t\tEmployee emp2 = new Employee(101, \"Amol\", 20, \"PQR\");\r\n\t\tEmployee emp3 = new Employee(506", "end": 278, "score": 0.9996327757835388, "start": 274, "tag": "NAME", "value": "Amol" }, { "context": "20, \"PQR\");\r\n\t\tEmployee emp3 = new Employee(506, \"Pramod\", 18, \"XYZ\");\r\n\t\t\r\n\t\tList<Employee> empList = new", "end": 337, "score": 0.9995905756950378, "start": 331, "tag": "NAME", "value": "Pramod" } ]
null
[]
package test2; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MasterClass { public static void main(String[] args) { Employee emp1 = new Employee(202, "Suraj", 12, "ABC"); Employee emp2 = new Employee(101, "Amol", 20, "PQR"); Employee emp3 = new Employee(506, "Pramod", 18, "XYZ"); List<Employee> empList = new ArrayList<Employee>(); empList.add(emp1); empList.add(emp2); empList.add(emp3); Collections.sort(empList); for (Employee employee : empList) { System.out.println(employee); } NameCompare nc = new NameCompare(); Collections.sort(empList, nc); System.out.println("---"); for (Employee employee : empList) { System.out.println(employee); } //System.out.println(empList); } }
824
0.644417
0.617718
34
22.235294
18.014795
57
false
false
0
0
0
0
0
0
2.352941
false
false
9
f623bcad56f847dc6e02ad0b6ec60b40d3bf800b
33,500,744,975,365
a2075d046250d6e8b27d69f1030142f0efdf3e2e
/lecture4-hw3/src/user/UserManager.java
b1fba2ca9a9df3271eb26f570dce523bffe8a994
[]
no_license
CosmicDust19/kodlama.io-javareactcamp
https://github.com/CosmicDust19/kodlama.io-javareactcamp
c42921845f3a1da52198ca6c59d0747af0bae50f
886bbae133dcf9739d8dda0471a20cfb9cb4952b
refs/heads/master
2023-08-18T02:22:23.016000
2021-10-04T11:40:26
2021-10-04T11:40:26
365,454,905
20
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package user; import log.Logger; import user.check.*; public class UserManager extends BaseUserManager { private UserCheckService checkService; public UserManager(UserCheckService checkService, Logger[] loggers) { super(loggers); this.checkService = checkService; } @Override public void save(User user) { if(checkService.checkIfRealPerson(user)) super.save(user); else System.out.println("Not a real person."); } }
UTF-8
Java
477
java
UserManager.java
Java
[]
null
[]
package user; import log.Logger; import user.check.*; public class UserManager extends BaseUserManager { private UserCheckService checkService; public UserManager(UserCheckService checkService, Logger[] loggers) { super(loggers); this.checkService = checkService; } @Override public void save(User user) { if(checkService.checkIfRealPerson(user)) super.save(user); else System.out.println("Not a real person."); } }
477
0.691824
0.691824
20
22.85
23.27504
73
false
false
0
0
0
0
0
0
0.45
false
false
9
cd8952f8ea0d36d62d02a45942037f070c818455
14,791,867,431,778
9c4450e31bbd822c3d5af2f76ae734c85f2129da
/src/main/java/com/aurospaces/neighbourhood/dao/TypeDao.java
ffa5c579b79182f44275b6f3af1195ef0856230a
[]
no_license
kotaiahandraju/School
https://github.com/kotaiahandraju/School
9f074879a353fd4fe3af0bc4514fbd687b2bbcb7
61d132f0c4ba5a806ef95db9855793adc37989bc
refs/heads/master
2021-04-29T11:42:35.653000
2018-07-19T10:17:22
2018-07-19T10:17:22
121,827,789
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.aurospaces.neighbourhood.dao; import java.util.List; import com.aurospaces.neighbourhood.bean.TypeBean; /** * @author sandhya * */ public interface TypeDao { boolean insertType(TypeBean objTypeBean); boolean updateType(TypeBean objTypeBean); List<TypeBean> getTypes(TypeBean objTypeBean, String likeSearch); TypeBean getType(TypeBean objTypeBean, String likeSearch); boolean deleteType(TypeBean objTypeBean); }
UTF-8
Java
446
java
TypeDao.java
Java
[ { "context": "paces.neighbourhood.bean.TypeBean;\n\n/**\n * @author sandhya\n *\n */\npublic interface TypeDao {\n\tboolean insert", "end": 153, "score": 0.9996044039726257, "start": 146, "tag": "USERNAME", "value": "sandhya" } ]
null
[]
/** * */ package com.aurospaces.neighbourhood.dao; import java.util.List; import com.aurospaces.neighbourhood.bean.TypeBean; /** * @author sandhya * */ public interface TypeDao { boolean insertType(TypeBean objTypeBean); boolean updateType(TypeBean objTypeBean); List<TypeBean> getTypes(TypeBean objTypeBean, String likeSearch); TypeBean getType(TypeBean objTypeBean, String likeSearch); boolean deleteType(TypeBean objTypeBean); }
446
0.775785
0.775785
20
21.299999
22.102262
66
false
false
0
0
0
0
0
0
0.75
false
false
9
fcfe9554a3be3ed2fe7881b2e7e19ee0f70c46ca
35,991,825,970,303
b69ca09d1535e604b60fdfee8db419cd6fc291bf
/Airport Managment System/src/airproject/application/Application.java
15ba9561c4d728355451c7c4e98257f549d2951e
[]
no_license
avyakta32/JAVA-Projects
https://github.com/avyakta32/JAVA-Projects
90c4bbea33b735f7e34d6dc481adb31994e99508
8d00042e43444b7d463d4d3a264f3b4ec4d31e86
refs/heads/master
2020-04-30T02:03:10.942000
2015-05-27T14:17:16
2015-05-27T14:17:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package airproject.application; import java.lang.reflect.InvocationTargetException; import airproject.controller.Controller; import airproject.model.Model; import airproject.view.View; public class Application { public static void main(String[] args) { // Initialise the model. Model.getInstance(); // Initialise the view. try { View view = new View(); new Controller(view); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } // Initialise the controller, links the model and the view. } }
UTF-8
Java
554
java
Application.java
Java
[]
null
[]
package airproject.application; import java.lang.reflect.InvocationTargetException; import airproject.controller.Controller; import airproject.model.Model; import airproject.view.View; public class Application { public static void main(String[] args) { // Initialise the model. Model.getInstance(); // Initialise the view. try { View view = new View(); new Controller(view); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } // Initialise the controller, links the model and the view. } }
554
0.741877
0.741877
23
23.086956
19.099085
64
false
false
0
0
0
0
0
0
1.565217
false
false
9
fc4ab0b5f04a4271112362fe55b14035ba6a1e02
37,726,992,749,098
0e83bf112d568e1f2fd0d0ca07de183a0119ee34
/后端/bookstore/src/main/java/com/whu/service/impl/BookService.java
5cabce86f78f0a3a21025ae6e1ff1ed1e56e8db3
[ "MIT" ]
permissive
banyingao/bookstore_vue
https://github.com/banyingao/bookstore_vue
e0060ee490ef8e324140f8f9073fd9071f128353
7e23b4e1ef29eca885828cca431276d0651ca880
refs/heads/main
2023-01-06T05:31:27.910000
2020-11-02T06:37:18
2020-11-02T06:37:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.whu.service.impl; // import com.sun.corba.se.impl.resolver.SplitLocalResolverImpl; import com.whu.mapper.IBookMapper; import com.whu.mapper.ICategoryMapper; import com.whu.pojo.Book; import com.whu.pojo.Category; import com.whu.service.IBookService; import java.util.List; public class BookService implements IBookService { ICategoryMapper categoryMapper; IBookMapper bookMapper; public void setCategoryMapper(ICategoryMapper categoryMapper) { this.categoryMapper = categoryMapper; } public void setBookMapper(IBookMapper bookMapper) { this.bookMapper = bookMapper; } @Override public List<Book> getAllBook() { List<Book> books =bookMapper.getAllBook(); return books; } @Override public List<Book> getByCategory(int category_id) { Category c=categoryMapper.getByCategory(category_id); List<Book> books =c.getBooks(); return books; } @Override public Book getById(int book_id) { return bookMapper.getById(book_id); } @Override public int add(Book book) { return bookMapper.add(book); } @Override public int update(Book book) { return bookMapper.update(book); } @Override public int delete(int book_id) { return bookMapper.delete(book_id); } }
UTF-8
Java
1,350
java
BookService.java
Java
[]
null
[]
package com.whu.service.impl; // import com.sun.corba.se.impl.resolver.SplitLocalResolverImpl; import com.whu.mapper.IBookMapper; import com.whu.mapper.ICategoryMapper; import com.whu.pojo.Book; import com.whu.pojo.Category; import com.whu.service.IBookService; import java.util.List; public class BookService implements IBookService { ICategoryMapper categoryMapper; IBookMapper bookMapper; public void setCategoryMapper(ICategoryMapper categoryMapper) { this.categoryMapper = categoryMapper; } public void setBookMapper(IBookMapper bookMapper) { this.bookMapper = bookMapper; } @Override public List<Book> getAllBook() { List<Book> books =bookMapper.getAllBook(); return books; } @Override public List<Book> getByCategory(int category_id) { Category c=categoryMapper.getByCategory(category_id); List<Book> books =c.getBooks(); return books; } @Override public Book getById(int book_id) { return bookMapper.getById(book_id); } @Override public int add(Book book) { return bookMapper.add(book); } @Override public int update(Book book) { return bookMapper.update(book); } @Override public int delete(int book_id) { return bookMapper.delete(book_id); } }
1,350
0.678519
0.678519
57
22.68421
19.713881
67
false
false
0
0
0
0
0
0
0.368421
false
false
9
fafcd9eed1aade617ee7bc1936c5067bf2570982
36,026,185,712,550
1d311dfbaff9c487e19a0b341ad3084ed6b01bce
/src/main/java/hash/LinkedList.java
bd416f0d8500c58582b42b26b98be2733201025f
[ "MIT" ]
permissive
MerrybyPractice/java_data_structures_and_algo
https://github.com/MerrybyPractice/java_data_structures_and_algo
aaa9ffb2caf0344d075b7b4f792dc988cc35779f
d674ac9ccdbebd12bc8a3f40e90a22ec034f2914
refs/heads/master
2020-05-14T19:34:57.802000
2019-08-13T03:05:11
2019-08-13T03:05:11
181,931,444
0
0
MIT
false
2019-08-13T03:05:12
2019-04-17T16:41:48
2019-06-06T17:43:24
2019-08-13T03:05:11
33,785
0
0
0
Java
false
false
package hash; import javax.annotation.Nullable; public class LinkedList { public class Node { public Hashtable.KeyValuePair keyValuePair; public Node reference; public Node(Hashtable.KeyValuePair keyValuePair, @Nullable Node reference) { this.keyValuePair = keyValuePair; this.reference = reference; } } private Node head; public Node getHead() { return head; } public LinkedList() { head = null; } public void insert(Hashtable.KeyValuePair keyValuePair) { Node current = head; this.head = new Node(keyValuePair, current); } public boolean includes(String key) { Node current = this.head; boolean inThisList = false; while ((current != null) && (inThisList == false)) { if (current.keyValuePair.key != key) { current = current.reference; } else if (current.keyValuePair.key == key) { inThisList = true; } } return inThisList; } public boolean includes(int key) { Node current = this.head; boolean inThisList = false; while ((current != null) && (inThisList == false)) { if (current.keyValuePair.intKey != key) { current = current.reference; } else if (current.keyValuePair.intKey == key) { inThisList = true; } } return inThisList; } }
UTF-8
Java
1,512
java
LinkedList.java
Java
[]
null
[]
package hash; import javax.annotation.Nullable; public class LinkedList { public class Node { public Hashtable.KeyValuePair keyValuePair; public Node reference; public Node(Hashtable.KeyValuePair keyValuePair, @Nullable Node reference) { this.keyValuePair = keyValuePair; this.reference = reference; } } private Node head; public Node getHead() { return head; } public LinkedList() { head = null; } public void insert(Hashtable.KeyValuePair keyValuePair) { Node current = head; this.head = new Node(keyValuePair, current); } public boolean includes(String key) { Node current = this.head; boolean inThisList = false; while ((current != null) && (inThisList == false)) { if (current.keyValuePair.key != key) { current = current.reference; } else if (current.keyValuePair.key == key) { inThisList = true; } } return inThisList; } public boolean includes(int key) { Node current = this.head; boolean inThisList = false; while ((current != null) && (inThisList == false)) { if (current.keyValuePair.intKey != key) { current = current.reference; } else if (current.keyValuePair.intKey == key) { inThisList = true; } } return inThisList; } }
1,512
0.556217
0.556217
67
21.567163
21.3627
84
false
false
0
0
0
0
0
0
0.343284
false
false
9
ff5eae65261d9fb2a104df9a078c8f61d699d923
27,273,042,395,895
13f4204f5174b91118f1b659fe46fcacb7e27a3a
/src/test/java/com/citytemperature/service/impl/MetaWeatherCityTemperatureServiceImplTest.java
9cd9429fa81c5c59ad93711bc0b75f0884603a0f
[]
no_license
santiagonbernardes/citytemperature
https://github.com/santiagonbernardes/citytemperature
2fdcfa7cd397074f020a41c6d661b8beddd709de
df0fc429cde84eb4b30cabe4e63072f64e648437
refs/heads/master
2023-06-24T21:27:51.748000
2021-06-20T23:53:21
2021-06-20T23:53:21
377,994,059
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.citytemperature.service.impl; import com.citytemperature.config.WebClientConfig; import com.citytemperature.domain.contract.CityTemperature; import com.citytemperature.domain.contract.Woeid; import com.citytemperature.domain.impl.MetaWeatherWoeidImpl; import com.citytemperature.exceptions.CityNotFoundException; import com.citytemperature.exceptions.CityTemperatureNotFoundException; import com.citytemperature.exceptions.MetaWeatherIntegrationException; import com.citytemperature.helpers.MockResponseHelper; import com.citytemperature.responses.MetaWeatherCityTemperatureResponseMock; import com.citytemperature.responses.MetaWeatherConsolidatedWeatherMock; import com.citytemperature.service.contract.CityTemperatureService; import com.citytemperature.service.contract.WoeidService; import com.fasterxml.jackson.databind.ObjectMapper; import okhttp3.mockwebserver.MockWebServer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.io.IOException; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class MetaWeatherCityTemperatureServiceImplTest { private MockWebServer mockServer; @Mock private WoeidService woeidServiceMock; private CityTemperatureService underTest; private MockResponseHelper helper; @BeforeEach void setupTestsVariables() throws IOException { this.mockServer = new MockWebServer(); this.mockServer.start(); final String baseUrl = String.format("http://%s:%s", mockServer.getHostName(), mockServer.getPort()); underTest = new MetaWeatherCityTemperatureServiceImpl( this.woeidServiceMock, WebClientConfig.buildWebClient(baseUrl, new ObjectMapper())); this.helper = new MockResponseHelper(); // sets a default behavior for this service, so I don't need to write it every time. final List<Woeid> defaultReturn = Collections.singletonList(new MetaWeatherWoeidImpl(484848, "City")); when(this.woeidServiceMock.findAllWoeidByCitiesName(any())).thenReturn(defaultReturn); } @AfterEach void shutdownServer() throws IOException { this.mockServer.shutdown(); } @Test void shouldThrowCityNotFoundExceptionWhenWoeidServiceDoesntReturnAnyWoeid() { when(this.woeidServiceMock.findAllWoeidByCitiesName(any())).thenReturn(Collections.emptyList()); assertThrows(CityNotFoundException.class, () -> this.underTest.findCityTemperature("Any")); } @Test void shouldTakeTheFirstWoeidReturnedByWoeidServiceAndUseItsIdToSearchForTemperatures() { final MetaWeatherWoeidImpl firstInList = spy(new MetaWeatherWoeidImpl(1, "City")); final MetaWeatherWoeidImpl secondInList = spy(new MetaWeatherWoeidImpl(2, "Any")); final List<Woeid> returnedWoeid = Arrays.asList(firstInList, secondInList); when(this.woeidServiceMock.findAllWoeidByCitiesName(any())).thenReturn(returnedWoeid); final MetaWeatherConsolidatedWeatherMock returned = new MetaWeatherConsolidatedWeatherMock(LocalDate.now(), BigDecimal.valueOf(27.8)); this.mockServer.enqueue( helper.getMockResponseStatusCode200( new MetaWeatherCityTemperatureResponseMock( Collections.singletonList(returned), "Test"))); this.underTest.findCityTemperature("Any"); verify(firstInList, times(1)).getId(); verify(secondInList, never()).getId(); } @Test void shouldReturnOldestTheCityTemperatureGivenItsApplicableDate() { final MetaWeatherConsolidatedWeatherMock expected = new MetaWeatherConsolidatedWeatherMock(LocalDate.now(), BigDecimal.valueOf(27.8)); final List<MetaWeatherConsolidatedWeatherMock> returnedTemperature = Arrays.asList( new MetaWeatherConsolidatedWeatherMock( LocalDate.now().plusDays(5), BigDecimal.valueOf(30.)), expected, new MetaWeatherConsolidatedWeatherMock( LocalDate.now().plusDays(2), BigDecimal.valueOf(29.4)), new MetaWeatherConsolidatedWeatherMock( LocalDate.now().plusDays(3), BigDecimal.valueOf(29.7))); mockServer.enqueue( helper.getMockResponseStatusCode200( new MetaWeatherCityTemperatureResponseMock(returnedTemperature, "Test"))); final CityTemperature actual = underTest.findCityTemperature("Any"); assertEquals(expected.getApplicableDate(), actual.getDateThisTemperatureIsExpected()); assertEquals(0, expected.getTheTemp().compareTo(actual.getTemperatureInCelsius())); } @Test void shouldRaiseCityTemperatureNotFoundExceptionWhenNoConsolidatedWeatherIsFound() { mockServer.enqueue( helper.getMockResponseStatusCode200( new MetaWeatherCityTemperatureResponseMock(Collections.emptyList(), "Test"))); assertThrows( CityTemperatureNotFoundException.class, () -> this.underTest.findCityTemperature("Any")); } @Test void shouldRaiseCityTemperatureNotFoundExceptionWhenConsolidatedWeatherIsNull() { mockServer.enqueue( helper.getMockResponseStatusCode200( new MetaWeatherCityTemperatureResponseMock(null, "Test"))); assertThrows( CityTemperatureNotFoundException.class, () -> this.underTest.findCityTemperature("Any")); } @Test void shouldRaiseCityTemperatureNotFoundExceptionWhenResponseBodyIsNull() { mockServer.enqueue(helper.getMockResponseStatusCode200(null)); assertThrows( CityTemperatureNotFoundException.class, () -> this.underTest.findCityTemperature("Any")); } @Test void shouldRaiseCityTemperatureNotFoundExceptionWhenMetaWeatherReturnsClientErrorStatusCode() { // Im returning a valid body so I don't get fooled and the exception is raised because the // response is null. mockServer.enqueue( helper.getMockResponseWithStatusCodeAndBody( 404, new MetaWeatherCityTemperatureResponseMock(Collections.emptyList(), "Test"))); assertThrows( CityTemperatureNotFoundException.class, () -> this.underTest.findCityTemperature("Any")); } @Test void shouldRaiseCityMetaWeatherIntegrationExceptionWhenMetaWeatherReturnsServerErrorStatusCode() { mockServer.enqueue(helper.getMockResponseWithStatusCodeAndBody(500, null)); assertThrows( MetaWeatherIntegrationException.class, () -> this.underTest.findCityTemperature("Any")); } }
UTF-8
Java
6,959
java
MetaWeatherCityTemperatureServiceImplTest.java
Java
[]
null
[]
package com.citytemperature.service.impl; import com.citytemperature.config.WebClientConfig; import com.citytemperature.domain.contract.CityTemperature; import com.citytemperature.domain.contract.Woeid; import com.citytemperature.domain.impl.MetaWeatherWoeidImpl; import com.citytemperature.exceptions.CityNotFoundException; import com.citytemperature.exceptions.CityTemperatureNotFoundException; import com.citytemperature.exceptions.MetaWeatherIntegrationException; import com.citytemperature.helpers.MockResponseHelper; import com.citytemperature.responses.MetaWeatherCityTemperatureResponseMock; import com.citytemperature.responses.MetaWeatherConsolidatedWeatherMock; import com.citytemperature.service.contract.CityTemperatureService; import com.citytemperature.service.contract.WoeidService; import com.fasterxml.jackson.databind.ObjectMapper; import okhttp3.mockwebserver.MockWebServer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.io.IOException; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class MetaWeatherCityTemperatureServiceImplTest { private MockWebServer mockServer; @Mock private WoeidService woeidServiceMock; private CityTemperatureService underTest; private MockResponseHelper helper; @BeforeEach void setupTestsVariables() throws IOException { this.mockServer = new MockWebServer(); this.mockServer.start(); final String baseUrl = String.format("http://%s:%s", mockServer.getHostName(), mockServer.getPort()); underTest = new MetaWeatherCityTemperatureServiceImpl( this.woeidServiceMock, WebClientConfig.buildWebClient(baseUrl, new ObjectMapper())); this.helper = new MockResponseHelper(); // sets a default behavior for this service, so I don't need to write it every time. final List<Woeid> defaultReturn = Collections.singletonList(new MetaWeatherWoeidImpl(484848, "City")); when(this.woeidServiceMock.findAllWoeidByCitiesName(any())).thenReturn(defaultReturn); } @AfterEach void shutdownServer() throws IOException { this.mockServer.shutdown(); } @Test void shouldThrowCityNotFoundExceptionWhenWoeidServiceDoesntReturnAnyWoeid() { when(this.woeidServiceMock.findAllWoeidByCitiesName(any())).thenReturn(Collections.emptyList()); assertThrows(CityNotFoundException.class, () -> this.underTest.findCityTemperature("Any")); } @Test void shouldTakeTheFirstWoeidReturnedByWoeidServiceAndUseItsIdToSearchForTemperatures() { final MetaWeatherWoeidImpl firstInList = spy(new MetaWeatherWoeidImpl(1, "City")); final MetaWeatherWoeidImpl secondInList = spy(new MetaWeatherWoeidImpl(2, "Any")); final List<Woeid> returnedWoeid = Arrays.asList(firstInList, secondInList); when(this.woeidServiceMock.findAllWoeidByCitiesName(any())).thenReturn(returnedWoeid); final MetaWeatherConsolidatedWeatherMock returned = new MetaWeatherConsolidatedWeatherMock(LocalDate.now(), BigDecimal.valueOf(27.8)); this.mockServer.enqueue( helper.getMockResponseStatusCode200( new MetaWeatherCityTemperatureResponseMock( Collections.singletonList(returned), "Test"))); this.underTest.findCityTemperature("Any"); verify(firstInList, times(1)).getId(); verify(secondInList, never()).getId(); } @Test void shouldReturnOldestTheCityTemperatureGivenItsApplicableDate() { final MetaWeatherConsolidatedWeatherMock expected = new MetaWeatherConsolidatedWeatherMock(LocalDate.now(), BigDecimal.valueOf(27.8)); final List<MetaWeatherConsolidatedWeatherMock> returnedTemperature = Arrays.asList( new MetaWeatherConsolidatedWeatherMock( LocalDate.now().plusDays(5), BigDecimal.valueOf(30.)), expected, new MetaWeatherConsolidatedWeatherMock( LocalDate.now().plusDays(2), BigDecimal.valueOf(29.4)), new MetaWeatherConsolidatedWeatherMock( LocalDate.now().plusDays(3), BigDecimal.valueOf(29.7))); mockServer.enqueue( helper.getMockResponseStatusCode200( new MetaWeatherCityTemperatureResponseMock(returnedTemperature, "Test"))); final CityTemperature actual = underTest.findCityTemperature("Any"); assertEquals(expected.getApplicableDate(), actual.getDateThisTemperatureIsExpected()); assertEquals(0, expected.getTheTemp().compareTo(actual.getTemperatureInCelsius())); } @Test void shouldRaiseCityTemperatureNotFoundExceptionWhenNoConsolidatedWeatherIsFound() { mockServer.enqueue( helper.getMockResponseStatusCode200( new MetaWeatherCityTemperatureResponseMock(Collections.emptyList(), "Test"))); assertThrows( CityTemperatureNotFoundException.class, () -> this.underTest.findCityTemperature("Any")); } @Test void shouldRaiseCityTemperatureNotFoundExceptionWhenConsolidatedWeatherIsNull() { mockServer.enqueue( helper.getMockResponseStatusCode200( new MetaWeatherCityTemperatureResponseMock(null, "Test"))); assertThrows( CityTemperatureNotFoundException.class, () -> this.underTest.findCityTemperature("Any")); } @Test void shouldRaiseCityTemperatureNotFoundExceptionWhenResponseBodyIsNull() { mockServer.enqueue(helper.getMockResponseStatusCode200(null)); assertThrows( CityTemperatureNotFoundException.class, () -> this.underTest.findCityTemperature("Any")); } @Test void shouldRaiseCityTemperatureNotFoundExceptionWhenMetaWeatherReturnsClientErrorStatusCode() { // Im returning a valid body so I don't get fooled and the exception is raised because the // response is null. mockServer.enqueue( helper.getMockResponseWithStatusCodeAndBody( 404, new MetaWeatherCityTemperatureResponseMock(Collections.emptyList(), "Test"))); assertThrows( CityTemperatureNotFoundException.class, () -> this.underTest.findCityTemperature("Any")); } @Test void shouldRaiseCityMetaWeatherIntegrationExceptionWhenMetaWeatherReturnsServerErrorStatusCode() { mockServer.enqueue(helper.getMockResponseWithStatusCodeAndBody(500, null)); assertThrows( MetaWeatherIntegrationException.class, () -> this.underTest.findCityTemperature("Any")); } }
6,959
0.776979
0.769938
157
43.324841
31.537304
100
false
false
0
0
0
0
89
0.076735
0.687898
false
false
9
e59bdc1a9d969ab85993c22dc1efcbd82b052ed3
27,273,042,395,430
cd45d44492aac1e18ce233f4015ba432261fbe0a
/mylibrary/src/main/java/com/oraro/listener/IUavInfoListener.java
6d2d1afc6d817f9edf8eed9b2ca43baecaf53b39
[]
no_license
wenjiang152385/MyApplicationno
https://github.com/wenjiang152385/MyApplicationno
5429933d41a7c349ca4a6cf91a12c4962325fec4
3c737c5cb0a5805b61bc7372015a44503226f71d
refs/heads/master
2021-01-11T19:54:16.986000
2017-01-19T06:23:43
2017-01-19T06:23:43
79,422,426
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.oraro.listener; import com.ceewa.entity.model.UAVInfo; /** * Created by Administrator on 2016/12/9 0009. * * @author * 获取主帧里的飞机的信息回调 */ public interface IUavInfoListener { /** * 无人机信息的回调(主帧信息) 参数: uavInfo - 主帧信息 另请参阅: UAVInfo * @param uavInfo */ void uavInfolistener(UAVInfo uavInfo); void resultCodelistener(String s, String s1); }
UTF-8
Java
473
java
IUavInfoListener.java
Java
[]
null
[]
package com.oraro.listener; import com.ceewa.entity.model.UAVInfo; /** * Created by Administrator on 2016/12/9 0009. * * @author * 获取主帧里的飞机的信息回调 */ public interface IUavInfoListener { /** * 无人机信息的回调(主帧信息) 参数: uavInfo - 主帧信息 另请参阅: UAVInfo * @param uavInfo */ void uavInfolistener(UAVInfo uavInfo); void resultCodelistener(String s, String s1); }
473
0.640199
0.610422
22
17.318182
15.783727
51
false
false
0
0
0
0
0
0
0.227273
false
false
9
8945cbda6355b413a315fddf6963f60bed7d98b4
36,112,085,062,734
a55a5fd9337709c10270f734828dd271c118afcd
/sql2xml/src/gudusoft/gsqlparser/sql2xml/model/dispatch_clause.java
80cf2db56a402894348fc1a187dd40a021e0b3d3
[ "Apache-2.0" ]
permissive
sqlparser/sql2xml
https://github.com/sqlparser/sql2xml
321653c4b136acf00b64f314e90253159e1fe6f8
e8e336923b11951e03fe50b182752012e7e8b481
refs/heads/master
2021-01-01T17:28:37.685000
2014-01-10T10:51:42
2014-01-10T10:51:42
14,269,568
6
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package gudusoft.gsqlparser.sql2xml.model; public class dispatch_clause { }
UTF-8
Java
79
java
dispatch_clause.java
Java
[]
null
[]
package gudusoft.gsqlparser.sql2xml.model; public class dispatch_clause { }
79
0.78481
0.772152
7
10.285714
16.077618
42
false
false
0
0
0
0
0
0
0.142857
false
false
9
33a225f26f669adac7e6124ee3bee8cbeb66dff2
36,532,991,852,427
108b0b5771fd069404cb6be46d03c317cc40daee
/src/Test/Print1.java
4e4c52957d7239794018edf94e0464a9453e7382
[]
no_license
yue980009351/Study
https://github.com/yue980009351/Study
40fcd72de44e37f1b063756badad8058f1354ca8
4327fc60502d7cbc16264b851fe6eeb5e17ee4d3
refs/heads/master
2020-04-05T02:30:34.903000
2018-11-07T02:35:35
2018-11-07T02:35:35
156,479,584
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Test; import java.util.Scanner; /** *@Date 2018/7/18 16:18 * 1.利用for循环打印如下格式的程序 * 1 * 22 * 333 * 4444 * 55555 **/ public class Print1 { public static void main(String[] args) { for (int i=1;i<=5;i++) { for(int j=0;j<i;j++) { System.out.print(i); } System.out.println(""); } } }
UTF-8
Java
399
java
Print1.java
Java
[]
null
[]
package Test; import java.util.Scanner; /** *@Date 2018/7/18 16:18 * 1.利用for循环打印如下格式的程序 * 1 * 22 * 333 * 4444 * 55555 **/ public class Print1 { public static void main(String[] args) { for (int i=1;i<=5;i++) { for(int j=0;j<i;j++) { System.out.print(i); } System.out.println(""); } } }
399
0.479893
0.396783
24
14.583333
12.144671
44
false
false
0
0
0
0
0
0
0.333333
false
false
9
9078f5c43f7b943b6153a8529d3f8983c71c42e4
39,522,289,087,396
58c3010c3855fa3b9c6a279fbe39c5c0c8ff042a
/Projects/Graduation Project/src/main/java/yu_cse/graduation_project_edit/activities/LoginMainActivity.java
f047330fef20140dca9be23e81e41dd6b3f6dd72
[]
no_license
mgu1206/Extra_Information
https://github.com/mgu1206/Extra_Information
df5fc435a427f6a5ffe77d039f722e1e6bd01041
72d7a7bf2f84a3ace0e77c792950d68bc370e3b6
refs/heads/master
2021-01-10T06:29:11.038000
2016-03-05T07:41:04
2016-03-05T07:41:04
53,189,746
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package yu_cse.graduation_project_edit.activities; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.PointF; import android.graphics.drawable.AnimationDrawable; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.os.Message; import android.os.Vibrator; import android.os.Handler; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.jiahuan.svgmapview.SVGMapView; import com.jiahuan.svgmapview.SVGMapViewListener; import com.jiahuan.svgmapview.overlay.SVGMapLocationOverlay; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.concurrent.ExecutionException; import de.uvwxy.footpath.core.StepDetection; import de.uvwxy.footpath.core.StepTrigger; import yu_cse.graduation_project_edit.R; import yu_cse.graduation_project_edit.location.BuildingListSet; import yu_cse.graduation_project_edit.location.GetMapNameText; import yu_cse.graduation_project_edit.location.GetLocation; import yu_cse.graduation_project_edit.util.AssetsHelper; import yu_cse.graduation_project_edit.util.PhpExcute; import yu_cse.graduation_project_edit.util.TaskRemoveCheckService; public class LoginMainActivity extends Activity implements AdapterView.OnItemSelectedListener, SensorEventListener, View.OnClickListener { final Context context = this; final float MAX_ZOOM = 3.0f; //최대 줌 배율 private float presuureValue; private LocationRefresh locationRefresh = null; private MapFinder mapFinder; private int currentPosX = 0, currentPosY = 0, currentDirection = 0, previousPosX = 0, previousPosY = 0, previousDirection = 0, pPreviousPosX = 0, pPreviousPosY = 0, pPreviousDirection = 0, tempPosX = 0, tempPosY = 0, overPosCnt = 0, isItReverse = 0; private SensorManager m_sensor_manager; private Sensor m_acc_sensor, m_mag_sensor, preSensor; private float[] m_acc_data = null, m_mag_data = null; private float[] m_rotation = new float[9]; private float[] m_result_data = new float[3]; public GetLocation getLocation; private PhpExcute phpExcute; private SVGMapView mapView; //지도가 표현될 커스텀 뷰 private SVGMapLocationOverlay locationOverlay; //위치가 포현될 오버레이 private Vibrator buttonVibe; private boolean isLocationRef = false, isItPressSensor = false; //현재위치가 갱신 되고 있는지 여부를 저장하는 불린값 private ImageButton showMyLocation, showMyFreind, editInformation, delAccount; private Intent activityChangeIntent, intent; // 인텐트 private Intent service; private String session, currentMap = ""; public TextView mapTextView; private JSONObject jsonObject, jo; private JSONArray jsonArray; public PositionSet positionSet; public PositionSet tempPos; private Handler handler; private Handler uiHandler; boolean checkAutoLogin, isMapExist; private ImageView locationIconOff, locationIconOn, pressSensorIcon; ArrayList<PositionSet> tempposi; GetMapNameText getMapNameText; Message msg, uiChMsg, altiMsg; private StepDetection stepDetection; private StepTrigger stepTrigger; private Spinner mapListSpinner; private String preCurrentMap = ""; ArrayList<String> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_main); getMapNameText = new GetMapNameText(); SharedPreferences temp = getSharedPreferences("sessinInfo", MODE_PRIVATE); SharedPreferences pref = getSharedPreferences("loginInfo", MODE_PRIVATE); checkAutoLogin = pref.getBoolean("isItAutoLogin", false); if (checkAutoLogin) { session = pref.getString("mem_id", ""); //이전 액티비티에서 세션값을 넘겨 받음(로그인 상태) } else { session = temp.getString("session", ""); } mapListSpinner = (Spinner) findViewById(R.id.mapList); service = new Intent(this, TaskRemoveCheckService.class); service.putExtra("session", session); service.putExtra("isAutoLogin", checkAutoLogin); startService(service); pressSensorIcon = (ImageView) findViewById(R.id.pressSensorIcon); mapTextView = (TextView) findViewById(R.id.mapNameTextView); m_sensor_manager = (SensorManager) getSystemService(SENSOR_SERVICE); m_acc_sensor = m_sensor_manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); m_mag_sensor = m_sensor_manager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); boolean test = false; /** * 기압센서 사용가능한지 확인. */ if (m_sensor_manager.getDefaultSensor(Sensor.TYPE_PRESSURE) != null) { preSensor = m_sensor_manager.getDefaultSensor(Sensor.TYPE_PRESSURE); isItPressSensor = true; mapListSpinner.setVisibility(View.INVISIBLE); pressSensorIcon.setImageResource(R.drawable.circle_green); Toast.makeText(this, "기압센서로 층을 구분합니다.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "해당기기엔 기압센서가 없습니다.\n맵뷰 우측 상단에서 지도 선택 가능합니다.", Toast.LENGTH_SHORT).show(); getTitleList(); isItPressSensor = false; pressSensorIcon.setImageResource(R.drawable.circle_red); mapListSpinner.setVisibility(View.VISIBLE); } tempposi = new ArrayList<>(); showMyFreind = (ImageButton) findViewById(R.id.fr_loc_bt); showMyFreind.setOnClickListener(this); // 버튼 클릭 리스너 등록(아래동일) showMyLocation = (ImageButton) findViewById(R.id.my_loc_bt); showMyLocation.setOnClickListener(this); editInformation = (ImageButton) findViewById(R.id.edit_info_bt); editInformation.setOnClickListener(this); delAccount = (ImageButton) findViewById(R.id.del_account_bt); delAccount.setOnClickListener(this); mapView = (SVGMapView) findViewById(R.id.map_view); buttonVibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); locationOverlay = new SVGMapLocationOverlay(mapView); //locationOveray 객체를 맵뷰에 등록 locationOverlay.setMode(SVGMapLocationOverlay.MODE_NORMAL); locationIconOff = (ImageView) findViewById(R.id.loc_icon_off); locationIconOn = (ImageView) findViewById(R.id.loc_icon_on); locationIconOn.setImageResource(R.drawable.my_blinking_drawable); AnimationDrawable frameAnimation = (AnimationDrawable) locationIconOn.getDrawable(); frameAnimation.start(); locationIconOn.setVisibility(View.INVISIBLE); locationIconOff.setVisibility(View.VISIBLE); getMapNameText = new GetMapNameText(); stepTrigger = new StepTrigger() { @Override public void trigger(long now_ms, double compDir) { } @Override public void dataHookAcc(long now_ms, double x, double y, double z) { } @Override public void dataHookComp(long now_ms, double x, double y, double z) { } @Override public void timedDataHook(long now_ms, double[] acc, double[] comp) { } }; stepDetection = new StepDetection(this, stepTrigger, 0.31, 1.4, 250); handler = new MyHandler(this); uiHandler = new UiChagneHandler(this); } class PositionSet { public int pos = 0; public int pos_x = 0; public int pos_y = 0; public int cnt = 1; } private static class MyHandler extends Handler { /** * 외부 쓰레드에서 액티비티UI변경을 위한 핸들러 */ private final WeakReference<LoginMainActivity> mActivity; //this.ob public MyHandler(LoginMainActivity activity) { mActivity = new WeakReference<LoginMainActivity>(activity); } @Override public void handleMessage(Message msg) { this.obtainMessage(); LoginMainActivity activity = mActivity.get(); if (activity != null) { activity.mapTextView.setText(String.valueOf(msg.obj)); } } } private static class UiChagneHandler extends Handler { /** * 외부 쓰레드에서 액티비티UI변경을 위한 핸들러 */ private final WeakReference<LoginMainActivity> mActivity; //this.ob public UiChagneHandler(LoginMainActivity activity) { mActivity = new WeakReference<LoginMainActivity>(activity); } @Override public void handleMessage(Message msg) { this.obtainMessage(); LoginMainActivity activity = mActivity.get(); if (activity != null) { if (msg.arg1 == 1) { activity.locationIconOn.setVisibility(View.VISIBLE); activity.locationIconOff.setVisibility(View.INVISIBLE); } else { } } } } public void onAccuracyChanged(Sensor sensor, int accuracy) { } public void onSensorChanged(SensorEvent event) { float var0 = event.values[0]; if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { // 가속 센서가 전달한 데이터인 경우 // 수치 데이터를 복사한다. m_acc_data = event.values.clone(); } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { // 자기장 센서가 전달한 데이터인 경우 // 수치 데이터를 복사한다. m_mag_data = event.values.clone(); } // 데이터가 존재하는 경우 if (m_acc_data != null && m_mag_data != null) { SensorManager.getRotationMatrix(m_rotation, null, m_acc_data, m_mag_data); SensorManager.getOrientation(m_rotation, m_result_data); String str; m_result_data[0] = (float) Math.toDegrees(m_result_data[0]); if (m_result_data[0] < 0) m_result_data[0] += 360; str = "azimuth(z) : " + (int) m_result_data[0]; } if (event.sensor.getType() == Sensor.TYPE_PRESSURE) { presuureValue = var0; //altituteTextView.setText(String.valueOf(var0)); //mapTextView.setText(String.valueOf(var0)); } } private int getDirection() { /** * 0~360도를 4개의 범위로 나누어서 * 1~4의 정수 값으로 반환 */ int azimuth = (int) m_result_data[0]; int direction; if (((315 <= azimuth) && (azimuth < 360)) && ((0 <= azimuth) && (azimuth < 45))) { direction = 1; } else if ((45 <= azimuth) && (azimuth < 135)) { direction = 2; } else if ((135 <= azimuth) && (azimuth < 225)) { direction = 3; } else if ((225 <= azimuth) && (azimuth < 315)) { direction = 4; } else direction = -1; return direction; } private double calDistance(int cPosX, int pPosX, int cPosY, int pPosY) { /** * 상동하나 두 지점의 거리를 구하는 함수 */ double dist; dist = Math.sqrt(Math.pow(pPosX - cPosX, 2) + Math.pow(pPosY - cPosY, 2)); return dist; } private double calDistance(int cPosX, int cPosY) { /** * 상동하나 두 지점의 거리를 구하는 함수 */ double dist; dist = Math.sqrt(Math.pow(cPosX, 2) + Math.pow(cPosY, 2)); return dist; } public static int f_direct(int x1, int y1, int x2, int y2) { ////이전전,이전 좌표를 통해 방향성 구성 int lx1, ly1; int direct_point = 0; lx1 = x2 - x1; ly1 = y2 - y1; if (lx1 > 0) { if (ly1 > 0) { direct_point = 1; // 오른쪽 위 } else if (ly1 == 0) { direct_point = 2; // 오른쪽 } else if (ly1 < 0) { direct_point = 3; // 오른쪽 밑 } } else if (lx1 == 0) { if (ly1 < 0) { direct_point = 4; // 밑 } else if (ly1 == 0) { //direct_point=9;// (0,0) 그대로 다시 측정 } else if (ly1 > 0) direct_point = 8; // 위 } else if (lx1 < 0) { if (ly1 > 0) { direct_point = 7; // 왼쪽 위 } else if (ly1 == 0) { direct_point = 6; // 왼쪽 } else if (ly1 < 0) { direct_point = 5; // 왼쪽 밑 } } return direct_point; } public static int s_direct(int x1, int y1, int x2, int y2, int x3, int y3, int direct_point) { //이전전,이전, 현재 좌표 들의 각도 구하여 방향성 double lx1, ly1, lx2, ly2; lx1 = x2 - x1; //두점을 이은 직선의 길이 구하기 ly1 = y2 - y1; lx2 = x2 - x3; ly2 = y2 - y3; double inner = (lx1 * lx2 + ly1 * ly2); //내적 double i1 = Math.sqrt(lx1 * lx1 + ly1 * ly1); //벡터 정규화 double i2 = Math.sqrt(lx2 * lx2 + ly2 * ly2); //벡터 정규화 lx1 = (lx1 / i1); //단위 벡터 ly1 = (ly1 / i1); lx2 = (lx2 / i2); ly2 = (ly2 / i2); inner = (lx1 * lx2 + ly1 * ly2); //내적 다시 구하기 double result = Math.acos(inner) * 180 / (Math.PI); //각도 구하기 if (lx1 > lx2) result = 360 - result; //360도 까지 표현 if (result >= 360) result = result - 360; //360도 이상일 시 각도를 재구성 if (result >= 0 && result <= 30) direct_point = direct_point + 4; //방향 재구성 else if (result > 30 && result <= 60) direct_point = direct_point - 1; else if (result > 60 && result <= 105) direct_point = direct_point - 2; else if (result > 105 && result <= 150) direct_point = direct_point - 3; else if (result > 150 && result <= 195) ; else if (result > 195 && result <= 240) direct_point = direct_point + 3; else if (result > 240 && result <= 285) direct_point = direct_point + 2; else if (result > 285 && result <= 330) direct_point = direct_point + 1; else if (result > 330 && result <= 360) direct_point = direct_point - 4; if (direct_point <= 0) direct_point = direct_point + 8; //8방향 설정 else if (direct_point > 8) direct_point = direct_point - 8; return direct_point; } private void positionWeightor() { /** * 각 위치들은 결과에서 얼마만큼 중복되어 나타났는지 cnt의 값을 가지고 이를 기준으로 소팅됨. * * 어느정도 까지의 결과들에서 cnt를 모두 합하여 이를 100으로 보고 각 위치마다 cnt를 기준으로 * * 가중치(확률)을 곱하여 간단하게 위치를 보정. */ float cntSum = 0; float persenTage; float temp[] = new float[10]; tempPos = new PositionSet(); for (int i = 0; i < 10; i++) { temp[i] = 0f; } sortResultPositions(); try { Comparator<PositionSet> comparator = new Comparator<PositionSet>() { @Override public int compare(PositionSet lhs, PositionSet rhs) { return (lhs.cnt > rhs.cnt ? -1 : (lhs.cnt == rhs.cnt ? 0 : 1)); } }; Collections.sort(tempposi, comparator); //중복된 결과가 많은 순(cnt값)으로 정렬 for (int i = 0; i < tempposi.size(); i++) { cntSum += tempposi.get(i).cnt; } persenTage = 1 / cntSum; for (int i = 0; i < tempposi.size(); i++) { temp[i] = tempposi.get(i).cnt * persenTage; } for (int i = 0; i < tempposi.size(); i++) { tempPos.pos_x += (int) (((float) tempposi.get(i).pos_x * temp[i])); } for (int i = 0; i < tempposi.size(); i++) { tempPos.pos_y += (int) (((float) tempposi.get(i).pos_y * temp[i])); } } catch (NullPointerException e) { e.printStackTrace(); } } private void setMyLocation(String map, int posx, int posy) { PhpExcute phpExcute1 = new PhpExcute(); try { String result = phpExcute1.execute("http://minsdatanetwork.iptime.org:82/iptsPhp/locationService/insertlocation.php?mem_id=" + session + "&map=" + map + "&posx=" + posx + "&posy=" + posy).get(); phpExcute1.cancel(true); } catch (NullPointerException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } class MapFinder extends Thread { private boolean mapRefState; //Message msg1 = handler.obtainMessage(); //Message msg = handler.obtainMessage(); //Message mapMessage = mapHandler.obtainMessage(); String[] temp; public void setRunningState(boolean state) { mapRefState = state; } public void run() { //if(mapRefState) msg1.arg1 = 3; //else msg1.arg1 = 4; //handler.sendMessage(msg1); while (mapRefState) { altiMsg = new Message(); altiMsg = uiHandler.obtainMessage(); msg = new Message(); msg = handler.obtainMessage(); uiChMsg = new Message(); uiChMsg = uiHandler.obtainMessage(); String mapName; PhpExcute mPhpExcute = new PhpExcute(); try { mapName = mPhpExcute.execute("http://minsdatanetwork.iptime.org:82/iptsPhp/locationService/getMapbyPress.php?press=" + presuureValue).get(); temp = mapName.split(","); mapName = temp[1]; altiMsg.arg1 = 2; altiMsg.obj = temp[0]; uiHandler.sendMessage(altiMsg); //mapMessage.arg1 = 5; // mapMessage.obj = stepDetection.getstepCount(); // mapHandler.sendMessage(mapMessage); if (!mapName.equals("") && !currentMap.equals(mapName)) { isMapExist = loadIndoorMap(mapName); currentMap = mapName; } if (!isMapExist) { isLocationRef = false; setRunningState(false); currentMap = ""; } if (isMapExist) { msg.arg1 = 0; /** * currentMap 변수가 널일경우를 대비 * */ try { msg.obj = getMapNameText.getMapName(currentMap); } catch (NullPointerException e) { e.printStackTrace(); } //handler.dispatchMessage(msg); handler.sendMessage(msg); uiChMsg.arg1 = 1; uiHandler.sendMessage(uiChMsg); if (!locationRefresh.locationRefState) { locationRefresh.setRunningState(true); locationRefresh.start(); } } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } class LocationRefresh extends Thread { public boolean locationRefState, needSleep=false; private int delayTime = 0, maxRadius = 0, maxOverCount = 0; public void setRunningState(boolean state) { locationRefState = state; }; public void setSuspendMode(boolean suspend){ this.needSleep = suspend; }; public boolean getSuspendMode() { return needSleep; } public void run() { try { while (locationRefState) { msg = new Message(); msg = handler.obtainMessage(); if (!isItPressSensor) { uiChMsg = new Message(); uiChMsg = uiHandler.obtainMessage(); uiChMsg.arg1 = 1; uiHandler.sendMessage(uiChMsg); if (!preCurrentMap.equals("") && !currentMap.equals(preCurrentMap)) { isMapExist = loadIndoorMap(preCurrentMap); currentMap = preCurrentMap; } if (isMapExist) { msg.arg1 = 0; /** * currentMap 변수가 널일경우를 대비 * */ try { msg.obj = getMapNameText.getMapName(currentMap); } catch (NullPointerException e) { e.printStackTrace(); } //handler.dispatchMessage(msg); handler.sendMessage(msg); } } if (stepDetection.getstepCount() != 0) { delayTime = 0; maxRadius = 80; maxOverCount = 2; } else { delayTime = 1000; maxRadius = 10; maxOverCount = 5; } try { positionWeightor(); String str = "POSX : " + tempPos.pos_x + " | POSY: " + tempPos.pos_y; currentPosX = tempPos.pos_x; currentPosY = tempPos.pos_y; currentDirection = getDirection(); //loadIndoorMap(currentMap); if ((previousPosX == 0 && previousPosY == 0) || overPosCnt == maxOverCount || isItReverse == 1) { /** * (previousPosX == 0 && previousPosY == 0) : 위치참조가 어플실행후 처음일경우 * * overPosCnt : 이전위치 값에 비해 현재위치 값이 현저히 차이가 날경우의 횟수 * 현저한 위치의 변화가 두번이상 될경우 그 곳으로 위치 변경 * * isItReverse : pPrevious위치 -> previous위치 -> current위치 의 이동변화에서 * 갑작스런 위치 변화가 있을경우 위치를 옮기지 않고 이 값을증가 * 두번째부터는 위치를 변경 */ locationOverlay.setPosition(new PointF(currentPosX, currentPosY)); //locationOveray의 위치를 변경 pPreviousPosX = previousPosX; pPreviousPosY = previousPosY; pPreviousDirection = previousDirection; //previousPos를 pPreviousPos에 저장 previousPosX = currentPosX; previousPosY = currentPosY; previousDirection = currentDirection; //currentPos를 previousPos에 저장 overPosCnt = 0; isItReverse = 0; mapView.refresh(); //맵뷰 갱신 } else { /** * 지도의 (0,0)에서부터 현재위치와 지난 위치들의 거리를 측정하고, 갑작스런 위치 * 변동시에 적용. */ boolean flag = false; double ppDist = calDistance(pPreviousPosX, pPreviousPosY); double pDist = calDistance(previousPosX, previousPosY); double cDist = calDistance(currentPosX, currentPosY); if (ppDist <= pDist) { if (pDist <= cDist) flag = true; else flag = false; } else { if (pDist > cDist) flag = true; else flag = false; } if (((pPreviousDirection == previousDirection) && (previousDirection == currentDirection)) && (flag)) { double distance = calDistance(previousPosX, currentPosX, previousPosY, currentPosY); //현재 위치와 이전위치의 거리를 계산 if ((distance < maxRadius) && (previousDirection == pPreviousDirection) && (previousDirection == currentDirection)) { /** * 위치변화가 100픽셀 미만 일경우에만 위치를 변동시키고 그보다 클경우 예외상황으로 overPosCnt값 증가. */ tempPosX = previousPosX; tempPosY = previousPosY; while (true) { /** * tempPos에 previousPos를 저장하고, tempPos의 값을 1픽셀 씩 증가시키며 * currentPos가 될때 까지 위치를 갱신 * ----> 현재 위치를 표시하는 오버레이가 부드럽게 진행됨. */ if (currentPosX > tempPosX) { tempPosX += 1; } else if (currentPosX < tempPosX) { tempPosX -= 1; } else { //nothing to do... } if (currentPosY > tempPosY) { tempPosY += 1; } else if (currentPosY < tempPosY) { tempPosY -= 1; } else { //nothing to do } locationOverlay.setPosition(new PointF(tempPosX, tempPosY)); mapView.refresh(); if (tempPosX == currentPosX && tempPosY == currentPosY) { pPreviousPosX = previousPosX; pPreviousPosY = previousPosY; pPreviousDirection = previousDirection; previousPosX = currentPosX; previousPosY = currentPosY; previousDirection = currentDirection; break; } } } else { overPosCnt++; //현재위치와 이전위치의 거리가 80픽셀 이상(8 미터) 날경우 } } else { isItReverse++; //이동 경로상 특이한(갑작스런) 방향전환이 생긴경우 } } /** * Insert current my location to DataBase table. * */ setMyLocation(currentMap, currentPosX, currentPosY); } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } buttonVibe.vibrate(30); //진동 tempPos.pos_x = 0; tempPos.pos_y = 0; try { Thread.sleep(delayTime); //쓰레드 0.5초 슬립 } catch (InterruptedException e) { e.printStackTrace(); } tempposi.clear(); //위치들의 값을 가지고 있는 tempposi어레이 리스트를 초기화 } while(needSleep) { } } catch (NullPointerException e) { e.printStackTrace(); } } } public void sortResultPositions() { /** * php실행 결과로 가지고온 위치결과들을 JSON으로 스플릿하고 * 중복되는 위치들의 cnt를 증가시키는 함수 */ String[] result; String mapName = ""; getLocation = new GetLocation(LoginMainActivity.this, session, currentMap); try { jsonObject = new JSONObject(getLocation.getCurrentPosition()); jsonArray = jsonObject.getJSONArray("results"); for (int i = 0; i < jsonArray.length(); i++) { jo = jsonArray.getJSONObject(i); if (jo.getString("pos").equals("empty")) { //textView.setText("못찾음"); } else { positionSet = new PositionSet(); //currentMap = jo.getString("map_id"); positionSet.pos = Integer.parseInt(jo.getString("pos")); positionSet.pos_x = Integer.parseInt(jo.getString("pos_x")); positionSet.pos_y = Integer.parseInt(jo.getString("pos_y")); tempposi.add(positionSet); } } } catch (JSONException e) { e.printStackTrace(); } try { for (int i = 0; i < tempposi.size() - 1; i++) { for (int j = i + 1; j < tempposi.size(); j++) { if (tempposi.get(i).pos == tempposi.get(j).pos) { /** * pos의 값이 같은 것이 있을경우 * cnt를 증가시키고 확인한 곳은 삭제 */ tempposi.get(i).cnt++; //cnt 증가 tempposi.remove(j); //삭제 } } } } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } // } } @Override public void onClick(View v) { buttonVibe.vibrate(20); switch (v.getId()) { case R.id.my_loc_bt: //현재 위치 표시 버튼 클릭시 실행 if (!isLocationRef) { isLocationRef = true; mapFinder = new MapFinder(); locationRefresh = new LocationRefresh(); if (isItPressSensor) { mapFinder.setRunningState(true); mapFinder.start(); } else { if (preCurrentMap.equals("") || preCurrentMap == null) { isLocationRef = false; Toast.makeText(this, "먼저 우측 상단에서 맵을 고르세요!\n맵이 없다면 옵션->지도관리 에서 다운!", Toast.LENGTH_SHORT).show(); } else { //loadIndoorMap(currentMap); locationRefresh.setRunningState(true); locationRefresh.start(); } } mapView.getOverLays().add(locationOverlay); mapView.refresh(); } else { locationIconOn.setVisibility(View.INVISIBLE); locationIconOff.setVisibility(View.VISIBLE); isLocationRef = false; mapFinder.setRunningState(false); locationRefresh.setRunningState(false); if (mapFinder.isAlive()) { mapFinder.interrupt(); mapFinder = null; } if (locationRefresh.isAlive()) { locationRefresh.interrupt(); locationRefresh = null; } try { mapView.getOverLays().remove(1); //위치오버레이 삭제 currentPosX = 0; currentPosY = 0; } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } mapView.refresh(); setMyLocation("nulll", 0, 0); } break; case R.id.fr_loc_bt: activityChangeIntent = new Intent(LoginMainActivity.this, ShowMyFriend.class); //친구 리스트보는 화면으로 변경 activityChangeIntent.putExtra("session", session); startActivity(activityChangeIntent); break; case R.id.edit_info_bt: activityChangeIntent = new Intent(LoginMainActivity.this, InformationEditActivity.class); activityChangeIntent.putExtra("session", session); startActivity(activityChangeIntent); break; case R.id.del_account_bt: AlertDialog.Builder askAlert = new AlertDialog.Builder(this); askAlert.setTitle("정말 계정을 삭제할까요?"); askAlert.setMessage("친구들의 위치를 알수없게 됩니다!"); askAlert.setPositiveButton("네", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { showDialog(); } }); askAlert.setNegativeButton("취소!", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); askAlert.show(); break; default: break; } } //LoginMainActivity의 버튼들 온클릭 메소드 public void showDialog() { phpExcute = new PhpExcute(); final Context mContext = getApplicationContext(); LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.custom_dialog, (ViewGroup) findViewById(R.id.layout_root)); final EditText passwdInput = (EditText) layout.findViewById(R.id.passwd_input); AlertDialog.Builder askAlert = new AlertDialog.Builder(this); askAlert.setTitle("비밀번호 확인"); askAlert.setMessage("본인 계정의 비밀번호를 입력해주세요."); askAlert.setView(layout); askAlert.setPositiveButton("삭제", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { try { String result = phpExcute.execute("http://minsdatanetwork.iptime.org:82/iptsPhp/memberManage/unregistration.php?mem_id=" + session + "&mem_pw=" + passwdInput.getText().toString()).get(); if (result.equals("incorrect pw")) { Toast.makeText(context, "비밀번호가 틀렸습니다.", Toast.LENGTH_SHORT).show(); } else if (result.equals("delete success")) { Toast.makeText(context, "사용자의 모든 정보가 삭제되었습니다.\n사용해주셔서 감사합니다.", Toast.LENGTH_SHORT).show(); intent = new Intent(LoginMainActivity.this, MainActivity.class); startActivity(intent); finish(); } else Toast.makeText(context, "오류가 발생한거 같습니다.\n잠시뒤 다시 시도해주세요.", Toast.LENGTH_SHORT).show(); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }); askAlert.setNegativeButton("취소!", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); AlertDialog ad = askAlert.create(); ad.show(); } protected boolean loadIndoorMap(String mapName) { String mapPath = "/storage/sdcard0/indoorMapData/" + mapName + ".svg"; File mapFile = new File(mapPath); if (mapFile.isFile()) { mapView.registerMapViewListener(new SVGMapViewListener() { @Override public void onMapLoadComplete() { /* 지도가 로딩된후에 설정되는 값들 */ mapView.setDrawingCacheEnabled(true); mapView.setAnimationCacheEnabled(true); mapView.setAlwaysDrawnWithCacheEnabled(true); mapView.getController().setRotationGestureEnabled(false); //지도 회전이 안되도록 설정 mapView.getController().setRotateWithTouchEventCenterEnabled(true); mapView.getController().setZoomWithTouchEventCenterEnabled(true); mapView.getController().setMaxZoomValue(MAX_ZOOM); //최대 줌 배율 설정 } @Override public void onMapLoadError() { //지도 로딩에 에러가 발생했을 경우 showToastMessage("Map Load Error."); } @Override public void onGetCurrentMap(Bitmap bitmap) { } }); mapView.loadMap(AssetsHelper.getContent(this, mapPath)); //지도 로딩 메소드 return true; } else { Message msg = handler.obtainMessage(); msg.arg1 = 1; msg.obj = "맵이 존재하지 않아요! 다운받아주세요!"; handler.sendMessage(msg); return false; } } @Override protected void onResume() { super.onResume(); mapView.onResume(); m_sensor_manager.registerListener(this, m_acc_sensor, SensorManager.SENSOR_DELAY_UI); m_sensor_manager.registerListener(this, m_mag_sensor, SensorManager.SENSOR_DELAY_UI); m_sensor_manager.registerListener(this, preSensor, SensorManager.SENSOR_DELAY_NORMAL); // �з� stepDetection.load(); try { if (locationRefresh.getSuspendMode()) { locationRefresh.setSuspendMode(false); } }catch(NullPointerException e) { e.printStackTrace(); } } @Override protected void onPause() { super.onPause(); mapView.onPause(); m_sensor_manager.unregisterListener(this); try { if(!locationRefresh.getSuspendMode()) { locationRefresh.setSuspendMode(true); } stepDetection.unload(); } catch (NullPointerException e) { e.printStackTrace(); } } @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); } @Override public void onDestroy() { super.onDestroy(); //GCMRegistrar.unregister(this); mapView.onDestroy(); try { if (mapFinder.isAlive()) { mapFinder.setRunningState(false); } if (locationRefresh.isAlive()) { locationRefresh.setRunningState(false); } } catch (NullPointerException e) { e.printStackTrace(); } m_sensor_manager.unregisterListener(this); stopService(service); try { stepDetection.unload(); } catch (NullPointerException e) { e.printStackTrace(); } logoutOperation(1); } @Override public void onBackPressed() { //super.onBackPressed(); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle("프로그램 종료 확인"); alertDialogBuilder.setMessage("정말 종료할까요??!").setCancelable(false).setPositiveButton("종료", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { LoginMainActivity.this.finish(); } }).setNegativeButton("취소", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_login_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { boolean checkAutoLogin; SharedPreferences pref = getSharedPreferences("loginInfo", MODE_PRIVATE); checkAutoLogin = pref.getBoolean("isItAutoLogin", false); if (checkAutoLogin == true) { removeAutoLoginInfo(); showToastMessage("로그인 정보가 삭제되었어요!~"); } else { showToastMessage("설정 되어 있지 않아요~"); } return true; } if (id == R.id.logOut) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle("로그아웃 확인 확인"); alertDialogBuilder.setMessage("정말 로그아웃 할까요?").setCancelable(false).setPositiveButton("네", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //GCM 언레지 등록 logoutOperation(0); removeLoginInfo(); intent = new Intent(LoginMainActivity.this, MainActivity.class); startActivity(intent); finish(); } }).setNegativeButton("아니욥", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } if (id == R.id.manageMap) { Intent intent = new Intent(LoginMainActivity.this, MapListActivity.class); startActivity(intent); } return super.onOptionsItemSelected(item); } private void removeLoginInfo() { SharedPreferences pref = getSharedPreferences("loginInfo", MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.remove("isItAutoLogin"); editor.remove("mem_id"); editor.remove("mem_pw"); editor.commit(); } private void showToastMessage(String str) { Toast.makeText(LoginMainActivity.this, str, Toast.LENGTH_SHORT).show(); //토스트 출력하는 함수 } // 값(Key Data) 삭제하기 private void removeAutoLoginInfo() { SharedPreferences pref = getSharedPreferences("loginInfo", MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.remove("isItAutoLogin"); editor.remove("mem_id"); editor.remove("mem_pw"); editor.commit(); } private void logoutOperation(int mode) { String tempResult = new String(); boolean temp; phpExcute = new PhpExcute(); //Intent intent; if (mode == 1) { SharedPreferences pref = getSharedPreferences("loginInfo", MODE_PRIVATE); if (pref.getBoolean("isItAutoLogin", false)) { mode = 1; } else mode = 0; } try { tempResult = phpExcute.execute("http://minsdatanetwork.iptime.org:82/iptsPhp/memberManage/change_state_to_off.php?id=" + session + "&mode=" + mode).get(); phpExcute.cancel(true); } catch (Exception e) { e.printStackTrace(); } } }
UTF-8
Java
48,451
java
LoginMainActivity.java
Java
[]
null
[]
package yu_cse.graduation_project_edit.activities; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.PointF; import android.graphics.drawable.AnimationDrawable; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.os.Message; import android.os.Vibrator; import android.os.Handler; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.jiahuan.svgmapview.SVGMapView; import com.jiahuan.svgmapview.SVGMapViewListener; import com.jiahuan.svgmapview.overlay.SVGMapLocationOverlay; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.concurrent.ExecutionException; import de.uvwxy.footpath.core.StepDetection; import de.uvwxy.footpath.core.StepTrigger; import yu_cse.graduation_project_edit.R; import yu_cse.graduation_project_edit.location.BuildingListSet; import yu_cse.graduation_project_edit.location.GetMapNameText; import yu_cse.graduation_project_edit.location.GetLocation; import yu_cse.graduation_project_edit.util.AssetsHelper; import yu_cse.graduation_project_edit.util.PhpExcute; import yu_cse.graduation_project_edit.util.TaskRemoveCheckService; public class LoginMainActivity extends Activity implements AdapterView.OnItemSelectedListener, SensorEventListener, View.OnClickListener { final Context context = this; final float MAX_ZOOM = 3.0f; //최대 줌 배율 private float presuureValue; private LocationRefresh locationRefresh = null; private MapFinder mapFinder; private int currentPosX = 0, currentPosY = 0, currentDirection = 0, previousPosX = 0, previousPosY = 0, previousDirection = 0, pPreviousPosX = 0, pPreviousPosY = 0, pPreviousDirection = 0, tempPosX = 0, tempPosY = 0, overPosCnt = 0, isItReverse = 0; private SensorManager m_sensor_manager; private Sensor m_acc_sensor, m_mag_sensor, preSensor; private float[] m_acc_data = null, m_mag_data = null; private float[] m_rotation = new float[9]; private float[] m_result_data = new float[3]; public GetLocation getLocation; private PhpExcute phpExcute; private SVGMapView mapView; //지도가 표현될 커스텀 뷰 private SVGMapLocationOverlay locationOverlay; //위치가 포현될 오버레이 private Vibrator buttonVibe; private boolean isLocationRef = false, isItPressSensor = false; //현재위치가 갱신 되고 있는지 여부를 저장하는 불린값 private ImageButton showMyLocation, showMyFreind, editInformation, delAccount; private Intent activityChangeIntent, intent; // 인텐트 private Intent service; private String session, currentMap = ""; public TextView mapTextView; private JSONObject jsonObject, jo; private JSONArray jsonArray; public PositionSet positionSet; public PositionSet tempPos; private Handler handler; private Handler uiHandler; boolean checkAutoLogin, isMapExist; private ImageView locationIconOff, locationIconOn, pressSensorIcon; ArrayList<PositionSet> tempposi; GetMapNameText getMapNameText; Message msg, uiChMsg, altiMsg; private StepDetection stepDetection; private StepTrigger stepTrigger; private Spinner mapListSpinner; private String preCurrentMap = ""; ArrayList<String> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_main); getMapNameText = new GetMapNameText(); SharedPreferences temp = getSharedPreferences("sessinInfo", MODE_PRIVATE); SharedPreferences pref = getSharedPreferences("loginInfo", MODE_PRIVATE); checkAutoLogin = pref.getBoolean("isItAutoLogin", false); if (checkAutoLogin) { session = pref.getString("mem_id", ""); //이전 액티비티에서 세션값을 넘겨 받음(로그인 상태) } else { session = temp.getString("session", ""); } mapListSpinner = (Spinner) findViewById(R.id.mapList); service = new Intent(this, TaskRemoveCheckService.class); service.putExtra("session", session); service.putExtra("isAutoLogin", checkAutoLogin); startService(service); pressSensorIcon = (ImageView) findViewById(R.id.pressSensorIcon); mapTextView = (TextView) findViewById(R.id.mapNameTextView); m_sensor_manager = (SensorManager) getSystemService(SENSOR_SERVICE); m_acc_sensor = m_sensor_manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); m_mag_sensor = m_sensor_manager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); boolean test = false; /** * 기압센서 사용가능한지 확인. */ if (m_sensor_manager.getDefaultSensor(Sensor.TYPE_PRESSURE) != null) { preSensor = m_sensor_manager.getDefaultSensor(Sensor.TYPE_PRESSURE); isItPressSensor = true; mapListSpinner.setVisibility(View.INVISIBLE); pressSensorIcon.setImageResource(R.drawable.circle_green); Toast.makeText(this, "기압센서로 층을 구분합니다.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "해당기기엔 기압센서가 없습니다.\n맵뷰 우측 상단에서 지도 선택 가능합니다.", Toast.LENGTH_SHORT).show(); getTitleList(); isItPressSensor = false; pressSensorIcon.setImageResource(R.drawable.circle_red); mapListSpinner.setVisibility(View.VISIBLE); } tempposi = new ArrayList<>(); showMyFreind = (ImageButton) findViewById(R.id.fr_loc_bt); showMyFreind.setOnClickListener(this); // 버튼 클릭 리스너 등록(아래동일) showMyLocation = (ImageButton) findViewById(R.id.my_loc_bt); showMyLocation.setOnClickListener(this); editInformation = (ImageButton) findViewById(R.id.edit_info_bt); editInformation.setOnClickListener(this); delAccount = (ImageButton) findViewById(R.id.del_account_bt); delAccount.setOnClickListener(this); mapView = (SVGMapView) findViewById(R.id.map_view); buttonVibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); locationOverlay = new SVGMapLocationOverlay(mapView); //locationOveray 객체를 맵뷰에 등록 locationOverlay.setMode(SVGMapLocationOverlay.MODE_NORMAL); locationIconOff = (ImageView) findViewById(R.id.loc_icon_off); locationIconOn = (ImageView) findViewById(R.id.loc_icon_on); locationIconOn.setImageResource(R.drawable.my_blinking_drawable); AnimationDrawable frameAnimation = (AnimationDrawable) locationIconOn.getDrawable(); frameAnimation.start(); locationIconOn.setVisibility(View.INVISIBLE); locationIconOff.setVisibility(View.VISIBLE); getMapNameText = new GetMapNameText(); stepTrigger = new StepTrigger() { @Override public void trigger(long now_ms, double compDir) { } @Override public void dataHookAcc(long now_ms, double x, double y, double z) { } @Override public void dataHookComp(long now_ms, double x, double y, double z) { } @Override public void timedDataHook(long now_ms, double[] acc, double[] comp) { } }; stepDetection = new StepDetection(this, stepTrigger, 0.31, 1.4, 250); handler = new MyHandler(this); uiHandler = new UiChagneHandler(this); } class PositionSet { public int pos = 0; public int pos_x = 0; public int pos_y = 0; public int cnt = 1; } private static class MyHandler extends Handler { /** * 외부 쓰레드에서 액티비티UI변경을 위한 핸들러 */ private final WeakReference<LoginMainActivity> mActivity; //this.ob public MyHandler(LoginMainActivity activity) { mActivity = new WeakReference<LoginMainActivity>(activity); } @Override public void handleMessage(Message msg) { this.obtainMessage(); LoginMainActivity activity = mActivity.get(); if (activity != null) { activity.mapTextView.setText(String.valueOf(msg.obj)); } } } private static class UiChagneHandler extends Handler { /** * 외부 쓰레드에서 액티비티UI변경을 위한 핸들러 */ private final WeakReference<LoginMainActivity> mActivity; //this.ob public UiChagneHandler(LoginMainActivity activity) { mActivity = new WeakReference<LoginMainActivity>(activity); } @Override public void handleMessage(Message msg) { this.obtainMessage(); LoginMainActivity activity = mActivity.get(); if (activity != null) { if (msg.arg1 == 1) { activity.locationIconOn.setVisibility(View.VISIBLE); activity.locationIconOff.setVisibility(View.INVISIBLE); } else { } } } } public void onAccuracyChanged(Sensor sensor, int accuracy) { } public void onSensorChanged(SensorEvent event) { float var0 = event.values[0]; if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { // 가속 센서가 전달한 데이터인 경우 // 수치 데이터를 복사한다. m_acc_data = event.values.clone(); } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { // 자기장 센서가 전달한 데이터인 경우 // 수치 데이터를 복사한다. m_mag_data = event.values.clone(); } // 데이터가 존재하는 경우 if (m_acc_data != null && m_mag_data != null) { SensorManager.getRotationMatrix(m_rotation, null, m_acc_data, m_mag_data); SensorManager.getOrientation(m_rotation, m_result_data); String str; m_result_data[0] = (float) Math.toDegrees(m_result_data[0]); if (m_result_data[0] < 0) m_result_data[0] += 360; str = "azimuth(z) : " + (int) m_result_data[0]; } if (event.sensor.getType() == Sensor.TYPE_PRESSURE) { presuureValue = var0; //altituteTextView.setText(String.valueOf(var0)); //mapTextView.setText(String.valueOf(var0)); } } private int getDirection() { /** * 0~360도를 4개의 범위로 나누어서 * 1~4의 정수 값으로 반환 */ int azimuth = (int) m_result_data[0]; int direction; if (((315 <= azimuth) && (azimuth < 360)) && ((0 <= azimuth) && (azimuth < 45))) { direction = 1; } else if ((45 <= azimuth) && (azimuth < 135)) { direction = 2; } else if ((135 <= azimuth) && (azimuth < 225)) { direction = 3; } else if ((225 <= azimuth) && (azimuth < 315)) { direction = 4; } else direction = -1; return direction; } private double calDistance(int cPosX, int pPosX, int cPosY, int pPosY) { /** * 상동하나 두 지점의 거리를 구하는 함수 */ double dist; dist = Math.sqrt(Math.pow(pPosX - cPosX, 2) + Math.pow(pPosY - cPosY, 2)); return dist; } private double calDistance(int cPosX, int cPosY) { /** * 상동하나 두 지점의 거리를 구하는 함수 */ double dist; dist = Math.sqrt(Math.pow(cPosX, 2) + Math.pow(cPosY, 2)); return dist; } public static int f_direct(int x1, int y1, int x2, int y2) { ////이전전,이전 좌표를 통해 방향성 구성 int lx1, ly1; int direct_point = 0; lx1 = x2 - x1; ly1 = y2 - y1; if (lx1 > 0) { if (ly1 > 0) { direct_point = 1; // 오른쪽 위 } else if (ly1 == 0) { direct_point = 2; // 오른쪽 } else if (ly1 < 0) { direct_point = 3; // 오른쪽 밑 } } else if (lx1 == 0) { if (ly1 < 0) { direct_point = 4; // 밑 } else if (ly1 == 0) { //direct_point=9;// (0,0) 그대로 다시 측정 } else if (ly1 > 0) direct_point = 8; // 위 } else if (lx1 < 0) { if (ly1 > 0) { direct_point = 7; // 왼쪽 위 } else if (ly1 == 0) { direct_point = 6; // 왼쪽 } else if (ly1 < 0) { direct_point = 5; // 왼쪽 밑 } } return direct_point; } public static int s_direct(int x1, int y1, int x2, int y2, int x3, int y3, int direct_point) { //이전전,이전, 현재 좌표 들의 각도 구하여 방향성 double lx1, ly1, lx2, ly2; lx1 = x2 - x1; //두점을 이은 직선의 길이 구하기 ly1 = y2 - y1; lx2 = x2 - x3; ly2 = y2 - y3; double inner = (lx1 * lx2 + ly1 * ly2); //내적 double i1 = Math.sqrt(lx1 * lx1 + ly1 * ly1); //벡터 정규화 double i2 = Math.sqrt(lx2 * lx2 + ly2 * ly2); //벡터 정규화 lx1 = (lx1 / i1); //단위 벡터 ly1 = (ly1 / i1); lx2 = (lx2 / i2); ly2 = (ly2 / i2); inner = (lx1 * lx2 + ly1 * ly2); //내적 다시 구하기 double result = Math.acos(inner) * 180 / (Math.PI); //각도 구하기 if (lx1 > lx2) result = 360 - result; //360도 까지 표현 if (result >= 360) result = result - 360; //360도 이상일 시 각도를 재구성 if (result >= 0 && result <= 30) direct_point = direct_point + 4; //방향 재구성 else if (result > 30 && result <= 60) direct_point = direct_point - 1; else if (result > 60 && result <= 105) direct_point = direct_point - 2; else if (result > 105 && result <= 150) direct_point = direct_point - 3; else if (result > 150 && result <= 195) ; else if (result > 195 && result <= 240) direct_point = direct_point + 3; else if (result > 240 && result <= 285) direct_point = direct_point + 2; else if (result > 285 && result <= 330) direct_point = direct_point + 1; else if (result > 330 && result <= 360) direct_point = direct_point - 4; if (direct_point <= 0) direct_point = direct_point + 8; //8방향 설정 else if (direct_point > 8) direct_point = direct_point - 8; return direct_point; } private void positionWeightor() { /** * 각 위치들은 결과에서 얼마만큼 중복되어 나타났는지 cnt의 값을 가지고 이를 기준으로 소팅됨. * * 어느정도 까지의 결과들에서 cnt를 모두 합하여 이를 100으로 보고 각 위치마다 cnt를 기준으로 * * 가중치(확률)을 곱하여 간단하게 위치를 보정. */ float cntSum = 0; float persenTage; float temp[] = new float[10]; tempPos = new PositionSet(); for (int i = 0; i < 10; i++) { temp[i] = 0f; } sortResultPositions(); try { Comparator<PositionSet> comparator = new Comparator<PositionSet>() { @Override public int compare(PositionSet lhs, PositionSet rhs) { return (lhs.cnt > rhs.cnt ? -1 : (lhs.cnt == rhs.cnt ? 0 : 1)); } }; Collections.sort(tempposi, comparator); //중복된 결과가 많은 순(cnt값)으로 정렬 for (int i = 0; i < tempposi.size(); i++) { cntSum += tempposi.get(i).cnt; } persenTage = 1 / cntSum; for (int i = 0; i < tempposi.size(); i++) { temp[i] = tempposi.get(i).cnt * persenTage; } for (int i = 0; i < tempposi.size(); i++) { tempPos.pos_x += (int) (((float) tempposi.get(i).pos_x * temp[i])); } for (int i = 0; i < tempposi.size(); i++) { tempPos.pos_y += (int) (((float) tempposi.get(i).pos_y * temp[i])); } } catch (NullPointerException e) { e.printStackTrace(); } } private void setMyLocation(String map, int posx, int posy) { PhpExcute phpExcute1 = new PhpExcute(); try { String result = phpExcute1.execute("http://minsdatanetwork.iptime.org:82/iptsPhp/locationService/insertlocation.php?mem_id=" + session + "&map=" + map + "&posx=" + posx + "&posy=" + posy).get(); phpExcute1.cancel(true); } catch (NullPointerException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } class MapFinder extends Thread { private boolean mapRefState; //Message msg1 = handler.obtainMessage(); //Message msg = handler.obtainMessage(); //Message mapMessage = mapHandler.obtainMessage(); String[] temp; public void setRunningState(boolean state) { mapRefState = state; } public void run() { //if(mapRefState) msg1.arg1 = 3; //else msg1.arg1 = 4; //handler.sendMessage(msg1); while (mapRefState) { altiMsg = new Message(); altiMsg = uiHandler.obtainMessage(); msg = new Message(); msg = handler.obtainMessage(); uiChMsg = new Message(); uiChMsg = uiHandler.obtainMessage(); String mapName; PhpExcute mPhpExcute = new PhpExcute(); try { mapName = mPhpExcute.execute("http://minsdatanetwork.iptime.org:82/iptsPhp/locationService/getMapbyPress.php?press=" + presuureValue).get(); temp = mapName.split(","); mapName = temp[1]; altiMsg.arg1 = 2; altiMsg.obj = temp[0]; uiHandler.sendMessage(altiMsg); //mapMessage.arg1 = 5; // mapMessage.obj = stepDetection.getstepCount(); // mapHandler.sendMessage(mapMessage); if (!mapName.equals("") && !currentMap.equals(mapName)) { isMapExist = loadIndoorMap(mapName); currentMap = mapName; } if (!isMapExist) { isLocationRef = false; setRunningState(false); currentMap = ""; } if (isMapExist) { msg.arg1 = 0; /** * currentMap 변수가 널일경우를 대비 * */ try { msg.obj = getMapNameText.getMapName(currentMap); } catch (NullPointerException e) { e.printStackTrace(); } //handler.dispatchMessage(msg); handler.sendMessage(msg); uiChMsg.arg1 = 1; uiHandler.sendMessage(uiChMsg); if (!locationRefresh.locationRefState) { locationRefresh.setRunningState(true); locationRefresh.start(); } } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } class LocationRefresh extends Thread { public boolean locationRefState, needSleep=false; private int delayTime = 0, maxRadius = 0, maxOverCount = 0; public void setRunningState(boolean state) { locationRefState = state; }; public void setSuspendMode(boolean suspend){ this.needSleep = suspend; }; public boolean getSuspendMode() { return needSleep; } public void run() { try { while (locationRefState) { msg = new Message(); msg = handler.obtainMessage(); if (!isItPressSensor) { uiChMsg = new Message(); uiChMsg = uiHandler.obtainMessage(); uiChMsg.arg1 = 1; uiHandler.sendMessage(uiChMsg); if (!preCurrentMap.equals("") && !currentMap.equals(preCurrentMap)) { isMapExist = loadIndoorMap(preCurrentMap); currentMap = preCurrentMap; } if (isMapExist) { msg.arg1 = 0; /** * currentMap 변수가 널일경우를 대비 * */ try { msg.obj = getMapNameText.getMapName(currentMap); } catch (NullPointerException e) { e.printStackTrace(); } //handler.dispatchMessage(msg); handler.sendMessage(msg); } } if (stepDetection.getstepCount() != 0) { delayTime = 0; maxRadius = 80; maxOverCount = 2; } else { delayTime = 1000; maxRadius = 10; maxOverCount = 5; } try { positionWeightor(); String str = "POSX : " + tempPos.pos_x + " | POSY: " + tempPos.pos_y; currentPosX = tempPos.pos_x; currentPosY = tempPos.pos_y; currentDirection = getDirection(); //loadIndoorMap(currentMap); if ((previousPosX == 0 && previousPosY == 0) || overPosCnt == maxOverCount || isItReverse == 1) { /** * (previousPosX == 0 && previousPosY == 0) : 위치참조가 어플실행후 처음일경우 * * overPosCnt : 이전위치 값에 비해 현재위치 값이 현저히 차이가 날경우의 횟수 * 현저한 위치의 변화가 두번이상 될경우 그 곳으로 위치 변경 * * isItReverse : pPrevious위치 -> previous위치 -> current위치 의 이동변화에서 * 갑작스런 위치 변화가 있을경우 위치를 옮기지 않고 이 값을증가 * 두번째부터는 위치를 변경 */ locationOverlay.setPosition(new PointF(currentPosX, currentPosY)); //locationOveray의 위치를 변경 pPreviousPosX = previousPosX; pPreviousPosY = previousPosY; pPreviousDirection = previousDirection; //previousPos를 pPreviousPos에 저장 previousPosX = currentPosX; previousPosY = currentPosY; previousDirection = currentDirection; //currentPos를 previousPos에 저장 overPosCnt = 0; isItReverse = 0; mapView.refresh(); //맵뷰 갱신 } else { /** * 지도의 (0,0)에서부터 현재위치와 지난 위치들의 거리를 측정하고, 갑작스런 위치 * 변동시에 적용. */ boolean flag = false; double ppDist = calDistance(pPreviousPosX, pPreviousPosY); double pDist = calDistance(previousPosX, previousPosY); double cDist = calDistance(currentPosX, currentPosY); if (ppDist <= pDist) { if (pDist <= cDist) flag = true; else flag = false; } else { if (pDist > cDist) flag = true; else flag = false; } if (((pPreviousDirection == previousDirection) && (previousDirection == currentDirection)) && (flag)) { double distance = calDistance(previousPosX, currentPosX, previousPosY, currentPosY); //현재 위치와 이전위치의 거리를 계산 if ((distance < maxRadius) && (previousDirection == pPreviousDirection) && (previousDirection == currentDirection)) { /** * 위치변화가 100픽셀 미만 일경우에만 위치를 변동시키고 그보다 클경우 예외상황으로 overPosCnt값 증가. */ tempPosX = previousPosX; tempPosY = previousPosY; while (true) { /** * tempPos에 previousPos를 저장하고, tempPos의 값을 1픽셀 씩 증가시키며 * currentPos가 될때 까지 위치를 갱신 * ----> 현재 위치를 표시하는 오버레이가 부드럽게 진행됨. */ if (currentPosX > tempPosX) { tempPosX += 1; } else if (currentPosX < tempPosX) { tempPosX -= 1; } else { //nothing to do... } if (currentPosY > tempPosY) { tempPosY += 1; } else if (currentPosY < tempPosY) { tempPosY -= 1; } else { //nothing to do } locationOverlay.setPosition(new PointF(tempPosX, tempPosY)); mapView.refresh(); if (tempPosX == currentPosX && tempPosY == currentPosY) { pPreviousPosX = previousPosX; pPreviousPosY = previousPosY; pPreviousDirection = previousDirection; previousPosX = currentPosX; previousPosY = currentPosY; previousDirection = currentDirection; break; } } } else { overPosCnt++; //현재위치와 이전위치의 거리가 80픽셀 이상(8 미터) 날경우 } } else { isItReverse++; //이동 경로상 특이한(갑작스런) 방향전환이 생긴경우 } } /** * Insert current my location to DataBase table. * */ setMyLocation(currentMap, currentPosX, currentPosY); } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } buttonVibe.vibrate(30); //진동 tempPos.pos_x = 0; tempPos.pos_y = 0; try { Thread.sleep(delayTime); //쓰레드 0.5초 슬립 } catch (InterruptedException e) { e.printStackTrace(); } tempposi.clear(); //위치들의 값을 가지고 있는 tempposi어레이 리스트를 초기화 } while(needSleep) { } } catch (NullPointerException e) { e.printStackTrace(); } } } public void sortResultPositions() { /** * php실행 결과로 가지고온 위치결과들을 JSON으로 스플릿하고 * 중복되는 위치들의 cnt를 증가시키는 함수 */ String[] result; String mapName = ""; getLocation = new GetLocation(LoginMainActivity.this, session, currentMap); try { jsonObject = new JSONObject(getLocation.getCurrentPosition()); jsonArray = jsonObject.getJSONArray("results"); for (int i = 0; i < jsonArray.length(); i++) { jo = jsonArray.getJSONObject(i); if (jo.getString("pos").equals("empty")) { //textView.setText("못찾음"); } else { positionSet = new PositionSet(); //currentMap = jo.getString("map_id"); positionSet.pos = Integer.parseInt(jo.getString("pos")); positionSet.pos_x = Integer.parseInt(jo.getString("pos_x")); positionSet.pos_y = Integer.parseInt(jo.getString("pos_y")); tempposi.add(positionSet); } } } catch (JSONException e) { e.printStackTrace(); } try { for (int i = 0; i < tempposi.size() - 1; i++) { for (int j = i + 1; j < tempposi.size(); j++) { if (tempposi.get(i).pos == tempposi.get(j).pos) { /** * pos의 값이 같은 것이 있을경우 * cnt를 증가시키고 확인한 곳은 삭제 */ tempposi.get(i).cnt++; //cnt 증가 tempposi.remove(j); //삭제 } } } } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } // } } @Override public void onClick(View v) { buttonVibe.vibrate(20); switch (v.getId()) { case R.id.my_loc_bt: //현재 위치 표시 버튼 클릭시 실행 if (!isLocationRef) { isLocationRef = true; mapFinder = new MapFinder(); locationRefresh = new LocationRefresh(); if (isItPressSensor) { mapFinder.setRunningState(true); mapFinder.start(); } else { if (preCurrentMap.equals("") || preCurrentMap == null) { isLocationRef = false; Toast.makeText(this, "먼저 우측 상단에서 맵을 고르세요!\n맵이 없다면 옵션->지도관리 에서 다운!", Toast.LENGTH_SHORT).show(); } else { //loadIndoorMap(currentMap); locationRefresh.setRunningState(true); locationRefresh.start(); } } mapView.getOverLays().add(locationOverlay); mapView.refresh(); } else { locationIconOn.setVisibility(View.INVISIBLE); locationIconOff.setVisibility(View.VISIBLE); isLocationRef = false; mapFinder.setRunningState(false); locationRefresh.setRunningState(false); if (mapFinder.isAlive()) { mapFinder.interrupt(); mapFinder = null; } if (locationRefresh.isAlive()) { locationRefresh.interrupt(); locationRefresh = null; } try { mapView.getOverLays().remove(1); //위치오버레이 삭제 currentPosX = 0; currentPosY = 0; } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } mapView.refresh(); setMyLocation("nulll", 0, 0); } break; case R.id.fr_loc_bt: activityChangeIntent = new Intent(LoginMainActivity.this, ShowMyFriend.class); //친구 리스트보는 화면으로 변경 activityChangeIntent.putExtra("session", session); startActivity(activityChangeIntent); break; case R.id.edit_info_bt: activityChangeIntent = new Intent(LoginMainActivity.this, InformationEditActivity.class); activityChangeIntent.putExtra("session", session); startActivity(activityChangeIntent); break; case R.id.del_account_bt: AlertDialog.Builder askAlert = new AlertDialog.Builder(this); askAlert.setTitle("정말 계정을 삭제할까요?"); askAlert.setMessage("친구들의 위치를 알수없게 됩니다!"); askAlert.setPositiveButton("네", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { showDialog(); } }); askAlert.setNegativeButton("취소!", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); askAlert.show(); break; default: break; } } //LoginMainActivity의 버튼들 온클릭 메소드 public void showDialog() { phpExcute = new PhpExcute(); final Context mContext = getApplicationContext(); LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.custom_dialog, (ViewGroup) findViewById(R.id.layout_root)); final EditText passwdInput = (EditText) layout.findViewById(R.id.passwd_input); AlertDialog.Builder askAlert = new AlertDialog.Builder(this); askAlert.setTitle("비밀번호 확인"); askAlert.setMessage("본인 계정의 비밀번호를 입력해주세요."); askAlert.setView(layout); askAlert.setPositiveButton("삭제", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { try { String result = phpExcute.execute("http://minsdatanetwork.iptime.org:82/iptsPhp/memberManage/unregistration.php?mem_id=" + session + "&mem_pw=" + passwdInput.getText().toString()).get(); if (result.equals("incorrect pw")) { Toast.makeText(context, "비밀번호가 틀렸습니다.", Toast.LENGTH_SHORT).show(); } else if (result.equals("delete success")) { Toast.makeText(context, "사용자의 모든 정보가 삭제되었습니다.\n사용해주셔서 감사합니다.", Toast.LENGTH_SHORT).show(); intent = new Intent(LoginMainActivity.this, MainActivity.class); startActivity(intent); finish(); } else Toast.makeText(context, "오류가 발생한거 같습니다.\n잠시뒤 다시 시도해주세요.", Toast.LENGTH_SHORT).show(); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }); askAlert.setNegativeButton("취소!", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); AlertDialog ad = askAlert.create(); ad.show(); } protected boolean loadIndoorMap(String mapName) { String mapPath = "/storage/sdcard0/indoorMapData/" + mapName + ".svg"; File mapFile = new File(mapPath); if (mapFile.isFile()) { mapView.registerMapViewListener(new SVGMapViewListener() { @Override public void onMapLoadComplete() { /* 지도가 로딩된후에 설정되는 값들 */ mapView.setDrawingCacheEnabled(true); mapView.setAnimationCacheEnabled(true); mapView.setAlwaysDrawnWithCacheEnabled(true); mapView.getController().setRotationGestureEnabled(false); //지도 회전이 안되도록 설정 mapView.getController().setRotateWithTouchEventCenterEnabled(true); mapView.getController().setZoomWithTouchEventCenterEnabled(true); mapView.getController().setMaxZoomValue(MAX_ZOOM); //최대 줌 배율 설정 } @Override public void onMapLoadError() { //지도 로딩에 에러가 발생했을 경우 showToastMessage("Map Load Error."); } @Override public void onGetCurrentMap(Bitmap bitmap) { } }); mapView.loadMap(AssetsHelper.getContent(this, mapPath)); //지도 로딩 메소드 return true; } else { Message msg = handler.obtainMessage(); msg.arg1 = 1; msg.obj = "맵이 존재하지 않아요! 다운받아주세요!"; handler.sendMessage(msg); return false; } } @Override protected void onResume() { super.onResume(); mapView.onResume(); m_sensor_manager.registerListener(this, m_acc_sensor, SensorManager.SENSOR_DELAY_UI); m_sensor_manager.registerListener(this, m_mag_sensor, SensorManager.SENSOR_DELAY_UI); m_sensor_manager.registerListener(this, preSensor, SensorManager.SENSOR_DELAY_NORMAL); // �з� stepDetection.load(); try { if (locationRefresh.getSuspendMode()) { locationRefresh.setSuspendMode(false); } }catch(NullPointerException e) { e.printStackTrace(); } } @Override protected void onPause() { super.onPause(); mapView.onPause(); m_sensor_manager.unregisterListener(this); try { if(!locationRefresh.getSuspendMode()) { locationRefresh.setSuspendMode(true); } stepDetection.unload(); } catch (NullPointerException e) { e.printStackTrace(); } } @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); } @Override public void onDestroy() { super.onDestroy(); //GCMRegistrar.unregister(this); mapView.onDestroy(); try { if (mapFinder.isAlive()) { mapFinder.setRunningState(false); } if (locationRefresh.isAlive()) { locationRefresh.setRunningState(false); } } catch (NullPointerException e) { e.printStackTrace(); } m_sensor_manager.unregisterListener(this); stopService(service); try { stepDetection.unload(); } catch (NullPointerException e) { e.printStackTrace(); } logoutOperation(1); } @Override public void onBackPressed() { //super.onBackPressed(); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle("프로그램 종료 확인"); alertDialogBuilder.setMessage("정말 종료할까요??!").setCancelable(false).setPositiveButton("종료", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { LoginMainActivity.this.finish(); } }).setNegativeButton("취소", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_login_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { boolean checkAutoLogin; SharedPreferences pref = getSharedPreferences("loginInfo", MODE_PRIVATE); checkAutoLogin = pref.getBoolean("isItAutoLogin", false); if (checkAutoLogin == true) { removeAutoLoginInfo(); showToastMessage("로그인 정보가 삭제되었어요!~"); } else { showToastMessage("설정 되어 있지 않아요~"); } return true; } if (id == R.id.logOut) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle("로그아웃 확인 확인"); alertDialogBuilder.setMessage("정말 로그아웃 할까요?").setCancelable(false).setPositiveButton("네", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //GCM 언레지 등록 logoutOperation(0); removeLoginInfo(); intent = new Intent(LoginMainActivity.this, MainActivity.class); startActivity(intent); finish(); } }).setNegativeButton("아니욥", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } if (id == R.id.manageMap) { Intent intent = new Intent(LoginMainActivity.this, MapListActivity.class); startActivity(intent); } return super.onOptionsItemSelected(item); } private void removeLoginInfo() { SharedPreferences pref = getSharedPreferences("loginInfo", MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.remove("isItAutoLogin"); editor.remove("mem_id"); editor.remove("mem_pw"); editor.commit(); } private void showToastMessage(String str) { Toast.makeText(LoginMainActivity.this, str, Toast.LENGTH_SHORT).show(); //토스트 출력하는 함수 } // 값(Key Data) 삭제하기 private void removeAutoLoginInfo() { SharedPreferences pref = getSharedPreferences("loginInfo", MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.remove("isItAutoLogin"); editor.remove("mem_id"); editor.remove("mem_pw"); editor.commit(); } private void logoutOperation(int mode) { String tempResult = new String(); boolean temp; phpExcute = new PhpExcute(); //Intent intent; if (mode == 1) { SharedPreferences pref = getSharedPreferences("loginInfo", MODE_PRIVATE); if (pref.getBoolean("isItAutoLogin", false)) { mode = 1; } else mode = 0; } try { tempResult = phpExcute.execute("http://minsdatanetwork.iptime.org:82/iptsPhp/memberManage/change_state_to_off.php?id=" + session + "&mode=" + mode).get(); phpExcute.cancel(true); } catch (Exception e) { e.printStackTrace(); } } }
48,451
0.503816
0.495443
1,355
32.848709
28.859579
206
false
false
0
0
0
0
0
0
0.543173
false
false
9
051229ee51875b403a6e4cdf7a62000b0912e51b
7,000,796,735,043
164e28530c58ddef9bf323c6f1180c08cf701ad5
/src/main/java/au/com/myob/monthlypayslip/exception/FileParseException.java
ad9791ac08972139ce37509110ab2499da8e3c70
[]
no_license
deanx/monthlypayslip-java
https://github.com/deanx/monthlypayslip-java
f4231524c17fa5abf6bee0082148ce0069cd3f7a
28a074ebbdb7adadd65de8b8b0b59a431337cc5e
refs/heads/master
2016-08-11T12:44:05.861000
2016-03-27T16:57:15
2016-03-27T16:57:15
54,823,566
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package au.com.myob.monthlypayslip.exception; public class FileParseException extends Exception { private static final long serialVersionUID = -3945952909447101454L; public FileParseException(String message, Exception e) { super(message, e); } }
UTF-8
Java
255
java
FileParseException.java
Java
[]
null
[]
package au.com.myob.monthlypayslip.exception; public class FileParseException extends Exception { private static final long serialVersionUID = -3945952909447101454L; public FileParseException(String message, Exception e) { super(message, e); } }
255
0.792157
0.717647
10
24.5
26.27261
68
false
false
0
0
0
0
0
0
1.1
false
false
9
dd5e338627c63824018d58a86100dab5d12fba1a
5,961,414,658,196
0bed4797be5a4d017d44cb9e48e24a2a262e1b6f
/lect03/JEE_DataLayer/src/main/java/ru/otus/dpopkov/jdbc/servlets/InitDataServlet.java
aea1d1087cff9ca59d8b97342ca0840debf8d3f8
[]
no_license
dpopkov/jee-hw
https://github.com/dpopkov/jee-hw
fec2c016bd37e873bd216cb91b241f4a2f3038f4
021dc31c233b652ebef93bd74d52dd290717a39a
refs/heads/master
2021-05-11T15:22:22.801000
2018-03-04T15:36:44
2018-03-04T15:36:44
117,728,417
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.otus.dpopkov.jdbc.servlets; import au.com.bytecode.opencsv.CSVReader; import ru.otus.dpopkov.jdbc.model.Employee; import ru.otus.dpopkov.jdbc.model.Position; import ru.otus.dpopkov.jdbc.model.Role; import ru.otus.dpopkov.jdbc.util.JPASessionUtil; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; 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 java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.util.*; @WebServlet( name = "initDataServlet", urlPatterns = {"/init"} ) public class InitDataServlet extends HttpServlet { private static final String POSITIONS_CSV_LOCATION = "/positions.csv"; private static final String EMPLOYEES_CSV_LOCATION = "/employees.csv"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { EntityManager em = JPASessionUtil.getEntityManager(); EntityTransaction transaction = em.getTransaction(); try { transaction.begin(); addDataToDb(em); transaction.commit(); } catch (Exception e) { transaction.rollback(); throw new ServletException(e); } finally { em.close(); } resp.sendRedirect("index.html"); } private void addDataToDb(EntityManager em) throws IOException { Map<String, Position> positionMap = readPositions(); List<Employee> employeeList = readEmployees(positionMap); for (Employee employee : employeeList) { em.persist(employee); } } private Map<String, Position> readPositions() throws IOException { Map<String, Position> positionMap = new HashMap<>(); Map<String, Role> roleMap = new HashMap<>(); List<String[]> list = csvToList(POSITIONS_CSV_LOCATION); for (String[] line : list) { Position position = new Position(); String name = line[0]; position.setName(name); for (int i = 1; i < line.length; i++) { String roleName = line[i]; Role role = new Role(); role.setName(roleName); roleMap.putIfAbsent(roleName, role); position.getRoles().add(roleMap.get(roleName)); } positionMap.put(name, position); } return positionMap; } private List<Employee> readEmployees(Map<String, Position> positionMap) throws IOException { List<Employee> employeeList = new ArrayList<>(); List<String[]> list = csvToList(EMPLOYEES_CSV_LOCATION); for(String[] line : list) { String fullName = line[0]; Employee employee = new Employee(); employee.setFullName(fullName); employee.setLogin(line[1]); Position position = positionMap.get(line[2]); employee.setPosition(position); employee.setSalary(new BigDecimal(line[3])); employeeList.add(employee); } return employeeList; } private List<String[]> csvToList(String csvResourceLocation) throws IOException { List<String[]> lines; try (InputStream inputStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(csvResourceLocation)) { CSVReader reader = new CSVReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); lines = reader.readAll(); } return lines; } }
UTF-8
Java
3,816
java
InitDataServlet.java
Java
[]
null
[]
package ru.otus.dpopkov.jdbc.servlets; import au.com.bytecode.opencsv.CSVReader; import ru.otus.dpopkov.jdbc.model.Employee; import ru.otus.dpopkov.jdbc.model.Position; import ru.otus.dpopkov.jdbc.model.Role; import ru.otus.dpopkov.jdbc.util.JPASessionUtil; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; 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 java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.util.*; @WebServlet( name = "initDataServlet", urlPatterns = {"/init"} ) public class InitDataServlet extends HttpServlet { private static final String POSITIONS_CSV_LOCATION = "/positions.csv"; private static final String EMPLOYEES_CSV_LOCATION = "/employees.csv"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { EntityManager em = JPASessionUtil.getEntityManager(); EntityTransaction transaction = em.getTransaction(); try { transaction.begin(); addDataToDb(em); transaction.commit(); } catch (Exception e) { transaction.rollback(); throw new ServletException(e); } finally { em.close(); } resp.sendRedirect("index.html"); } private void addDataToDb(EntityManager em) throws IOException { Map<String, Position> positionMap = readPositions(); List<Employee> employeeList = readEmployees(positionMap); for (Employee employee : employeeList) { em.persist(employee); } } private Map<String, Position> readPositions() throws IOException { Map<String, Position> positionMap = new HashMap<>(); Map<String, Role> roleMap = new HashMap<>(); List<String[]> list = csvToList(POSITIONS_CSV_LOCATION); for (String[] line : list) { Position position = new Position(); String name = line[0]; position.setName(name); for (int i = 1; i < line.length; i++) { String roleName = line[i]; Role role = new Role(); role.setName(roleName); roleMap.putIfAbsent(roleName, role); position.getRoles().add(roleMap.get(roleName)); } positionMap.put(name, position); } return positionMap; } private List<Employee> readEmployees(Map<String, Position> positionMap) throws IOException { List<Employee> employeeList = new ArrayList<>(); List<String[]> list = csvToList(EMPLOYEES_CSV_LOCATION); for(String[] line : list) { String fullName = line[0]; Employee employee = new Employee(); employee.setFullName(fullName); employee.setLogin(line[1]); Position position = positionMap.get(line[2]); employee.setPosition(position); employee.setSalary(new BigDecimal(line[3])); employeeList.add(employee); } return employeeList; } private List<String[]> csvToList(String csvResourceLocation) throws IOException { List<String[]> lines; try (InputStream inputStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(csvResourceLocation)) { CSVReader reader = new CSVReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); lines = reader.readAll(); } return lines; } }
3,816
0.648847
0.647013
103
36.048542
24.407295
114
false
false
0
0
0
0
0
0
0.718447
false
false
9
4494c6e67b5298ed536f0bd2c89affeba2d9837f
25,546,465,520,239
87a6fa292607338ea4a093f9f88f3241fb4be836
/src/main/java/com/applet/entity/geo/BikeGeoDetailInfo.java
98d5162afce0a753625e085f36051e4714feed7d
[]
no_license
bengniaofeibu/jiujiuwxapplet
https://github.com/bengniaofeibu/jiujiuwxapplet
6c9edeb08875c470b9a813c923ff1becadd114bc
523f970665cb136c519ba4aefe20e85c88659651
refs/heads/master
2020-03-27T23:02:58.527000
2018-09-04T03:32:35
2018-09-04T03:32:35
147,284,771
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.applet.entity.geo; public class BikeGeoDetailInfo { private String name; private GeoPointInfo point; public String getName() { return name; } public void setName(String name) { this.name = name; } public GeoPointInfo getPoint() { return point; } public void setPoint(GeoPointInfo point) { this.point = point; } }
UTF-8
Java
404
java
BikeGeoDetailInfo.java
Java
[]
null
[]
package com.applet.entity.geo; public class BikeGeoDetailInfo { private String name; private GeoPointInfo point; public String getName() { return name; } public void setName(String name) { this.name = name; } public GeoPointInfo getPoint() { return point; } public void setPoint(GeoPointInfo point) { this.point = point; } }
404
0.613861
0.613861
24
15.833333
15.051763
46
false
false
0
0
0
0
0
0
0.291667
false
false
9
23da8537a18d4dafbacccb09c51b026210632d42
14,164,802,189,990
cc6d6fda4bbb8e5cfd736957753b980a71e8b921
/src/extract/excel/data/Main.java
aecd86a16ea08801cc6e5a60d3e35149fd8e4789
[]
no_license
delpp/ExtractXLSDataCar
https://github.com/delpp/ExtractXLSDataCar
8e06e846d873fc3d289a87722f42f38357ec6403
24d10968b47bfd2f6644bcab7276abafa63efeab
refs/heads/master
2023-07-15T18:19:00.203000
2021-08-19T13:03:16
2021-08-19T13:03:16
397,945,194
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package extract.excel.data; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; public class Main extends Application{ public void start(Stage stage){ ViewLoader<AnchorPane, Object> viewLoader = new ViewLoader<AnchorPane, Object>("view/window.fxml"); AnchorPane anchorPane = viewLoader.getLayout(); Scene scene = new Scene(anchorPane); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(); } }
UTF-8
Java
538
java
Main.java
Java
[]
null
[]
package extract.excel.data; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; public class Main extends Application{ public void start(Stage stage){ ViewLoader<AnchorPane, Object> viewLoader = new ViewLoader<AnchorPane, Object>("view/window.fxml"); AnchorPane anchorPane = viewLoader.getLayout(); Scene scene = new Scene(anchorPane); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(); } }
538
0.745353
0.745353
25
20.559999
23.200138
101
false
false
0
0
0
0
0
0
1.44
false
false
9
8e2d2e8725ba17cd0d32de6654c796ff17fa3fff
8,005,819,084,801
b1cd2c0deb2de1b2149b7fbdfa4aa383a4858aa3
/rmi-service/src/main/java/cn/yxy/service/UserService.java
a2d680a0c08c9c9cecaaddf94f63588498ddf237
[]
no_license
wasax9t/JnshuFollow
https://github.com/wasax9t/JnshuFollow
118a2ae6aa81407fb62e062735111dbf30b07ea0
be08136af371387cab8c81a2a97608ed5e2db8c4
refs/heads/master
2021-01-19T23:12:59.568000
2017-06-20T11:35:16
2017-06-20T11:35:17
88,949,131
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.yxy.service; import cn.yxy.domain.User; import java.util.List; public interface UserService { boolean deleteByPrimaryKey(long id); long insert(User user); long insertSelective(User user); User selectByPrimaryKey(long id); boolean updateByPrimaryKey(User user); boolean updateByPrimaryKeySelective(User user); /** * 根据用户名查用户详情 */ User selectByName(String name); /** * 查询批量用户 */ List<User> selectByNameLike(String str); }
UTF-8
Java
534
java
UserService.java
Java
[]
null
[]
package cn.yxy.service; import cn.yxy.domain.User; import java.util.List; public interface UserService { boolean deleteByPrimaryKey(long id); long insert(User user); long insertSelective(User user); User selectByPrimaryKey(long id); boolean updateByPrimaryKey(User user); boolean updateByPrimaryKeySelective(User user); /** * 根据用户名查用户详情 */ User selectByName(String name); /** * 查询批量用户 */ List<User> selectByNameLike(String str); }
534
0.673307
0.673307
30
15.733334
16.6712
51
false
false
0
0
0
0
0
0
0.366667
false
false
9
548132c468a78b72a8fc5e44c7f31d74139e7580
26,096,221,357,483
470638d559d0e626ea6cff28462e8d0ec97f11f3
/java/培训笔记/0827/JDBC插入/Test.java
42b8de838e1d253ec96d4af6dedcfee72456a14b
[]
no_license
LiShuxue/BackEnd-Base
https://github.com/LiShuxue/BackEnd-Base
40069d6cc88501f170a0b30969b8bb978e453d31
5ab9d1e16b9924fe252933342fdb8c57f86631cd
refs/heads/master
2023-08-31T02:12:27.381000
2023-08-30T02:11:02
2023-08-30T02:11:02
93,992,632
0
0
null
false
2022-07-13T18:28:38
2017-06-11T08:49:05
2019-12-17T03:51:43
2022-07-13T18:28:38
225,391
0
0
22
HTML
false
false
package com.zyw.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class Test { public static void main(String[] args) { /** * 访问student表,向表中插入数据 */ Connection con = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:XE", "system", "system"); //通过数据库连接对象,获取一个Statement对象, //注意:它是java.sql下面的一个接口,用来执行 SQL语句 Statement stmt = con.createStatement(); //定义SQL语句,这个语句必须在数据库中(Navicat)执行过,再写到这里 String sql = "insert into STUDENT values(5,'test3'," + "to_date('2015-1-1','yyyy-mm-dd'),'tj','email','133')"; //executeUpdate返回值 就是执行的 影响行数 int count = stmt.executeUpdate(sql); if(count > 0){ System.out.println("执行成功"); }else{ System.out.println("执行失败了"); } } catch (Exception e) { e.printStackTrace(); } finally{ try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
GB18030
Java
1,223
java
Test.java
Java
[]
null
[]
package com.zyw.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class Test { public static void main(String[] args) { /** * 访问student表,向表中插入数据 */ Connection con = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:XE", "system", "system"); //通过数据库连接对象,获取一个Statement对象, //注意:它是java.sql下面的一个接口,用来执行 SQL语句 Statement stmt = con.createStatement(); //定义SQL语句,这个语句必须在数据库中(Navicat)执行过,再写到这里 String sql = "insert into STUDENT values(5,'test3'," + "to_date('2015-1-1','yyyy-mm-dd'),'tj','email','133')"; //executeUpdate返回值 就是执行的 影响行数 int count = stmt.executeUpdate(sql); if(count > 0){ System.out.println("执行成功"); }else{ System.out.println("执行失败了"); } } catch (Exception e) { e.printStackTrace(); } finally{ try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
1,223
0.654106
0.638647
42
23.642857
17.205788
64
false
false
0
0
0
0
0
0
2.785714
false
false
9
aaec62d25cbc67581fdabd8cc169d2c5dbf4443e
20,289,425,509,398
cd9a01567e8f8488becddacbb69b45521ad8cc42
/PR150_GOODROUTE/src_route/com/ynhenc/kml/KmlStyle.java
2f25cabb272b3be12353efc401d5ca7550b29e15
[ "Apache-2.0" ]
permissive
sunabove/ws_map_01
https://github.com/sunabove/ws_map_01
f976a980c2d2585957be4b5c17ae65f459317ec6
f28310f03ef82946ace11fb25c5e45ab74387d06
refs/heads/master
2022-11-21T07:07:38.036000
2020-07-24T22:11:25
2020-07-24T22:11:25
282,322,341
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ynhenc.kml; import java.awt.Color; import java.io.Writer; import com.ynhenc.comm.util.*; public abstract class KmlStyle extends KmlObject { public KmlStyleUrl getStyleUrl() { if( this.styleUrl == null ) { this.styleUrl = new KmlStyleUrl( this.getId() ); } return this.styleUrl; } public int getId() { return id; } @Override public String getTag() { return "Style"; } public KmlStyle( int id ) { super( null, null ); this.id = id; } private int id; private transient KmlStyleUrl styleUrl; }
UTF-8
Java
540
java
KmlStyle.java
Java
[]
null
[]
package com.ynhenc.kml; import java.awt.Color; import java.io.Writer; import com.ynhenc.comm.util.*; public abstract class KmlStyle extends KmlObject { public KmlStyleUrl getStyleUrl() { if( this.styleUrl == null ) { this.styleUrl = new KmlStyleUrl( this.getId() ); } return this.styleUrl; } public int getId() { return id; } @Override public String getTag() { return "Style"; } public KmlStyle( int id ) { super( null, null ); this.id = id; } private int id; private transient KmlStyleUrl styleUrl; }
540
0.677778
0.677778
35
14.428572
15.024334
51
false
false
0
0
0
0
0
0
1.171429
false
false
9
e0aa10ae978ea722235c0cabf4c390a9f29331f8
9,955,734,196,439
dc735f1430c85b8166b240b51830fec955044b72
/CallCenter/src/main/java/com/common/core/tree/TreeNode.java
31b7f072e30f80b7585e3186b04509cfb093def7
[]
no_license
fanyuhang/call-center
https://github.com/fanyuhang/call-center
1dba0271ff2e5a2bf076b350549a7977d143288e
b11b8978ffe1fee40699a27b6916f3935bd05208
refs/heads/master
2022-11-10T19:39:02.824000
2016-05-08T14:41:18
2016-05-08T14:41:18
276,818,300
0
0
null
true
2020-07-03T05:48:59
2020-07-03T05:48:59
2018-03-16T12:59:52
2016-05-08T14:43:12
6,733
0
0
0
null
false
false
package com.common.core.tree; import com.common.security.entity.Node; import org.springframework.beans.BeanUtils; /** * 树形节点 */ public class TreeNode extends Node { private TreeNode pNode; private String fullPath; public TreeNode() { } public TreeNode(Node node) { BeanUtils.copyProperties(node, this); } public TreeNode getpNode() { return pNode; } public void setpNode(TreeNode pNode) { this.pNode = pNode; } public String getFullPath() { return fullPath; } public void setFullPath(String fullPath) { this.fullPath = fullPath; } }
UTF-8
Java
649
java
TreeNode.java
Java
[]
null
[]
package com.common.core.tree; import com.common.security.entity.Node; import org.springframework.beans.BeanUtils; /** * 树形节点 */ public class TreeNode extends Node { private TreeNode pNode; private String fullPath; public TreeNode() { } public TreeNode(Node node) { BeanUtils.copyProperties(node, this); } public TreeNode getpNode() { return pNode; } public void setpNode(TreeNode pNode) { this.pNode = pNode; } public String getFullPath() { return fullPath; } public void setFullPath(String fullPath) { this.fullPath = fullPath; } }
649
0.634945
0.634945
37
16.324324
16.261469
46
false
false
0
0
0
0
0
0
0.297297
false
false
9
9b486175a4ea8dc86845235b2e6bf3716f2b9cce
27,599,459,894,343
e8ae8d06e00c0257535eb004396eea98e665b9a5
/aouth-jwt-demo/src/main/java/com/edntisolutions/aouth/api/model/Player.java
e7d2d4639a823ee78732c2084098bc3ac471dc4b
[]
no_license
edneyRoldao/spring-security-poc
https://github.com/edneyRoldao/spring-security-poc
22277832f6004412037e2253a43db25764cf580b
a4b29b60f838b3bbd2ae1769beb0383de893d8a9
refs/heads/master
2023-06-16T01:41:59.697000
2021-07-12T14:23:11
2021-07-12T14:23:11
385,272,441
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.edntisolutions.aouth.api.model; import lombok.Builder; import lombok.Data; import java.util.ArrayList; import java.util.List; @Data @Builder public class Player { private int id; private String name; private String team; public static List<Player> getMockPlayers() { List<Player> players = new ArrayList<>(); players.add(Player.builder().id(1).name("Messi").team("barcelona").build()); players.add(Player.builder().id(1).name("Ronaldo").team("real madrid").build()); players.add(Player.builder().id(1).name("Kobe").team("lakers").build()); return players; } }
UTF-8
Java
640
java
Player.java
Java
[ { "context": "\n players.add(Player.builder().id(1).name(\"Messi\").team(\"barcelona\").build());\n players.add", "end": 405, "score": 0.9997766613960266, "start": 400, "tag": "NAME", "value": "Messi" }, { "context": "\n players.add(Player.builder().id(1).name(\"Ronaldo\").team(\"real madrid\").build());\n players.a", "end": 492, "score": 0.9997844099998474, "start": 485, "tag": "NAME", "value": "Ronaldo" }, { "context": "\n players.add(Player.builder().id(1).name(\"Kobe\").team(\"lakers\").build());\n\n return player", "end": 578, "score": 0.9998153448104858, "start": 574, "tag": "NAME", "value": "Kobe" } ]
null
[]
package com.edntisolutions.aouth.api.model; import lombok.Builder; import lombok.Data; import java.util.ArrayList; import java.util.List; @Data @Builder public class Player { private int id; private String name; private String team; public static List<Player> getMockPlayers() { List<Player> players = new ArrayList<>(); players.add(Player.builder().id(1).name("Messi").team("barcelona").build()); players.add(Player.builder().id(1).name("Ronaldo").team("real madrid").build()); players.add(Player.builder().id(1).name("Kobe").team("lakers").build()); return players; } }
640
0.660937
0.65625
27
22.703703
26.239374
88
false
false
0
0
0
0
0
0
0.481481
false
false
9
e0823b35a2ab00e0360b426c6c2254f7b2206175
36,507,222,029,390
deecefb70d22f1da4c0f80d716f48b8da6fcac35
/src/Inscale/MultiBrowser.java
9538c0704948c0c22e307ef9064322479e0fd3bf
[]
no_license
navinphp/INSCALE_TEST
https://github.com/navinphp/INSCALE_TEST
577494e1e9d3419ca1501af6455a88920ecbb667
cf003d8054b3aed174e8dad00afef63a2a17b549
refs/heads/master
2020-05-30T23:36:38.474000
2019-06-03T15:11:51
2019-06-03T15:11:51
190,019,897
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Inscale; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.opera.OperaDriver; import org.openqa.selenium.safari.SafariDriver; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class MultiBrowser { WebDriver driver; @Test @Parameters({"browser"}) public void openBrowser(String browser) { if(browser.equalsIgnoreCase("firefox")) { driver =new FirefoxDriver(); } else if(browser.equalsIgnoreCase("chrome")) { System.setProperty("webdriver.chrome.driver","browsers//chromedriver"); driver = new ChromeDriver(); } else if(browser.equalsIgnoreCase("opera")) { System.setProperty("webdriver.opera.driver","browsers//operedriver"); driver = new OperaDriver(); } else if(browser.equalsIgnoreCase("IE")) { System.setProperty("webdriver.IE.driver","browsers//IEDriverServer.exe"); driver = new InternetExplorerDriver(); } else if(browser.equalsIgnoreCase("safari")) { driver = new SafariDriver(); } driver.manage().window().maximize(); driver.get("https://www.topdanmark.dk/"); driver.quit(); } }
UTF-8
Java
1,295
java
MultiBrowser.java
Java
[]
null
[]
package Inscale; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.opera.OperaDriver; import org.openqa.selenium.safari.SafariDriver; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class MultiBrowser { WebDriver driver; @Test @Parameters({"browser"}) public void openBrowser(String browser) { if(browser.equalsIgnoreCase("firefox")) { driver =new FirefoxDriver(); } else if(browser.equalsIgnoreCase("chrome")) { System.setProperty("webdriver.chrome.driver","browsers//chromedriver"); driver = new ChromeDriver(); } else if(browser.equalsIgnoreCase("opera")) { System.setProperty("webdriver.opera.driver","browsers//operedriver"); driver = new OperaDriver(); } else if(browser.equalsIgnoreCase("IE")) { System.setProperty("webdriver.IE.driver","browsers//IEDriverServer.exe"); driver = new InternetExplorerDriver(); } else if(browser.equalsIgnoreCase("safari")) { driver = new SafariDriver(); } driver.manage().window().maximize(); driver.get("https://www.topdanmark.dk/"); driver.quit(); } }
1,295
0.72278
0.72278
48
25.979166
22.065706
77
false
false
0
0
0
0
0
0
2.416667
false
false
9
d31e44d26f01ae66e41bdb80e6dd839bda8e21c7
21,062,519,661,746
0f93271f30d92a66577186b868e43f094f405956
/src/test/java/italo/mendes/sincronizacao/com/builder/BuilderTests.java
ede3f4cdbc44f7fb00a5242d8445019067e24a1a
[]
no_license
italonerd/SincronizacaoReceita
https://github.com/italonerd/SincronizacaoReceita
c089af5993f797a4fc0cf468b31310f816d75809
7444fa42016b0d800f8835d512ae6441e0fe7a94
refs/heads/master
2023-01-24T07:36:43.219000
2020-11-25T15:32:15
2020-11-25T15:32:15
311,873,638
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package italo.mendes.sincronizacao.com.builder; import italo.mendes.sincronizacao.com.bl.Builder; import italo.mendes.sincronizacao.com.bl.PrepareWorker; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.io.File; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; @SpringBootTest class BuilderTests { @Autowired private Builder builder; @Mock private PrepareWorker prepareMock; @BeforeEach void startMocks() { MockitoAnnotations.initMocks(this); } @Test() void buildTest() { Assertions.assertThrows(NullPointerException.class, () -> { builder.build(); }); } @Test() void buildWithParametersTest() { doNothing().when(prepareMock).prepareRoutine(any(File.class)); builder.setPrepare(prepareMock); builder.build(); } }
UTF-8
Java
1,209
java
BuilderTests.java
Java
[]
null
[]
package italo.mendes.sincronizacao.com.builder; import italo.mendes.sincronizacao.com.bl.Builder; import italo.mendes.sincronizacao.com.bl.PrepareWorker; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.io.File; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; @SpringBootTest class BuilderTests { @Autowired private Builder builder; @Mock private PrepareWorker prepareMock; @BeforeEach void startMocks() { MockitoAnnotations.initMocks(this); } @Test() void buildTest() { Assertions.assertThrows(NullPointerException.class, () -> { builder.build(); }); } @Test() void buildWithParametersTest() { doNothing().when(prepareMock).prepareRoutine(any(File.class)); builder.setPrepare(prepareMock); builder.build(); } }
1,209
0.729529
0.729529
46
25.282608
20.99551
70
false
false
0
0
0
0
0
0
0.5
false
false
9
43f8069dd6353c19cf1893d8a975821c825debb0
35,648,228,571,158
f0aeb0b1f56cfa587a179113fb6566aaf4d5c66f
/app/src/main/java/com/s_hack/amor/probamap/MapsActivity.java
4fdc8397b853bfc22ac531b0af8b8c4a4716807c
[]
no_license
SverbliukRoman/ProbaMap
https://github.com/SverbliukRoman/ProbaMap
52370948928a44637280a01304a18f4b510d7265
aba92822f5d89ee88f644925746b46075b4c818a
refs/heads/master
2019-12-22T21:06:59.125000
2017-03-01T16:38:40
2017-03-01T16:38:40
82,091,957
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.s_hack.amor.probamap; import android.content.pm.PackageManager; import android.location.Location; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Button; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import android.support.v4.*; public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener { private GoogleMap mMap; private Button but; private LatLng location; private static final String TAG = "MyApp"; Location mLocation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapLongClick(LatLng latLng) { mMap.addMarker(new MarkerOptions().position(latLng).title("ghjkl").visible(true).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))).setVisible(true); Log.e(TAG, "isworking"); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } googleMap.setMyLocationEnabled(true); mLocation = googleMap.getMyLocation(); //oko mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() { @Override public void onMapLongClick(LatLng latLng) { mMap.addMarker(new MarkerOptions().position(latLng).title("ghjkl").visible(true).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))).setVisible(true); } }); } }
UTF-8
Java
3,081
java
MapsActivity.java
Java
[]
null
[]
package com.s_hack.amor.probamap; import android.content.pm.PackageManager; import android.location.Location; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Button; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import android.support.v4.*; public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener { private GoogleMap mMap; private Button but; private LatLng location; private static final String TAG = "MyApp"; Location mLocation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapLongClick(LatLng latLng) { mMap.addMarker(new MarkerOptions().position(latLng).title("ghjkl").visible(true).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))).setVisible(true); Log.e(TAG, "isworking"); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } googleMap.setMyLocationEnabled(true); mLocation = googleMap.getMyLocation(); //oko mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() { @Override public void onMapLongClick(LatLng latLng) { mMap.addMarker(new MarkerOptions().position(latLng).title("ghjkl").visible(true).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))).setVisible(true); } }); } }
3,081
0.7173
0.716001
70
43.014286
46.569607
275
false
false
0
0
0
0
0
0
0.571429
false
false
9
1eb4967a6e394c31a75f5948445d11ef0674503c
29,815,663,021,408
40ecbb6b2ae84418a6c619859fb21f34a0639486
/M02 - Vehicles by Inheritance 01/src/com/vehicle/Pedal.java
dae8cc1befa51717d28a77fea2204cd81053399e
[ "Apache-2.0" ]
permissive
AnastasiaYiChen/Java-Code
https://github.com/AnastasiaYiChen/Java-Code
36334a8cb8f2829bfdc49e317f9d667a83ff7ca3
5c9c8cdebbe7ef7d202c8de6f877cd8ca96fceaf
refs/heads/main
2023-06-14T00:38:05.038000
2021-07-07T19:43:23
2021-07-07T19:43:23
337,608,112
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vehicle; /** * GAS or BRAKE */ public enum Pedal { /** * GAS */ GAS, /** * BRAKE */ BRAKE }
UTF-8
Java
143
java
Pedal.java
Java
[]
null
[]
package com.vehicle; /** * GAS or BRAKE */ public enum Pedal { /** * GAS */ GAS, /** * BRAKE */ BRAKE }
143
0.405594
0.405594
15
8.533334
5.760401
20
false
false
0
0
0
0
0
0
0.133333
false
false
9
45730e8d190b3e8e84fafdcce62b5c75dff5f1d7
18,932,215,893,861
e590b1e5823ae6ba1b559904732fee6987fde33d
/Messabout/src/Assignment08/Potion.java
56ec257a790fe04555c867999d4984f46ce80dbd
[]
no_license
Krosantos/Java2014
https://github.com/Krosantos/Java2014
1e633064dcde1a0727a02f910613a1ab709050c1
587852339efc25dfbc05b7273e250e46f2c0d2f9
refs/heads/master
2016-09-10T21:05:35.228000
2014-04-29T03:49:35
2014-04-29T03:49:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Assignment08; public class Potion { private int maxIngredients; private String contents = ""; public Potion(){ this.maxIngredients = 10; } public Potion(int size){ this.maxIngredients = size; } public boolean addIngredient(char ingredient){ if(this.contents.length() < this.maxIngredients && (ingredient == 'a' || ingredient == 'b' || ingredient == 'c' || ingredient == 'd' || ingredient =='w') ){ this.contents += ingredient; return true; } else return false; } @Override public String toString(){ return this.contents; } public boolean heatPotion(){ boolean result = false; String temp = ""; for(int i=0;i<contents.length();i++){ if(contents.charAt(i) == 'w'){ result = true; } else temp+=contents.charAt(i); } contents = temp; return result; } public void discardPotion(Bucket target){ target.dumpIngredient(contents); contents = ""; } public boolean isFull(){ if(contents.length() == maxIngredients){ return true; } else return false; } }
UTF-8
Java
1,047
java
Potion.java
Java
[]
null
[]
package Assignment08; public class Potion { private int maxIngredients; private String contents = ""; public Potion(){ this.maxIngredients = 10; } public Potion(int size){ this.maxIngredients = size; } public boolean addIngredient(char ingredient){ if(this.contents.length() < this.maxIngredients && (ingredient == 'a' || ingredient == 'b' || ingredient == 'c' || ingredient == 'd' || ingredient =='w') ){ this.contents += ingredient; return true; } else return false; } @Override public String toString(){ return this.contents; } public boolean heatPotion(){ boolean result = false; String temp = ""; for(int i=0;i<contents.length();i++){ if(contents.charAt(i) == 'w'){ result = true; } else temp+=contents.charAt(i); } contents = temp; return result; } public void discardPotion(Bucket target){ target.dumpIngredient(contents); contents = ""; } public boolean isFull(){ if(contents.length() == maxIngredients){ return true; } else return false; } }
1,047
0.644699
0.639924
54
18.388889
18.541662
106
false
false
0
0
0
0
0
0
2.166667
false
false
9
100295a5b9d8625de528c226ba0651f8fa59bfa2
19,550,691,178,849
58863f68507d0b5d4d64e15899f1b60b8978b218
/src/main/java/eular/net/eular/Problem13.java
17ecb49350c7090992fed8e712264eaa9c1e89e3
[]
no_license
Bharat9848/algopractice
https://github.com/Bharat9848/algopractice
7774de369d6790b4fbcec33ab0bbe67bdcecaa48
52a81a8e3f9a182315819cd0d8ce77397e99414b
refs/heads/master
2022-08-25T17:50:58.854000
2022-07-16T05:17:58
2022-07-16T05:17:58
135,737,814
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package eular.net.eular; /** * Created by bharat on 4/3/18. * Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. */ import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Problem13 { private static int[][] data = new int[100][50]; private static FileReader reader; private static BufferedReader bfReader; public static void main(String[] args){ populateData(); int[] result = new int[10]; int i=49; int carry =0; while(i>9){ carry = findSum(i,carry)/10; i--; } int sum=0; while(i>=0){ sum = findSum(i,carry); if(i==0){ result[9-i]= sum; }else{ result[9-i] = sum%10; carry = sum/10; } i--; } for(i=9;i>=0;i--){ System.out.print(result[i]); } } private static int findSum(int col, int previousCarry) { int sum =previousCarry; for(int i=0; i<100;i++){ sum += data[i][col]; } return sum; } public static void populateData(){ File path = new File("eular/Problem13"); try{ reader = new FileReader(path); bfReader = new BufferedReader(reader); String buffer = null; int j=0; while((buffer =bfReader.readLine())!= null&& j<101){ int i=0; int [] line = new int [50]; while(i<buffer.length()){ line[i] = Integer.parseInt(String.valueOf((buffer.charAt(i)))); i++; } storeline(line,j++); } }catch(FileNotFoundException fnf){ fnf.printStackTrace(); }catch(IOException ioe){ ioe.printStackTrace(); } } private static void storeline(int[] line, int index) { data[index] = line; } }
UTF-8
Java
2,142
java
Problem13.java
Java
[ { "context": "package eular.net.eular;\n\n/**\n * Created by bharat on 4/3/18.\n * Work out the first ten digits of th", "end": 50, "score": 0.998790442943573, "start": 44, "tag": "USERNAME", "value": "bharat" } ]
null
[]
package eular.net.eular; /** * Created by bharat on 4/3/18. * Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. */ import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Problem13 { private static int[][] data = new int[100][50]; private static FileReader reader; private static BufferedReader bfReader; public static void main(String[] args){ populateData(); int[] result = new int[10]; int i=49; int carry =0; while(i>9){ carry = findSum(i,carry)/10; i--; } int sum=0; while(i>=0){ sum = findSum(i,carry); if(i==0){ result[9-i]= sum; }else{ result[9-i] = sum%10; carry = sum/10; } i--; } for(i=9;i>=0;i--){ System.out.print(result[i]); } } private static int findSum(int col, int previousCarry) { int sum =previousCarry; for(int i=0; i<100;i++){ sum += data[i][col]; } return sum; } public static void populateData(){ File path = new File("eular/Problem13"); try{ reader = new FileReader(path); bfReader = new BufferedReader(reader); String buffer = null; int j=0; while((buffer =bfReader.readLine())!= null&& j<101){ int i=0; int [] line = new int [50]; while(i<buffer.length()){ line[i] = Integer.parseInt(String.valueOf((buffer.charAt(i)))); i++; } storeline(line,j++); } }catch(FileNotFoundException fnf){ fnf.printStackTrace(); }catch(IOException ioe){ ioe.printStackTrace(); } } private static void storeline(int[] line, int index) { data[index] = line; } }
2,142
0.492063
0.471055
76
27.18421
18.467403
90
false
false
0
0
0
0
0
0
0.618421
false
false
9
0527179b58217f1eb1cb8d24278dfae01ff2aac5
23,467,701,352,419
baf86c081bcee3344acb27b8e5e9dcce3f37e3a0
/repl03/Exercise73Arrays.java
7112fb105300c493c3c789de03f1eb9162b86bf1
[]
no_license
Hdey68/SofianeRiplExer
https://github.com/Hdey68/SofianeRiplExer
1d28f3a81083ba1cc3903888fd2965db5726f77b
75ce92ad97b690e341172a4af4fb62dfcf3c8f35
refs/heads/master
2023-02-08T11:09:42.215000
2021-01-05T03:26:06
2021-01-05T03:26:06
305,768,907
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sofiane.repl03; public class Exercise73Arrays { public static void main(String[] args) { // TODO Auto-generated method stub // Write a program that creates an array of integers and stores the following values: // 45, 78, 12, 67, 55 and then prints all array values. int[] integ= {45,78,12,67,55}; for(int i=0; i<integ.length; i++) { System.out.print(integ[i]+" "); } }///////////////////////////////Done////////////////////////////////////// }
UTF-8
Java
489
java
Exercise73Arrays.java
Java
[]
null
[]
package com.sofiane.repl03; public class Exercise73Arrays { public static void main(String[] args) { // TODO Auto-generated method stub // Write a program that creates an array of integers and stores the following values: // 45, 78, 12, 67, 55 and then prints all array values. int[] integ= {45,78,12,67,55}; for(int i=0; i<integ.length; i++) { System.out.print(integ[i]+" "); } }///////////////////////////////Done////////////////////////////////////// }
489
0.562372
0.511247
19
24.736841
26.331573
87
false
false
0
0
0
0
75
0.153374
2
false
false
9
031a1ff3fd5387fc657e646a7136dcf3afa0f07f
21,440,476,793,854
d88b185eed08fa511261b54e29cd83fa7e682343
/src/JavaMoodle18/AbstractClasses/Shapes.java
a148f1f412b684d85dfdc26cd08c38dbd732fe03
[]
no_license
GKSM24/2018_Moodle_Assignments
https://github.com/GKSM24/2018_Moodle_Assignments
48c702154a7168156aa0c30ce2901e47f36ce6b5
e5c851b1c6a5ebe9051e5d57c74c719903641510
refs/heads/master
2020-08-27T02:25:21.539000
2019-10-29T10:25:48
2019-10-29T10:25:48
217,218,385
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package JavaMoodle18.AbstractClasses; public abstract class Shapes { public String shape = ""; public abstract double area(); public abstract double perimeter(); public abstract void getData(); } abstract class Triangle extends Shapes{ public byte numberOfSides = 3; private double side1, side2, side3; public Triangle(){ shape = "triangle"; side1 = 0; side2 = 0; side3 = 0; } public double getSide1() { return side1; } public double getSide2() { return side2; } public double getSide3() { return side3; } public Triangle(double s1, double s2, double s3){ shape = "triangle"; side1 = s1; side2 = s2; side3 = s3; } public double area(){ double s = (side1+side2+side3)/2; return Math.sqrt(s*(s-side1)*(s-side2)*(s-side3)); } public double perimeter(){ return side1+side2+side3; } public void getData(){ System.out.println("The shape of triangle is "+shape); System.out.println("side 1= "+side1+" side 2= "+side2+" side 3= "+side3); System.out.println("Area = "+area()+" Perimeter = "+perimeter()); } } class IsoscelesTriangle extends Triangle{ public IsoscelesTriangle(){ super(); shape = "isosceles triangle"; } public IsoscelesTriangle(double s1, double s2){ super(s1, s1, s2); shape = "isosceles triangle"; } } class EquilateralTriangle extends Triangle{ public EquilateralTriangle(){ super(); shape = "equilateral triangle"; } public EquilateralTriangle(double side){ super(side,side,side); shape = "equilateral triangle"; } } class Circle extends Shapes{ private double radius; public Circle(){ shape = "circle"; radius = 0; } public double getRadius() { return radius; } public Circle(double r){ radius = r; shape = "circle"; } public double area(){ return Math.PI * radius * radius; } public double perimeter(){ return Math.PI * radius * 2; } public void getData(){ System.out.println("The shape is "+shape); System.out.println("radius = "+radius); System.out.println("Area = "+area()+" Perimeter = "+perimeter()); } } abstract class Quadrilateral extends Shapes{ public byte numberOfSides = 4; public Quadrilateral(){ shape = "quadrilateral"; } } class Rectangle extends Quadrilateral{ private double length, breadth; public Rectangle(){ shape = "rectangle"; length = 0; breadth = 0; } public double getLength() { return length; } public double getBreadth() { return breadth; } public Rectangle(double l, double b){ length = l; breadth = b; shape = "rectangle"; } public double area(){ return length * breadth; } public double perimeter(){ return 2*(length + breadth); } public void getData(){ System.out.println("The shape of quadrilateral is "+shape); System.out.println("length = "+length+" breadth = "+breadth); System.out.println("Area = "+area()+" Perimeter = "+perimeter()); } } class Square extends Quadrilateral{ private double side; public Square(){ shape = "square"; side = 0; } public double getSide() { return side; } public Square(double s){ shape = "square"; side = s; } public double area(){ return side * side; } public double perimeter(){ return 4 * side; } public void getData(){ System.out.println("The shape of quadrilateral is "+shape); System.out.println("Side = "+side); System.out.println("Area = "+area()+" Perimeter = "+perimeter()); } } class Rhombus extends Quadrilateral{ private double base, height; public Rhombus(){ shape = "rhombus"; base = 0; height = 0; } public Rhombus(double b, double h){ shape = "rhombus"; base = b; height = h; } public double getBase() { return base; } public double getHeight() { return height; } public double area(){ return base * height; } public double perimeter(){ return 4 * base; } public void getData(){ System.out.println("The shape of quadrilateral is "+shape); System.out.println("Base = "+base+" Height = "+height); System.out.println("Area = "+area()+" Perimeter = "+perimeter()); } }
UTF-8
Java
4,746
java
Shapes.java
Java
[]
null
[]
package JavaMoodle18.AbstractClasses; public abstract class Shapes { public String shape = ""; public abstract double area(); public abstract double perimeter(); public abstract void getData(); } abstract class Triangle extends Shapes{ public byte numberOfSides = 3; private double side1, side2, side3; public Triangle(){ shape = "triangle"; side1 = 0; side2 = 0; side3 = 0; } public double getSide1() { return side1; } public double getSide2() { return side2; } public double getSide3() { return side3; } public Triangle(double s1, double s2, double s3){ shape = "triangle"; side1 = s1; side2 = s2; side3 = s3; } public double area(){ double s = (side1+side2+side3)/2; return Math.sqrt(s*(s-side1)*(s-side2)*(s-side3)); } public double perimeter(){ return side1+side2+side3; } public void getData(){ System.out.println("The shape of triangle is "+shape); System.out.println("side 1= "+side1+" side 2= "+side2+" side 3= "+side3); System.out.println("Area = "+area()+" Perimeter = "+perimeter()); } } class IsoscelesTriangle extends Triangle{ public IsoscelesTriangle(){ super(); shape = "isosceles triangle"; } public IsoscelesTriangle(double s1, double s2){ super(s1, s1, s2); shape = "isosceles triangle"; } } class EquilateralTriangle extends Triangle{ public EquilateralTriangle(){ super(); shape = "equilateral triangle"; } public EquilateralTriangle(double side){ super(side,side,side); shape = "equilateral triangle"; } } class Circle extends Shapes{ private double radius; public Circle(){ shape = "circle"; radius = 0; } public double getRadius() { return radius; } public Circle(double r){ radius = r; shape = "circle"; } public double area(){ return Math.PI * radius * radius; } public double perimeter(){ return Math.PI * radius * 2; } public void getData(){ System.out.println("The shape is "+shape); System.out.println("radius = "+radius); System.out.println("Area = "+area()+" Perimeter = "+perimeter()); } } abstract class Quadrilateral extends Shapes{ public byte numberOfSides = 4; public Quadrilateral(){ shape = "quadrilateral"; } } class Rectangle extends Quadrilateral{ private double length, breadth; public Rectangle(){ shape = "rectangle"; length = 0; breadth = 0; } public double getLength() { return length; } public double getBreadth() { return breadth; } public Rectangle(double l, double b){ length = l; breadth = b; shape = "rectangle"; } public double area(){ return length * breadth; } public double perimeter(){ return 2*(length + breadth); } public void getData(){ System.out.println("The shape of quadrilateral is "+shape); System.out.println("length = "+length+" breadth = "+breadth); System.out.println("Area = "+area()+" Perimeter = "+perimeter()); } } class Square extends Quadrilateral{ private double side; public Square(){ shape = "square"; side = 0; } public double getSide() { return side; } public Square(double s){ shape = "square"; side = s; } public double area(){ return side * side; } public double perimeter(){ return 4 * side; } public void getData(){ System.out.println("The shape of quadrilateral is "+shape); System.out.println("Side = "+side); System.out.println("Area = "+area()+" Perimeter = "+perimeter()); } } class Rhombus extends Quadrilateral{ private double base, height; public Rhombus(){ shape = "rhombus"; base = 0; height = 0; } public Rhombus(double b, double h){ shape = "rhombus"; base = b; height = h; } public double getBase() { return base; } public double getHeight() { return height; } public double area(){ return base * height; } public double perimeter(){ return 4 * base; } public void getData(){ System.out.println("The shape of quadrilateral is "+shape); System.out.println("Base = "+base+" Height = "+height); System.out.println("Area = "+area()+" Perimeter = "+perimeter()); } }
4,746
0.563211
0.55078
231
19.549784
18.752337
81
false
false
0
0
0
0
0
0
0.419913
false
false
9
036897ff62fb603fb8c3d205491272888aafe88d
1,151,051,282,795
50c9ba1cd34c12d32a799fcdbee437529e01c5b3
/src/main/java/com/github/lerocha/controller/PropertiesController.java
8b049880ccfcf7be5f2846430398509227b1a6a7
[ "MIT" ]
permissive
lerocha/spring-boot-localizable-properties
https://github.com/lerocha/spring-boot-localizable-properties
150877fe06703822e48ca89c35887fd16dc51fda
a644d384929aa7f7b13136650a25784d18cdcafe
refs/heads/master
2022-02-13T19:41:49.469000
2016-10-11T04:43:53
2016-10-11T04:43:53
70,385,531
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.lerocha.controller; import com.github.lerocha.properties.RegionProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.Locale; /** * Created by lerocha on 10/8/16. */ @RestController public class PropertiesController { @Autowired RegionProperties regionProperties; @RequestMapping(value = "properties", method = RequestMethod.GET) public RegionProperties getProperties() { return regionProperties; } @RequestMapping(value = "properties/{locale}", method = RequestMethod.GET) public RegionProperties getProperties(@PathVariable Locale locale) { return regionProperties.fromLocale(locale); } }
UTF-8
Java
952
java
PropertiesController.java
Java
[ { "context": "ller;\n\nimport java.util.Locale;\n\n/**\n * Created by lerocha on 10/8/16.\n */\n@RestController\npublic class Prop", "end": 459, "score": 0.999634325504303, "start": 452, "tag": "USERNAME", "value": "lerocha" } ]
null
[]
package com.github.lerocha.controller; import com.github.lerocha.properties.RegionProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.Locale; /** * Created by lerocha on 10/8/16. */ @RestController public class PropertiesController { @Autowired RegionProperties regionProperties; @RequestMapping(value = "properties", method = RequestMethod.GET) public RegionProperties getProperties() { return regionProperties; } @RequestMapping(value = "properties/{locale}", method = RequestMethod.GET) public RegionProperties getProperties(@PathVariable Locale locale) { return regionProperties.fromLocale(locale); } }
952
0.781513
0.77626
30
30.733334
26.695734
78
false
false
0
0
0
0
0
0
0.433333
false
false
9
da0db720b6a036c977df13183170ffc6da1f9fe2
489,626,337,249
e6e871e061345875e23597d6025cefcce8f7eac7
/Listas/src/Q5.java
679a100a06bbd6a8a9698386207fbfc196bac92c
[]
no_license
biancahdc/PEOO
https://github.com/biancahdc/PEOO
dfe594171e9ad3660d486083e6e6d385cfdcafaf
0b7434b4c90071170a9246d45340acf4caeeb220
refs/heads/master
2020-10-02T04:57:55.811000
2019-12-13T23:36:46
2019-12-13T23:36:46
227,707,425
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; public class Q5 { public static void main(String[] args) { Scanner leia = new Scanner (System.in); int i = 1; boolean acabou = false; int media = 0; int acumulador = 0; while(!acabou) { System.out.println("Digite a idade do aluno:"); int idade = leia.nextInt(); acumulador += idade; System.out.println("Acabaram os alunos?(true ou false) "); acabou = leia.nextBoolean(); if(acabou == false) { i++; } } media = acumulador/i; System.out.println("A média das idades dos alunos é: " + media); } }
ISO-8859-2
Java
604
java
Q5.java
Java
[]
null
[]
import java.util.Scanner; public class Q5 { public static void main(String[] args) { Scanner leia = new Scanner (System.in); int i = 1; boolean acabou = false; int media = 0; int acumulador = 0; while(!acabou) { System.out.println("Digite a idade do aluno:"); int idade = leia.nextInt(); acumulador += idade; System.out.println("Acabaram os alunos?(true ou false) "); acabou = leia.nextBoolean(); if(acabou == false) { i++; } } media = acumulador/i; System.out.println("A média das idades dos alunos é: " + media); } }
604
0.596346
0.589701
27
20.296297
18.556849
67
false
false
0
0
0
0
0
0
2.407408
false
false
9
6f26e6c77938cacaa51f2c4b39ae20522e40b26a
20,066,087,261,149
b1ea174ba0c02ddd0385201bcf586b93ee6946ba
/src/main/java/com/pydio/cells/api/S3Client.java
75895045842bcfbd2fc60d9da13b07904201ea6c
[ "Apache-2.0" ]
permissive
stjordanis/cells-sdk-java
https://github.com/stjordanis/cells-sdk-java
5c29f3976ea8c03b318b80e0b9b8f83e6a66e830
7d2e298b638042815f9e730f677b3d598ce93cf4
refs/heads/master
2023-07-07T11:57:55.844000
2021-08-11T08:56:48
2021-08-11T08:56:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pydio.cells.api; import com.pydio.cells.api.SDKException; import java.io.InputStream; import java.net.URL; public interface S3Client { InputStream getThumb(String file) throws SDKException; URL getUploadPreSignedURL(String ws, String folder, String name) throws SDKException; URL getDownloadPreSignedURL(String ws, String file) throws SDKException; URL getStreamingPreSignedURL(String slug, String file, String contentType) throws SDKException; }
UTF-8
Java
481
java
S3Client.java
Java
[]
null
[]
package com.pydio.cells.api; import com.pydio.cells.api.SDKException; import java.io.InputStream; import java.net.URL; public interface S3Client { InputStream getThumb(String file) throws SDKException; URL getUploadPreSignedURL(String ws, String folder, String name) throws SDKException; URL getDownloadPreSignedURL(String ws, String file) throws SDKException; URL getStreamingPreSignedURL(String slug, String file, String contentType) throws SDKException; }
481
0.794179
0.7921
17
27.352942
32.886509
99
false
false
0
0
0
0
0
0
0.764706
false
false
9
1ea209ca16e76ba511fe248bbd90da3f16c12fbc
23,115,514,035,013
b4353b34a1d02048c44334b6192c3466282e7f09
/src/application/objects/LinkNode.java
d9c7bd13e48ddf0b8f6a914406bc94d4fbf43032
[]
no_license
jmeech/UML
https://github.com/jmeech/UML
f5a5a34bab6c5cdd8feb58d04d3c0e77372b6000
f38c45b172f67691edf275b69e5fae5294a4d410
refs/heads/master
2020-03-29T04:31:37.209000
2018-12-03T00:28:26
2018-12-03T00:28:26
149,535,245
0
2
null
false
2018-12-01T19:56:27
2018-09-20T01:45:17
2018-11-30T19:47:36
2018-12-01T19:07:46
3,263
0
1
1
Java
false
null
package application.objects; import java.util.ArrayList; import java.util.List; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; public class LinkNode { private IntegerProperty xPos = new SimpleIntegerProperty(); private IntegerProperty yPos = new SimpleIntegerProperty(); private List<Link> connectedLinks; private IntegerProperty xPosL = new SimpleIntegerProperty(); private IntegerProperty xPosR = new SimpleIntegerProperty(); private IntegerProperty yPosU = new SimpleIntegerProperty(); private IntegerProperty yPosD = new SimpleIntegerProperty(); /** * Constructs an instance of LinkNode * * @constructor */ public LinkNode() { connectedLinks = new ArrayList<Link>(); } /** * Constructs an instance of LinkNode * * @constructor * @param x * the x position of the LinkNode * @param y * the y position of the LinkNode */ public LinkNode(int x, int y) { xPos.set(x); yPos.set(y); connectedLinks = new ArrayList<Link>(); } /** * Sets the x position of the LinkNode * * @param x * the x position to be set */ public void setX(int x) { xPos.set(x); } /** * Sets the y position of the LinkNode * * @param y * the y position to be set */ public void setY(int y) { yPos.set(y); } /** * Returns the x position of the LinkNode * * @return * the x position of the LinkNode */ public int getX() { return xPos.get(); } /** * Returns the y position of the LinkNode * * @return * the y position of the LinkNode */ public int getY() { return yPos.get(); } /** * Returns the xPos property of the LinkNode * * @return * the LinkNode's xPos property */ public IntegerProperty getXProperty() { return xPos; } /** * Returns the yPos property of the LinkNode * * @return * the LinkNode's yPos property */ public IntegerProperty getYProperty() { return yPos; } /** * Add the parent Link to the list of Links that originate from this LinkNode * * @param one * of the Links that uses this LinkNode */ public void giveParent(Link dad) { if (!connectedLinks.contains(dad)) connectedLinks.add(dad); } /** * Sets the 4 bounds of the LinkNode * * @param xL * the left bound to be set * @param xR * the right bound to be set * @param yU * the top bound to be set * @param yD * to bottom bound to be set */ public void setBounds(int xL, int xR, int yU, int yD) { xPosL.set(xL); xPosR.set(xR); yPosU.set(yU); yPosD.set(yD); } /** * Returns the left bound of the LinkNode * * @return the left bound of the LinkNode */ public int getL() { return xPosL.get(); } /** * Returns the right bound of the LinkNode * * @return the right bound of the LinkNode */ public int getR() { return xPosR.get(); } /** * Returns the upper bound of the LinkNode * * @return the upper bound of the LinkNode */ public int getU() { return yPosU.get(); } /** * Returns the lower bound of the LinkNode * * @return the lower bound of the LinkNode */ public int getD() { return yPosD.get(); } /** * Tell each parent Link to update its line coordinates * */ public void updateLink() { for (Link link : connectedLinks) if (link != null) link.updateLine(); } /** * Link will be removed from this LinkNode, remove all instances of link * * @param link * to be removed */ public void removeMe(Link link) { while (connectedLinks.contains(link)) connectedLinks.remove(link); } /** * All links will be removed from this LinkNode * */ public void clearLinks() { connectedLinks.clear(); } /** * Returns an appropriate offset for the Link based on its index in the list of links connected to this LinkNode * ( offsets number pattern is such: 0, 1, -1, 2, -2, ... ) * * @param link * The link object that wants to know what its index is * * @return * The correct number in the series as derived from the index of the Link */ public int askNum(Link link) { int x = connectedLinks.indexOf(link); return (int) Math.ceil(((double)x)/((double)x%2==0?-2:2)); } }
UTF-8
Java
4,332
java
LinkNode.java
Java
[]
null
[]
package application.objects; import java.util.ArrayList; import java.util.List; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; public class LinkNode { private IntegerProperty xPos = new SimpleIntegerProperty(); private IntegerProperty yPos = new SimpleIntegerProperty(); private List<Link> connectedLinks; private IntegerProperty xPosL = new SimpleIntegerProperty(); private IntegerProperty xPosR = new SimpleIntegerProperty(); private IntegerProperty yPosU = new SimpleIntegerProperty(); private IntegerProperty yPosD = new SimpleIntegerProperty(); /** * Constructs an instance of LinkNode * * @constructor */ public LinkNode() { connectedLinks = new ArrayList<Link>(); } /** * Constructs an instance of LinkNode * * @constructor * @param x * the x position of the LinkNode * @param y * the y position of the LinkNode */ public LinkNode(int x, int y) { xPos.set(x); yPos.set(y); connectedLinks = new ArrayList<Link>(); } /** * Sets the x position of the LinkNode * * @param x * the x position to be set */ public void setX(int x) { xPos.set(x); } /** * Sets the y position of the LinkNode * * @param y * the y position to be set */ public void setY(int y) { yPos.set(y); } /** * Returns the x position of the LinkNode * * @return * the x position of the LinkNode */ public int getX() { return xPos.get(); } /** * Returns the y position of the LinkNode * * @return * the y position of the LinkNode */ public int getY() { return yPos.get(); } /** * Returns the xPos property of the LinkNode * * @return * the LinkNode's xPos property */ public IntegerProperty getXProperty() { return xPos; } /** * Returns the yPos property of the LinkNode * * @return * the LinkNode's yPos property */ public IntegerProperty getYProperty() { return yPos; } /** * Add the parent Link to the list of Links that originate from this LinkNode * * @param one * of the Links that uses this LinkNode */ public void giveParent(Link dad) { if (!connectedLinks.contains(dad)) connectedLinks.add(dad); } /** * Sets the 4 bounds of the LinkNode * * @param xL * the left bound to be set * @param xR * the right bound to be set * @param yU * the top bound to be set * @param yD * to bottom bound to be set */ public void setBounds(int xL, int xR, int yU, int yD) { xPosL.set(xL); xPosR.set(xR); yPosU.set(yU); yPosD.set(yD); } /** * Returns the left bound of the LinkNode * * @return the left bound of the LinkNode */ public int getL() { return xPosL.get(); } /** * Returns the right bound of the LinkNode * * @return the right bound of the LinkNode */ public int getR() { return xPosR.get(); } /** * Returns the upper bound of the LinkNode * * @return the upper bound of the LinkNode */ public int getU() { return yPosU.get(); } /** * Returns the lower bound of the LinkNode * * @return the lower bound of the LinkNode */ public int getD() { return yPosD.get(); } /** * Tell each parent Link to update its line coordinates * */ public void updateLink() { for (Link link : connectedLinks) if (link != null) link.updateLine(); } /** * Link will be removed from this LinkNode, remove all instances of link * * @param link * to be removed */ public void removeMe(Link link) { while (connectedLinks.contains(link)) connectedLinks.remove(link); } /** * All links will be removed from this LinkNode * */ public void clearLinks() { connectedLinks.clear(); } /** * Returns an appropriate offset for the Link based on its index in the list of links connected to this LinkNode * ( offsets number pattern is such: 0, 1, -1, 2, -2, ... ) * * @param link * The link object that wants to know what its index is * * @return * The correct number in the series as derived from the index of the Link */ public int askNum(Link link) { int x = connectedLinks.indexOf(link); return (int) Math.ceil(((double)x)/((double)x%2==0?-2:2)); } }
4,332
0.630886
0.628578
215
19.153488
20.13789
114
false
false
0
0
0
0
0
0
1.330233
false
false
9
66fe182cdd2032e1c45ce703543732714f53065e
21,809,843,940,170
10b0520506168ae807772b9061ea95e62f664522
/Dynamic Programming/BestTimeToBuyAndSellStockWithCooldown.java
5bf8bed645104b8f8de4b68abfadcb6a9ff28fd2
[]
no_license
jcohao/leetcode-notebook
https://github.com/jcohao/leetcode-notebook
e11884e67727b9f12fabdb5e54515944e4810ba0
5e4481ce67395a09dadfebfbd98b93005da2f804
refs/heads/master
2021-07-07T17:47:47.149000
2020-09-06T11:44:56
2020-09-06T11:44:56
182,337,229
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class BestTimeToBuyAndSellStockWithCooldown { /** * buy[i] 表示第 i 天之前最后一个操作是买,此时的最大收益 * sell[i] 表示第 i 天之前最后一个操作是卖,此时的最大收益 * rest[i] 表示第 i 天之前最后一个操作是冷冻期,此时的最大利益 * * 状态方程: * buy[i] = max(rest[i-1] - price, buy[i-1]) * sell[i] = max(buy[i-1] + price, sell[i-1]) * rest[i] = max(sell[i-1], buy[i-1], rest[i-1]) */ public int maxProfit(int[] prices) { if (prices == null || prices.length < 2) return 0; int len = prices.length; int[] buy = new int[len+1]; int[] sell = new int[len+1]; int[] rest = new int[len+1]; buy[0] = Integer.MIN_VALUE; for (int i = 0; i < len; i++) { buy[i+1] = Math.max(rest[i] - prices[i], buy[i]); sell[i+1] = Math.max(buy[i] + prices[i], sell[i]); rest[i+1] = Math.max(sell[i], Math.max(buy[i], rest[i])); } return sell[len]; } public static void main(String[] args) { BestTimeToBuyAndSellStockWithCooldown solution = new BestTimeToBuyAndSellStockWithCooldown(); System.out.println(solution.maxProfit(new int[]{1,2,3,0,2})); } }
UTF-8
Java
1,299
java
BestTimeToBuyAndSellStockWithCooldown.java
Java
[]
null
[]
class BestTimeToBuyAndSellStockWithCooldown { /** * buy[i] 表示第 i 天之前最后一个操作是买,此时的最大收益 * sell[i] 表示第 i 天之前最后一个操作是卖,此时的最大收益 * rest[i] 表示第 i 天之前最后一个操作是冷冻期,此时的最大利益 * * 状态方程: * buy[i] = max(rest[i-1] - price, buy[i-1]) * sell[i] = max(buy[i-1] + price, sell[i-1]) * rest[i] = max(sell[i-1], buy[i-1], rest[i-1]) */ public int maxProfit(int[] prices) { if (prices == null || prices.length < 2) return 0; int len = prices.length; int[] buy = new int[len+1]; int[] sell = new int[len+1]; int[] rest = new int[len+1]; buy[0] = Integer.MIN_VALUE; for (int i = 0; i < len; i++) { buy[i+1] = Math.max(rest[i] - prices[i], buy[i]); sell[i+1] = Math.max(buy[i] + prices[i], sell[i]); rest[i+1] = Math.max(sell[i], Math.max(buy[i], rest[i])); } return sell[len]; } public static void main(String[] args) { BestTimeToBuyAndSellStockWithCooldown solution = new BestTimeToBuyAndSellStockWithCooldown(); System.out.println(solution.maxProfit(new int[]{1,2,3,0,2})); } }
1,299
0.539462
0.520382
36
31.055555
24.992159
101
false
false
0
0
0
0
0
0
0.777778
false
false
9
104f4bbbbb4d421353ba4e7356e06e859d01bc74
21,809,843,938,506
9e04f576dac816818a390c957767f0a7546ff9c1
/traffic_service/src/main/java/com/reverie/service/impl/UserPlateApplyServiceImpl.java
3e7be8f992a549bfdd2a61f26e6bf71b26af3a95
[]
no_license
ReverieZH/TrafficeManage
https://github.com/ReverieZH/TrafficeManage
64570999a8ccab88d9d54c6d101b4fa4807d341b
8db782e6c12a728a65cb9a9585f76ab48d8c2543
refs/heads/master
2023-05-15T07:23:57.116000
2021-06-14T03:53:28
2021-06-14T03:53:28
370,409,349
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.reverie.service.impl; import com.reverie.domain.Userplateapply; import com.reverie.mapper.UserPlateApplyMapper; import com.reverie.service.UserPlateApplyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service("userPlateApplyService") @Transactional public class UserPlateApplyServiceImpl implements UserPlateApplyService { @Autowired private UserPlateApplyMapper userPlateApplyMapper; @Override public Userplateapply selectPlateApplyedByUser(String username) { return userPlateApplyMapper.selectPalteApply(username); } @Override public int save(Userplateapply userPlateApply) { return userPlateApplyMapper.insert(userPlateApply); } }
UTF-8
Java
835
java
UserPlateApplyServiceImpl.java
Java
[]
null
[]
package com.reverie.service.impl; import com.reverie.domain.Userplateapply; import com.reverie.mapper.UserPlateApplyMapper; import com.reverie.service.UserPlateApplyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service("userPlateApplyService") @Transactional public class UserPlateApplyServiceImpl implements UserPlateApplyService { @Autowired private UserPlateApplyMapper userPlateApplyMapper; @Override public Userplateapply selectPlateApplyedByUser(String username) { return userPlateApplyMapper.selectPalteApply(username); } @Override public int save(Userplateapply userPlateApply) { return userPlateApplyMapper.insert(userPlateApply); } }
835
0.813174
0.813174
26
31.115385
25.800011
74
false
false
0
0
0
0
0
0
0.384615
false
false
9
689b09709afc1b99bf15d9bd6e191b12216fb0ad
15,934,328,706,403
fbd12754a0625b0a60d4866f69fb9b2d1b773b74
/snapshot/other_code/Container/app/src/main/java/com/bm/container/module/login/AgreementActivity.java
0205aee4f6b9decb14e283eed070eab6f9998d58
[]
no_license
byprolujunyu/lujunyu
https://github.com/byprolujunyu/lujunyu
33229104421f3b77a10c3fafbaec264cc793b33e
3b0cfc22e9e1bea75a2b9ab6845e2d180423d5ac
refs/heads/master
2020-04-27T05:12:11.488000
2019-04-20T01:22:38
2019-04-20T01:22:38
174,075,009
85
18
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bm.container.module.login; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import com.bm.container.R; import com.bm.container.constants.ConstantsTag; import com.bm.container.databinding.ActivityAgreementBinding; import com.bm.container.module.BaseActivity; import org.simple.eventbus.EventBus; /** * P3_2注册协议 */ public class AgreementActivity extends BaseActivity { private ActivityAgreementBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_agreement); setTopbar(); setLoading(); initWeb(); // Collection.agreement(this, baseBean -> { // binding.web.loadUrl(baseBean.getData().toString()); // }); binding.web.loadUrl("http://www.findcontainer.cn/containerH5/agreement.html"); } /** * 预留js交互方法 */ @JavascriptInterface public void back() { // binding.refresh.setRefreshing(true); // Observable // .timer(1, TimeUnit.SECONDS) // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(aLong -> { // finishAc(); // binding.refresh.setRefreshing(false); // }); finishAc(); EventBus.getDefault().post("isCheckedTrue", ConstantsTag.IS_CHECKED_TRUE); } /** * 设定网页 */ private void initWeb() { WebSettings webSettings = binding.web.getSettings(); webSettings.setSavePassword(false); webSettings.setSaveFormData(false); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(false); webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); binding.web.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { binding.web.loadUrl(url); return true; } }); binding.web.addJavascriptInterface(AgreementActivity.this, "interface"); } private void setLoading() { setLoading(binding.refresh); binding.refresh.setEnabled(false); binding.refresh.setColorSchemeColors(loadingColors); } private void setTopbar() { binding.topbar.toolbar.setTitle(""); binding.topbar.toolbar.setNavigationIcon(R.drawable.toolbar_back); binding.topbar.title.setText(R.string.agreement_title); setSupportActionBar(binding.topbar.toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); binding.topbar.toolbar.setNavigationOnClickListener(view -> finishAc()); } /** * 如有视频,使用此方法停止播放 */ @Override protected void onPause() { binding.web.reload(); super.onPause(); } }
UTF-8
Java
3,039
java
AgreementActivity.java
Java
[]
null
[]
package com.bm.container.module.login; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import com.bm.container.R; import com.bm.container.constants.ConstantsTag; import com.bm.container.databinding.ActivityAgreementBinding; import com.bm.container.module.BaseActivity; import org.simple.eventbus.EventBus; /** * P3_2注册协议 */ public class AgreementActivity extends BaseActivity { private ActivityAgreementBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_agreement); setTopbar(); setLoading(); initWeb(); // Collection.agreement(this, baseBean -> { // binding.web.loadUrl(baseBean.getData().toString()); // }); binding.web.loadUrl("http://www.findcontainer.cn/containerH5/agreement.html"); } /** * 预留js交互方法 */ @JavascriptInterface public void back() { // binding.refresh.setRefreshing(true); // Observable // .timer(1, TimeUnit.SECONDS) // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(aLong -> { // finishAc(); // binding.refresh.setRefreshing(false); // }); finishAc(); EventBus.getDefault().post("isCheckedTrue", ConstantsTag.IS_CHECKED_TRUE); } /** * 设定网页 */ private void initWeb() { WebSettings webSettings = binding.web.getSettings(); webSettings.setSavePassword(false); webSettings.setSaveFormData(false); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(false); webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); binding.web.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { binding.web.loadUrl(url); return true; } }); binding.web.addJavascriptInterface(AgreementActivity.this, "interface"); } private void setLoading() { setLoading(binding.refresh); binding.refresh.setEnabled(false); binding.refresh.setColorSchemeColors(loadingColors); } private void setTopbar() { binding.topbar.toolbar.setTitle(""); binding.topbar.toolbar.setNavigationIcon(R.drawable.toolbar_back); binding.topbar.title.setText(R.string.agreement_title); setSupportActionBar(binding.topbar.toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); binding.topbar.toolbar.setNavigationOnClickListener(view -> finishAc()); } /** * 如有视频,使用此方法停止播放 */ @Override protected void onPause() { binding.web.reload(); super.onPause(); } }
3,039
0.674489
0.673148
97
29.752577
23.378567
86
false
false
0
0
0
0
0
0
0.979381
false
false
9
3a2be5247547f327666e4f6dce559c81d910fd9a
10,625,749,152,203
bd550ab5e7e96207e9b15bf3402afd7b93a51908
/src/main/java/michal/odpadyapi/Entity/KodyOdpadow.java
55a6c1ebc22628cd2623e9d26c1a5f1225ace99f
[]
no_license
michalzst/odpady-api
https://github.com/michalzst/odpady-api
542e1d0368246f447c5901bdc7211da310845972
2d62c35ce5146f913987332ece6473b878fbdd3c
refs/heads/master
2022-02-11T18:25:54.507000
2019-06-28T16:27:40
2019-06-28T16:27:40
194,301,162
0
0
null
false
2022-01-21T23:26:22
2019-06-28T16:08:18
2019-06-28T16:27:51
2022-01-21T23:26:20
9
0
0
1
Java
false
false
package michal.odpadyapi.Entity; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import javax.persistence.*; @Entity public class KodyOdpadow { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String kodOdpadu; private String nazwaOdpadu; private boolean aktywny; // @ManyToOne // @JoinColumn(name = "kodyOdpadow", nullable = false) // @OnDelete(action = OnDeleteAction.CASCADE) // @JsonIgnore // private Posiadacz posiadacz; // public Posiadacz getPosiadacz() { // return posiadacz; // } // // public void setPosiadacz(Posiadacz posiadacz) { // this.posiadacz = posiadacz; // } public KodyOdpadow() { } public KodyOdpadow(String kodOdpadu, String nazwaOdpadu, boolean aktywny) { this.kodOdpadu = kodOdpadu; this.nazwaOdpadu = nazwaOdpadu; this.aktywny = aktywny; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getKodOdpadu() { return kodOdpadu; } public void setKodOdpadu(String kodOdpadu) { this.kodOdpadu = kodOdpadu; } public String getNazwaOdpadu() { return nazwaOdpadu; } public void setNazwaOdpadu(String nazwaOdpadu) { this.nazwaOdpadu = nazwaOdpadu; } public boolean isAktywny() { return aktywny; } public void setAktywny(boolean aktywny) { this.aktywny = aktywny; } }
UTF-8
Java
1,605
java
KodyOdpadow.java
Java
[]
null
[]
package michal.odpadyapi.Entity; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import javax.persistence.*; @Entity public class KodyOdpadow { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String kodOdpadu; private String nazwaOdpadu; private boolean aktywny; // @ManyToOne // @JoinColumn(name = "kodyOdpadow", nullable = false) // @OnDelete(action = OnDeleteAction.CASCADE) // @JsonIgnore // private Posiadacz posiadacz; // public Posiadacz getPosiadacz() { // return posiadacz; // } // // public void setPosiadacz(Posiadacz posiadacz) { // this.posiadacz = posiadacz; // } public KodyOdpadow() { } public KodyOdpadow(String kodOdpadu, String nazwaOdpadu, boolean aktywny) { this.kodOdpadu = kodOdpadu; this.nazwaOdpadu = nazwaOdpadu; this.aktywny = aktywny; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getKodOdpadu() { return kodOdpadu; } public void setKodOdpadu(String kodOdpadu) { this.kodOdpadu = kodOdpadu; } public String getNazwaOdpadu() { return nazwaOdpadu; } public void setNazwaOdpadu(String nazwaOdpadu) { this.nazwaOdpadu = nazwaOdpadu; } public boolean isAktywny() { return aktywny; } public void setAktywny(boolean aktywny) { this.aktywny = aktywny; } }
1,605
0.649844
0.649844
73
20.986301
18.979797
79
false
false
0
0
0
0
0
0
0.356164
false
false
9
185c5772fe4d3b990da52313fe5a980c5d85cd1c
10,058,813,421,929
3ff2b105bc6854984a9aace8d71fc11a1e91d5f0
/src/main/java/com/smates/dbc2/po/TblCropPattern.java
26fa94fe348c91682fc9ab8504710f0e7ef75541
[ "Apache-2.0" ]
permissive
MarchMachao/watershed
https://github.com/MarchMachao/watershed
d0fa09012398a4672bfb2e13513c9844d48d75b3
401da957e018a2eebb582d0f1542f88f1346d08f
refs/heads/master
2021-01-19T13:37:31.985000
2017-08-20T13:43:48
2017-08-20T13:43:48
100,847,839
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.smates.dbc2.po; import java.util.UUID; /** * 种植结构数据表 * * @author machao * */ public class TblCropPattern { private String id; private String fldWatershedCode; private String fldCountyCode; private String fldDate; private String fldCropType; private double fldCropArea; private double fldIrrQuota; private double fldFertilizer; private double fldYieldPer; private double fldCropPrice; public TblCropPattern() { } public TblCropPattern(String fldWatershedCode, String fldCountyCode, String fldDate, String fldCropType, double fldCropArea, double fldIrrQuota, double fldFertilizer, double fldYieldPer, double fldCropPrice) { this.id = UUID.randomUUID().toString(); this.fldWatershedCode = fldWatershedCode; this.fldCountyCode = fldCountyCode; this.fldDate = fldDate; this.fldCropType = fldCropType; this.fldCropArea = fldCropArea; this.fldIrrQuota = fldIrrQuota; this.fldFertilizer = fldFertilizer; this.fldYieldPer = fldYieldPer; this.fldCropPrice = fldCropPrice; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFldWatershedCode() { return fldWatershedCode; } public void setFldWatershedCode(String fldWatershedCode) { this.fldWatershedCode = fldWatershedCode; } public String getFldCountyCode() { return fldCountyCode; } public void setFldCountyCode(String fldCountyCode) { this.fldCountyCode = fldCountyCode; } public String getFldDate() { return fldDate; } public void setFldDate(String fldDate) { this.fldDate = fldDate; } public String getFldCropType() { return fldCropType; } public void setFldCropType(String fldCropType) { this.fldCropType = fldCropType; } public double getFldCropArea() { return fldCropArea; } public void setFldCropArea(double fldCropArea) { this.fldCropArea = fldCropArea; } public double getFldIrrQuota() { return fldIrrQuota; } public void setFldIrrQuota(double fldIrrQuota) { this.fldIrrQuota = fldIrrQuota; } public double getFldFertilizer() { return fldFertilizer; } public void setFldFertilizer(double fldFertilizer) { this.fldFertilizer = fldFertilizer; } public double getFldYieldPer() { return fldYieldPer; } public void setFldYieldPer(double fldYieldPer) { this.fldYieldPer = fldYieldPer; } public double getFldCropPrice() { return fldCropPrice; } public void setFldCropPrice(double fldCropPrice) { this.fldCropPrice = fldCropPrice; } }
UTF-8
Java
2,626
java
TblCropPattern.java
Java
[ { "context": "ava.util.UUID;\r\n\r\n/**\r\n * 种植结构数据表\r\n * \r\n * @author machao\r\n *\r\n */\r\npublic class TblCropPattern {\r\n\r\n\tpriva", "end": 96, "score": 0.8759039640426636, "start": 90, "tag": "USERNAME", "value": "machao" } ]
null
[]
package com.smates.dbc2.po; import java.util.UUID; /** * 种植结构数据表 * * @author machao * */ public class TblCropPattern { private String id; private String fldWatershedCode; private String fldCountyCode; private String fldDate; private String fldCropType; private double fldCropArea; private double fldIrrQuota; private double fldFertilizer; private double fldYieldPer; private double fldCropPrice; public TblCropPattern() { } public TblCropPattern(String fldWatershedCode, String fldCountyCode, String fldDate, String fldCropType, double fldCropArea, double fldIrrQuota, double fldFertilizer, double fldYieldPer, double fldCropPrice) { this.id = UUID.randomUUID().toString(); this.fldWatershedCode = fldWatershedCode; this.fldCountyCode = fldCountyCode; this.fldDate = fldDate; this.fldCropType = fldCropType; this.fldCropArea = fldCropArea; this.fldIrrQuota = fldIrrQuota; this.fldFertilizer = fldFertilizer; this.fldYieldPer = fldYieldPer; this.fldCropPrice = fldCropPrice; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFldWatershedCode() { return fldWatershedCode; } public void setFldWatershedCode(String fldWatershedCode) { this.fldWatershedCode = fldWatershedCode; } public String getFldCountyCode() { return fldCountyCode; } public void setFldCountyCode(String fldCountyCode) { this.fldCountyCode = fldCountyCode; } public String getFldDate() { return fldDate; } public void setFldDate(String fldDate) { this.fldDate = fldDate; } public String getFldCropType() { return fldCropType; } public void setFldCropType(String fldCropType) { this.fldCropType = fldCropType; } public double getFldCropArea() { return fldCropArea; } public void setFldCropArea(double fldCropArea) { this.fldCropArea = fldCropArea; } public double getFldIrrQuota() { return fldIrrQuota; } public void setFldIrrQuota(double fldIrrQuota) { this.fldIrrQuota = fldIrrQuota; } public double getFldFertilizer() { return fldFertilizer; } public void setFldFertilizer(double fldFertilizer) { this.fldFertilizer = fldFertilizer; } public double getFldYieldPer() { return fldYieldPer; } public void setFldYieldPer(double fldYieldPer) { this.fldYieldPer = fldYieldPer; } public double getFldCropPrice() { return fldCropPrice; } public void setFldCropPrice(double fldCropPrice) { this.fldCropPrice = fldCropPrice; } }
2,626
0.718224
0.717841
122
19.409836
20.290817
107
false
false
0
0
0
0
0
0
1.368852
false
false
9
1e8bc6b5e82d0e91a33df057a81f27f7c6c180d0
17,841,294,172,378
75540062734636fbbd8684c3ea399d64d83087bb
/MiniNetAssignment2/src/NotBeClassmatesException.java
9775b193988ad4d2e1ecaf1d1f8e3e12c6569238
[]
no_license
rmit-s3639923-Yining-Chen/Assignment2
https://github.com/rmit-s3639923-Yining-Chen/Assignment2
f6f0f5cabc4e66f0328d6ee217b3fd99cd3fce2c
55908e076b730bbd4a2934aa16247ff6d2ee2685
refs/heads/master
2020-03-17T14:07:13.240000
2018-05-21T14:38:31
2018-05-21T14:38:31
133,659,094
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * This is NotBeClassmatesException class * * @version 1.00 14 May 2018 * @author Yining Chen */ public class NotBeClassmatesException extends Exception{ public NotBeClassmatesException() { super("One is not Adult!"); } }
UTF-8
Java
232
java
NotBeClassmatesException.java
Java
[ { "context": "ion class \n*\n* @version 1.00 14 May 2018\n* @author Yining Chen\n*/\npublic class NotBeClassmatesException extends ", "end": 97, "score": 0.9984805583953857, "start": 86, "tag": "NAME", "value": "Yining Chen" } ]
null
[]
/** * This is NotBeClassmatesException class * * @version 1.00 14 May 2018 * @author <NAME> */ public class NotBeClassmatesException extends Exception{ public NotBeClassmatesException() { super("One is not Adult!"); } }
227
0.728448
0.689655
12
18.333334
18.354534
56
false
false
0
0
0
0
0
0
0.5
false
false
9
68a42733311332a35462121ccf10e7be2d71d17a
17,841,294,173,767
b061924f1a304355e79fefa735485dfeb9f4d349
/src/com/wenyuankeji/spring/dao/impl/BaseRequestkeyrecordDaoImpl.java
9ad26b221e140d5a051f5b40ad4ecf9eb89cd5db
[]
no_license
EvilCodes/ShunJianMeiWeb
https://github.com/EvilCodes/ShunJianMeiWeb
7895373bfcdc9f824267eec1d0a98e6eaeee343e
7a4f3bf7c1c675b7ad8f0f62414c3c006178de5c
refs/heads/master
2021-01-18T16:08:41.157000
2017-03-30T14:59:42
2017-03-30T14:59:42
86,715,440
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wenyuankeji.spring.dao.impl; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; import com.wenyuankeji.spring.dao.IBaseRequestKeyRecordDao; import com.wenyuankeji.spring.model.BaseRequestKeyRecord; import com.wenyuankeji.spring.util.BaseException; @Repository public class BaseRequestkeyrecordDaoImpl implements IBaseRequestKeyRecordDao { @Resource(name = "sessionFactory") private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public int addBaseRequestKeyRecord(BaseRequestKeyRecord o) throws BaseException { try { Session session = sessionFactory.getCurrentSession(); Integer id = (Integer) session.save(o); return id; }catch (Exception e) { throw new BaseException(e.getMessage()); } } @Override public boolean selectBaseRequestKeyRecord(String keystring) throws BaseException { try { Session session = sessionFactory.getCurrentSession(); String hql = "FROM BaseRequestKeyRecord WHERE keystring=? "; Query query = session.createQuery(hql); query.setString(0, keystring); if (query.list() !=null && query.list().size() > 0) { return true; } }catch (Exception e) { throw new BaseException(e.getMessage()); } return false; } }
UTF-8
Java
1,439
java
BaseRequestkeyrecordDaoImpl.java
Java
[]
null
[]
package com.wenyuankeji.spring.dao.impl; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; import com.wenyuankeji.spring.dao.IBaseRequestKeyRecordDao; import com.wenyuankeji.spring.model.BaseRequestKeyRecord; import com.wenyuankeji.spring.util.BaseException; @Repository public class BaseRequestkeyrecordDaoImpl implements IBaseRequestKeyRecordDao { @Resource(name = "sessionFactory") private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public int addBaseRequestKeyRecord(BaseRequestKeyRecord o) throws BaseException { try { Session session = sessionFactory.getCurrentSession(); Integer id = (Integer) session.save(o); return id; }catch (Exception e) { throw new BaseException(e.getMessage()); } } @Override public boolean selectBaseRequestKeyRecord(String keystring) throws BaseException { try { Session session = sessionFactory.getCurrentSession(); String hql = "FROM BaseRequestKeyRecord WHERE keystring=? "; Query query = session.createQuery(hql); query.setString(0, keystring); if (query.list() !=null && query.list().size() > 0) { return true; } }catch (Exception e) { throw new BaseException(e.getMessage()); } return false; } }
1,439
0.766505
0.765115
50
27.780001
24.658703
83
false
false
0
0
0
0
0
0
1.78
false
false
9
313ceb22351058c6308d7004355bcab39adc2a74
6,975,026,927,905
b59e62ab7e4b59b037262c38966c7562aaaff5fe
/app/src/main/java/com/example/administrator/filtiration/MainActivity.java
5127e6f2d4e8aadff403105a57e9c33033784660
[]
no_license
KiroAlbear/Filtiration
https://github.com/KiroAlbear/Filtiration
450957377aef1c3420c58702f93c649a61cbc21d
2b3cbaef15a6d7e9a6b65a93613b3688c399899c
refs/heads/master
2020-03-22T18:20:24.441000
2018-07-11T14:46:18
2018-07-11T14:46:18
140,453,355
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.administrator.filtiration; import android.databinding.DataBindingUtil; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.administrator.filtiration.Model.UsersList; import com.example.administrator.filtiration.ViewModel.myAdapter; import com.example.administrator.filtiration.ViewModel.myViewModel; import com.example.administrator.filtiration.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { ActivityMainBinding activityMainBinding; myAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); UsersList usersList = new UsersList(); activityMainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main); RecyclerView recyclerView = findViewById(R.id.myRecycleView); EditText editText = (EditText)findViewById(R.id.editText); adapter = new myAdapter(usersList.AdingUsersList()); final myViewModel viewModel = new myViewModel( this,recyclerView,adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(adapter); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { viewModel.SearchList(charSequence.toString()); //Toast.makeText(getApplicationContext(),charSequence.toString(),Toast.LENGTH_SHORT).show(); } @Override public void afterTextChanged(Editable editable) { } }); } }
UTF-8
Java
2,277
java
MainActivity.java
Java
[]
null
[]
package com.example.administrator.filtiration; import android.databinding.DataBindingUtil; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.administrator.filtiration.Model.UsersList; import com.example.administrator.filtiration.ViewModel.myAdapter; import com.example.administrator.filtiration.ViewModel.myViewModel; import com.example.administrator.filtiration.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { ActivityMainBinding activityMainBinding; myAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); UsersList usersList = new UsersList(); activityMainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main); RecyclerView recyclerView = findViewById(R.id.myRecycleView); EditText editText = (EditText)findViewById(R.id.editText); adapter = new myAdapter(usersList.AdingUsersList()); final myViewModel viewModel = new myViewModel( this,recyclerView,adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(adapter); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { viewModel.SearchList(charSequence.toString()); //Toast.makeText(getApplicationContext(),charSequence.toString(),Toast.LENGTH_SHORT).show(); } @Override public void afterTextChanged(Editable editable) { } }); } }
2,277
0.692578
0.689504
65
33.984615
30.811333
113
false
false
0
0
0
0
0
0
0.646154
false
false
9
72e26f96d8ea2882e8e8d65421660787e60c41e5
32,478,542,736,497
4896c8b595e50e3bef53a9dbda1e54148be769ad
/CurrentAccount.java
9a2d8ce516c7ad77691c2fccda04e84d3d465f1f
[]
no_license
harshita-p05/HarshitaP_QAT
https://github.com/harshita-p05/HarshitaP_QAT
8b473a5fa1fa16d4e52657cfe834ef0caed66adf
2c0320a4a7311c05e706a51880fbb5706e4ff955
refs/heads/main
2023-07-14T01:37:38.717000
2021-08-20T04:41:47
2021-08-20T04:41:47
397,892,695
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package QatTest_HarshitaP; public class CurrentAccount implements BankAccount { @Override public void checkBankBalance() { System.out.println("check balance in the current account"); } @Override public void validateUser() { System.out.println("Validate user in the current account"); } }
UTF-8
Java
331
java
CurrentAccount.java
Java
[]
null
[]
package QatTest_HarshitaP; public class CurrentAccount implements BankAccount { @Override public void checkBankBalance() { System.out.println("check balance in the current account"); } @Override public void validateUser() { System.out.println("Validate user in the current account"); } }
331
0.685801
0.685801
19
15.421053
21.092068
61
false
false
0
0
0
0
0
0
1
false
false
9
e0fd8e27b7e2df30ac69d8cb5677ea7baf2d240f
26,319,559,632,943
8949d6056aa60cff1952e59b4c745c25f2555a3f
/app/src/main/java/com/example/daniel/findgym/activity/CadastroModalidadeActivity.java
a0d5dd37927253a5ce1c197d98a6e385941c8999
[]
no_license
Daniel-1993/FindGym
https://github.com/Daniel-1993/FindGym
b2383665d9cbc8e7ba35bd616d19c1ceeaa773af
c1b2e291e5e41f852f4827237de0c8cee1f99ba5
refs/heads/master
2021-01-23T01:12:59.626000
2017-03-26T21:25:19
2017-03-26T21:25:19
85,889,303
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.daniel.findgym.activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.example.daniel.findgym.R; import com.example.daniel.findgym.model.Modalidade; import com.example.daniel.findgym.model.Treinador; import java.util.ArrayList; public class CadastroModalidadeActivity extends AppCompatActivity { EditText edtDescricao; Spinner spnTreinador; int id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cadastro_modalidade); final ArrayList<Treinador> treinadores = (ArrayList) Treinador.listAll(Treinador.class); ArrayAdapter<Treinador> adapter = new ArrayAdapter<Treinador>(this, android.R.layout.simple_spinner_item, treinadores); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spnTreinador = (Spinner) findViewById(R.id.spnTreinador); spnTreinador.setAdapter(adapter); edtDescricao = (EditText) findViewById(R.id.edtDescricao); Button btnSalvarModalidade = (Button) findViewById(R.id.btnSalvarModalidade); Button btnEditarModadlidade = (Button) findViewById(R.id.btnEditarModadlidade); Button btnExcluirModalidade = (Button) findViewById(R.id.btnExcluirModalidade); btnSalvarModalidade.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { salvar(); } }); btnEditarModadlidade.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); btnExcluirModalidade.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); } public void salvar(){ Treinador treinador = ((Treinador)spnTreinador.getSelectedItem()); Modalidade modalidade = new Modalidade(edtDescricao.getText().toString(), treinador); modalidade.save(); Toast.makeText(this,"Modalidade Cadastrada", Toast.LENGTH_LONG).show(); this.finish(); } }
UTF-8
Java
2,464
java
CadastroModalidadeActivity.java
Java
[ { "context": "package com.example.daniel.findgym.activity;\n\nimport android.content.Intent;", "end": 26, "score": 0.5235903263092041, "start": 20, "tag": "USERNAME", "value": "daniel" }, { "context": "\nimport android.widget.Toast;\n\nimport com.example.daniel.findgym.R;\nimport com.example.daniel.findgym.mode", "end": 362, "score": 0.569259524345398, "start": 356, "tag": "USERNAME", "value": "daniel" }, { "context": " com.example.daniel.findgym.R;\nimport com.example.daniel.findgym.model.Modalidade;\nimport com.example.dani", "end": 399, "score": 0.7045726180076599, "start": 393, "tag": "USERNAME", "value": "daniel" }, { "context": "niel.findgym.model.Modalidade;\nimport com.example.daniel.findgym.model.Treinador;\n\nimport java.util.ArrayL", "end": 451, "score": 0.7462137341499329, "start": 445, "tag": "USERNAME", "value": "daniel" } ]
null
[]
package com.example.daniel.findgym.activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.example.daniel.findgym.R; import com.example.daniel.findgym.model.Modalidade; import com.example.daniel.findgym.model.Treinador; import java.util.ArrayList; public class CadastroModalidadeActivity extends AppCompatActivity { EditText edtDescricao; Spinner spnTreinador; int id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cadastro_modalidade); final ArrayList<Treinador> treinadores = (ArrayList) Treinador.listAll(Treinador.class); ArrayAdapter<Treinador> adapter = new ArrayAdapter<Treinador>(this, android.R.layout.simple_spinner_item, treinadores); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spnTreinador = (Spinner) findViewById(R.id.spnTreinador); spnTreinador.setAdapter(adapter); edtDescricao = (EditText) findViewById(R.id.edtDescricao); Button btnSalvarModalidade = (Button) findViewById(R.id.btnSalvarModalidade); Button btnEditarModadlidade = (Button) findViewById(R.id.btnEditarModadlidade); Button btnExcluirModalidade = (Button) findViewById(R.id.btnExcluirModalidade); btnSalvarModalidade.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { salvar(); } }); btnEditarModadlidade.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); btnExcluirModalidade.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); } public void salvar(){ Treinador treinador = ((Treinador)spnTreinador.getSelectedItem()); Modalidade modalidade = new Modalidade(edtDescricao.getText().toString(), treinador); modalidade.save(); Toast.makeText(this,"Modalidade Cadastrada", Toast.LENGTH_LONG).show(); this.finish(); } }
2,464
0.698458
0.698052
82
29.04878
30.740021
127
false
false
0
0
0
0
0
0
0.512195
false
false
9
3ef35ee705b92ab0dbb06b37859bbb14c76e0ecd
8,040,178,804,201
29633595199f3907872f162f6360b99d95af6370
/app/src/main/java/com/hit/zhou/scanmachine/common/http/StringCallback.java
f31480095942462e50990a21ca9ff489fb44b3c9
[]
no_license
BigPig-LittleTail/Scanmachine
https://github.com/BigPig-LittleTail/Scanmachine
a894d9600796f0af42476c6469408a335e63596b
e4f3948d5a07578b90eeb14b0a0f3ef6a75e916d
refs/heads/master
2020-04-07T04:45:16.395000
2018-11-18T09:57:53
2018-11-18T09:57:53
158,070,076
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hit.zhou.scanmachine.common.http; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import com.google.gson.Gson; import java.io.IOException; import java.lang.ref.WeakReference; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * Created by zhou on 2018/11/8. */ public abstract class StringCallback implements Callback{ @Override public void onFailure(Call call, IOException e) { onFailure(); } @Override public void onResponse(Call call, Response response) throws IOException { String josnResult = response.body().string(); Gson gson = new Gson(); String result = gson.fromJson(josnResult,String.class); Log.e("result",josnResult); onResponse(result); } public abstract void onResponse(String result); public abstract void onFailure(); }
UTF-8
Java
922
java
StringCallback.java
Java
[ { "context": "lback;\nimport okhttp3.Response;\n\n/**\n * Created by zhou on 2018/11/8.\n */\n\npublic abstract class StringCa", "end": 342, "score": 0.9994843602180481, "start": 338, "tag": "USERNAME", "value": "zhou" } ]
null
[]
package com.hit.zhou.scanmachine.common.http; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import com.google.gson.Gson; import java.io.IOException; import java.lang.ref.WeakReference; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * Created by zhou on 2018/11/8. */ public abstract class StringCallback implements Callback{ @Override public void onFailure(Call call, IOException e) { onFailure(); } @Override public void onResponse(Call call, Response response) throws IOException { String josnResult = response.body().string(); Gson gson = new Gson(); String result = gson.fromJson(josnResult,String.class); Log.e("result",josnResult); onResponse(result); } public abstract void onResponse(String result); public abstract void onFailure(); }
922
0.708243
0.697397
38
23.236841
20.410826
77
false
false
0
0
0
0
0
0
0.605263
false
false
9
de96475b96e367d0892901cd2d59b94b65667400
32,822,140,098,451
1b208619f5c70196ddef57724eab1da64fc9ef3f
/SpringMVCApplication/src/main/java/com/dao/SignUpDao.java
62afbf343d290dd659253c5cba670d52f1ff7794
[]
no_license
PRAKASH4150/HCL_JAVA_Assignments_Mode1
https://github.com/PRAKASH4150/HCL_JAVA_Assignments_Mode1
5e67ea8054b7474900e53b39baabc64933954525
7a42ac0462071473340d193635fb673105231e55
refs/heads/master
2023-02-05T02:08:40.088000
2020-12-23T17:12:54
2020-12-23T17:12:54
311,353,466
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dao; import com.model.SignUp; public interface SignUpDao { public void createAccount(SignUp signUp); public boolean doesAccountExists(SignUp signUp); }
UTF-8
Java
169
java
SignUpDao.java
Java
[]
null
[]
package com.dao; import com.model.SignUp; public interface SignUpDao { public void createAccount(SignUp signUp); public boolean doesAccountExists(SignUp signUp); }
169
0.792899
0.792899
9
17.777779
18.066406
49
false
false
0
0
0
0
0
0
0.666667
false
false
9
721ed40f0ece1ab4971f0a4b36279ea431f0da91
25,847,113,209,984
f27cd4bcf1afa0163b623045a291fcbc348deb13
/src/main/java/com/example/demo/service/ImageParsingService.java
b1e50c50aa0464d2f66bfe624ca81ce98439fa9f
[]
no_license
KevinSilvaQuintana/mrz-parser-hackathon
https://github.com/KevinSilvaQuintana/mrz-parser-hackathon
8fa54c0664010a291c50e6c7e5399e75b287a015
e5485e3209b7b946c7b513c50823c1c0e2f5d306
refs/heads/master
2020-04-07T03:58:35.719000
2018-11-18T14:54:43
2018-11-18T14:54:43
158,035,685
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.service; import com.example.demo.model.ParsingResult; import com.google.cloud.vision.v1.*; import com.google.protobuf.ByteString; import org.joda.time.DateTime; import org.springframework.stereotype.Service; import javax.xml.bind.DatatypeConverter; import java.io.*; import java.util.ArrayList; import java.util.List; //TODO: apply filter to image. //TODO: if confidence is below threshold, highlight it in red. @Service public class ImageParsingService { private static final String IMAGES_DIR = System.getProperty("user.home") + File.separator + "Documents" + File.separator + "hackathonImages"; public static final ParsingResult BAD_PARSING_RESULT = new ParsingResult(0, null); public ParsingResult parseImageFromBase64String(String imageAsBase64) throws IOException { String[] strings = imageAsBase64.split(","); String header = strings[0]; File imagefile = new File(getImagesDir(IMAGES_DIR), "Image_" + DateTime.now().getMillis() + "." + getFileExtension(header)); //convert base64 string to binary data byte[] data = DatatypeConverter.parseBase64Binary(strings[1]); try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(imagefile))) { outputStream.write(data); } String successMessage = "Created file: " + imagefile.toString(); System.out.println(successMessage); return callGoogleCloudImageParsing(imagefile); } private File getImagesDir(String path) { File hackathonImagesDirectory = new File(path); if (hackathonImagesDirectory.exists()) { System.out.println(hackathonImagesDirectory + " already exists"); } else if (hackathonImagesDirectory.mkdirs()) { System.out.println(hackathonImagesDirectory + " was created"); } else { System.out.println(hackathonImagesDirectory + " was not created"); } return hackathonImagesDirectory; } public ParsingResult callGoogleCloudImageParsing(File file) throws IOException { List<AnnotateImageRequest> requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(file)); Image img = Image.newBuilder().setContent(imgBytes).build(); Feature feat = Feature.newBuilder().setType(Feature.Type.DOCUMENT_TEXT_DETECTION).build(); ImageContext imageContext = ImageContext.newBuilder() .addLanguageHints("fr") .build(); AnnotateImageRequest request = AnnotateImageRequest.newBuilder() .addFeatures(feat) .setImageContext(imageContext) .setImage(img) .build(); requests.add(request); try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List<AnnotateImageResponse> responses = response.getResponsesList(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { System.out.printf("Error: %s\n", res.getError().getMessage()); return null; } float totalConfidence = 0; // For full list of available annotations, see http://g.co/cloud/vision/docs TextAnnotation annotation = res.getFullTextAnnotation(); for (Page page : annotation.getPagesList()) { String pageText = ""; for (Block block : page.getBlocksList()) { String blockText = ""; for (Paragraph para : block.getParagraphsList()) { String paraText = ""; for (Word word : para.getWordsList()) { String wordText = ""; for (Symbol character : word.getSymbolsList()) { wordText = wordText + character.getText(); System.out.format( "Char: %s (confidence: %f)\n", character.getText(), character.getConfidence()); } System.out.format("Word text: %s (confidence: %f)\n\n", wordText, word.getConfidence()); paraText = String.format("%s %s", paraText, wordText); } // Output Example using Paragraph: System.out.println("\nParagraph: \n" + paraText); System.out.format("Paragraph Confidence: %f\n", para.getConfidence()); blockText = blockText + paraText; totalConfidence = para.getConfidence(); } pageText = pageText + blockText; } } System.out.println("\nComplete annotation:"); String parsedText = annotation.getText(); System.out.println("BEFORE: "); System.out.println(parsedText); String[] split = parsedText.split("\n"); // wrong MRZ if(split.length != 2) { return BAD_PARSING_RESULT; } String firstPart = fixSpacingIssues(0, split); String secondPart = fixSpacingIssues(1, split); secondPart = secondPart.replace("O", "0"); String fixedMrz = firstPart + "\n" + secondPart; System.out.println("AFTER: "); System.out.println(fixedMrz); return new ParsingResult(totalConfidence, fixedMrz); } } return BAD_PARSING_RESULT; } private String fixSpacingIssues(int i, String[] split) { return (split[i].length() <= 44) ? split[i].replace(" ", "<") : split[i].replace(" ", ""); } private String getFileExtension(String header) { String extension; //check image's extension switch (header) { case "data:image/jpeg;base64": extension = "jpeg"; break; case "data:image/png;base64": extension = "png"; break; default://should write cases for more images types extension = "jpg"; break; } return extension; } }
UTF-8
Java
6,672
java
ImageParsingService.java
Java
[]
null
[]
package com.example.demo.service; import com.example.demo.model.ParsingResult; import com.google.cloud.vision.v1.*; import com.google.protobuf.ByteString; import org.joda.time.DateTime; import org.springframework.stereotype.Service; import javax.xml.bind.DatatypeConverter; import java.io.*; import java.util.ArrayList; import java.util.List; //TODO: apply filter to image. //TODO: if confidence is below threshold, highlight it in red. @Service public class ImageParsingService { private static final String IMAGES_DIR = System.getProperty("user.home") + File.separator + "Documents" + File.separator + "hackathonImages"; public static final ParsingResult BAD_PARSING_RESULT = new ParsingResult(0, null); public ParsingResult parseImageFromBase64String(String imageAsBase64) throws IOException { String[] strings = imageAsBase64.split(","); String header = strings[0]; File imagefile = new File(getImagesDir(IMAGES_DIR), "Image_" + DateTime.now().getMillis() + "." + getFileExtension(header)); //convert base64 string to binary data byte[] data = DatatypeConverter.parseBase64Binary(strings[1]); try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(imagefile))) { outputStream.write(data); } String successMessage = "Created file: " + imagefile.toString(); System.out.println(successMessage); return callGoogleCloudImageParsing(imagefile); } private File getImagesDir(String path) { File hackathonImagesDirectory = new File(path); if (hackathonImagesDirectory.exists()) { System.out.println(hackathonImagesDirectory + " already exists"); } else if (hackathonImagesDirectory.mkdirs()) { System.out.println(hackathonImagesDirectory + " was created"); } else { System.out.println(hackathonImagesDirectory + " was not created"); } return hackathonImagesDirectory; } public ParsingResult callGoogleCloudImageParsing(File file) throws IOException { List<AnnotateImageRequest> requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(file)); Image img = Image.newBuilder().setContent(imgBytes).build(); Feature feat = Feature.newBuilder().setType(Feature.Type.DOCUMENT_TEXT_DETECTION).build(); ImageContext imageContext = ImageContext.newBuilder() .addLanguageHints("fr") .build(); AnnotateImageRequest request = AnnotateImageRequest.newBuilder() .addFeatures(feat) .setImageContext(imageContext) .setImage(img) .build(); requests.add(request); try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List<AnnotateImageResponse> responses = response.getResponsesList(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { System.out.printf("Error: %s\n", res.getError().getMessage()); return null; } float totalConfidence = 0; // For full list of available annotations, see http://g.co/cloud/vision/docs TextAnnotation annotation = res.getFullTextAnnotation(); for (Page page : annotation.getPagesList()) { String pageText = ""; for (Block block : page.getBlocksList()) { String blockText = ""; for (Paragraph para : block.getParagraphsList()) { String paraText = ""; for (Word word : para.getWordsList()) { String wordText = ""; for (Symbol character : word.getSymbolsList()) { wordText = wordText + character.getText(); System.out.format( "Char: %s (confidence: %f)\n", character.getText(), character.getConfidence()); } System.out.format("Word text: %s (confidence: %f)\n\n", wordText, word.getConfidence()); paraText = String.format("%s %s", paraText, wordText); } // Output Example using Paragraph: System.out.println("\nParagraph: \n" + paraText); System.out.format("Paragraph Confidence: %f\n", para.getConfidence()); blockText = blockText + paraText; totalConfidence = para.getConfidence(); } pageText = pageText + blockText; } } System.out.println("\nComplete annotation:"); String parsedText = annotation.getText(); System.out.println("BEFORE: "); System.out.println(parsedText); String[] split = parsedText.split("\n"); // wrong MRZ if(split.length != 2) { return BAD_PARSING_RESULT; } String firstPart = fixSpacingIssues(0, split); String secondPart = fixSpacingIssues(1, split); secondPart = secondPart.replace("O", "0"); String fixedMrz = firstPart + "\n" + secondPart; System.out.println("AFTER: "); System.out.println(fixedMrz); return new ParsingResult(totalConfidence, fixedMrz); } } return BAD_PARSING_RESULT; } private String fixSpacingIssues(int i, String[] split) { return (split[i].length() <= 44) ? split[i].replace(" ", "<") : split[i].replace(" ", ""); } private String getFileExtension(String header) { String extension; //check image's extension switch (header) { case "data:image/jpeg;base64": extension = "jpeg"; break; case "data:image/png;base64": extension = "png"; break; default://should write cases for more images types extension = "jpg"; break; } return extension; } }
6,672
0.555306
0.551559
150
43.486668
30.090029
145
false
false
0
0
0
0
0
0
0.64
false
false
9
e6c80e0bdc634ad2ba58ac4b3465d95231e8fd8a
26,070,451,513,992
fb62026d5f219531b747e77f24ba801a6789eb13
/MyTest/src/myCh8/button/ButtonFrameTest.java
92f71f8ab3c3787c770323e5ed997c8531212e26
[]
no_license
WenhaoZhang/CoreJava9E
https://github.com/WenhaoZhang/CoreJava9E
6d962031d8c2ca9eb88b346d0c9612bcec2c98ba
9ff4a1e7cc6e3a16f57830bbee3c2330f06372cf
refs/heads/master
2016-05-27T20:00:01.492000
2014-05-30T10:11:34
2014-05-30T10:11:34
18,983,102
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package myCh8.button; /** * @version 1.00 2014-05-20 * @author Wenhao Zhang */ import java.awt.EventQueue; import javax.swing.*; public class ButtonFrameTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { JFrame frame = new ButtonFrame(); frame.setTitle("Button Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } }
UTF-8
Java
455
java
ButtonFrameTest.java
Java
[ { "context": "utton;\n\n/**\n * @version 1.00 2014-05-20\n * @author Wenhao Zhang\n */\n\nimport java.awt.EventQueue;\nimport javax.swi", "end": 78, "score": 0.9998189806938171, "start": 66, "tag": "NAME", "value": "Wenhao Zhang" } ]
null
[]
package myCh8.button; /** * @version 1.00 2014-05-20 * @author <NAME> */ import java.awt.EventQueue; import javax.swing.*; public class ButtonFrameTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { JFrame frame = new ButtonFrame(); frame.setTitle("Button Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } }
449
0.674725
0.648352
26
16.5
16.031818
57
false
false
0
0
0
0
0
0
1.615385
false
false
9
f6588ac07aec865d7bbec50ca2e4109d12b0f4cf
30,812,095,414,353
624b58ae7e138b885f71cb3f212159e66a856aa7
/kodilla-sudoku/src/main/java/com/kodilla/sudoku/Board.java
b8655e004e517dd0e92419b97e4098ae4240c200
[]
no_license
nyuqiu/tomasz-orzol-kodilla-java
https://github.com/nyuqiu/tomasz-orzol-kodilla-java
dbe0ecd01a34b86922e4ea51536d0e91bf06dde8
5de6a9c04875580d1423b842827955992daf446d
refs/heads/master
2022-05-27T09:39:33.327000
2022-05-22T15:03:29
2022-05-22T15:03:29
154,555,808
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kodilla.sudoku; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Board extends Prototype { private static Board boardInstance = null; private List<Row> columns = new ArrayList<>(addRows()); private Map<String, Set<Element>> partsByName = new HashMap<>(addPartsByName()); private Set<String> boardValues = new HashSet<>(); public Board() { } public Board deepCopy() throws CloneNotSupportedException { Board clonedBoard = (Board) super.clone(); clonedBoard.columns = new ArrayList<>(); for (Row theRow : columns) { Row clonedRow = new Row(); clonedRow.getSudokuElements().clear(); for (Element element : theRow.getSudokuElements()) { clonedRow.getSudokuElements().add(element.deepCopy()); } clonedBoard.getColumns().add(clonedRow); } clonedBoard.partsByName = new HashMap<>(addPartsByName()); clonedBoard.boardValues = new HashSet<>(getBoardValues()); return clonedBoard; } public void repopulateValuesInOneOfNine() { partsByName.clear(); partsByName = new HashMap<>(addPartsByName()); } private Map<String, Set<Element>> addPartsByName() { return new HashMap<String, Set<Element>>() {{ put("topLeft", addElementsFromOneOfNine(0, 2, 0, 2)); put("topCentre", addElementsFromOneOfNine(3, 5, 0, 2)); put("topRight", addElementsFromOneOfNine(6, 8, 0, 2)); put("centreLeft", addElementsFromOneOfNine(0, 2, 3, 5)); put("centreCentre", addElementsFromOneOfNine(3, 5, 3, 5)); put("centreRight", addElementsFromOneOfNine(6, 8, 3, 5)); put("bottomLeft", addElementsFromOneOfNine(0, 2, 6, 8)); put("bottomCentre", addElementsFromOneOfNine(3, 5, 6, 8)); put("bottomRight", addElementsFromOneOfNine(6, 8, 6, 8)); }}; } private List<Row> addRows() { List<Row> result = new ArrayList<>(); IntStream.range(0, 9).forEach(n -> result.add(new Row())); return result; } public Set<String> getBoardValues() { return new HashSet<String>() {{ for (int column = 0; column < 9; column++) { for (int row = 0; row < 9; row++) { add(fieldByColumnAndRow(column, row).getValue()); } } }}; } public List<Row> getColumns() { return columns; } public Set<String> getColumnValues(int column) { Set<String> set = new HashSet<>(); IntStream.range(0, 9).forEach(row -> set.add(fieldByColumnAndRow(column, row).getValue())); set.remove(Element.EMPTY); return set; } public Set<String> getRowValues(int row) { Set<String> set = new HashSet<>(); IntStream.range(0, 9).forEach(column -> set.add(fieldByColumnAndRow(column, row).getValue())); set.remove(Element.EMPTY); return set; } public Set<String> getValuesFromOneOfNine(int column, int row) { return new HashSet<>(checkWhichPartOfBoard(column, row)).stream() .map(Element::getValue) .filter(n -> !Objects.equals(n, Element.EMPTY)) .collect(Collectors.toSet()); } public boolean setValue(int column, int row, String value) { if (!(getColumnValues(column).contains(value)) && !(getRowValues(row).contains(value)) && !(getValuesFromOneOfNine(column, row).contains(value)) && Integer.parseInt(value) <= 9 && Integer.parseInt(value) >= 1) { fieldByColumnAndRow(column, row).setValue(value); return true; } else { System.out.println("Cannot add this value"); return false; } } public Element fieldByColumnAndRow(int column, int row) { return getColumns().get(column).getSudokuElements().get(row); } public static Board getInstance() { if (boardInstance == null) { boardInstance = new Board(); } return boardInstance; } private Set<Element> addElementsFromOneOfNine(int fromColumn, int toColumn, int fromRow, int toRow) { Set<Element> result = new HashSet<>(); for (int column = fromColumn; column <= toColumn; column++) { for (int row = fromRow; row <= toRow; row++) { result.add(fieldByColumnAndRow(column, row)); } } return result; } public Set<Element> checkWhichPartOfBoard(int column, int row) { String fullNameOneOfNine; if (0 <= row && row <= 2) { fullNameOneOfNine = "top" + checkForRow(column); } else if (3 <= row && row <= 5) { fullNameOneOfNine = "centre" + checkForRow(column); } else if (6 <= row && row <= 8) { fullNameOneOfNine = "bottom" + checkForRow(column); } else { return null; } return partsByName.get(fullNameOneOfNine); } private String checkForRow(int column) { if (0 <= column && column <= 2) { return "Left"; } else if (3 <= column && column <= 5) { return "Centre"; } else if (6 <= column && column <= 8) { return "Right"; } else { return null; } } @Override public String toString() { String result = ""; for (int row = 0; row < 9; row++) { for (int column = 0; column < 9; column++) { result += " " + fieldByColumnAndRow(column, row).getValue() + " "; } result += "\n"; } return result; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Board that = (Board) o; return Objects.equals(columns, that.columns) && Objects.equals(partsByName, that.partsByName) && Objects.equals(boardValues, that.boardValues); } @Override public int hashCode() { return Objects.hash(columns, partsByName, boardValues); } public void fillTheSudokuBoardForTesting(Board board, int columnMax, int rowMax) { for (int columnNumber = 0; columnNumber < columnMax; columnNumber++) { for (int rowNumber = 0; rowNumber < rowMax; rowNumber++) { if (columnNumber == 0 || columnNumber == 3 || columnNumber == 6) { addingCorrectValueToBoard(board, columnNumber, rowNumber, 1); } else if (columnNumber == 1 || columnNumber == 4 || columnNumber == 7) { if (rowNumber < 6) { addingCorrectValueToBoard(board, columnNumber, rowNumber, 4); } else addingCorrectValueToBoard(board, columnNumber, rowNumber, -5); } else if (columnNumber == 2 || columnNumber == 5 || columnNumber == 8) { if (rowNumber < 3) { addingCorrectValueToBoard(board, columnNumber, rowNumber, 7); } else addingCorrectValueToBoard(board, columnNumber, rowNumber, -2); } } } } private void addingCorrectValueToBoard(Board board, int columnNumber, int rowNumber, int modifyByThis) { board.setValue(columnNumber, rowNumber, Integer.toString(biggerThanNine(rowNumber + modifyByThis + columnNumber / 3))); } private int biggerThanNine(int value) { return value < 10 ? value : value - 9; } }
UTF-8
Java
7,747
java
Board.java
Java
[]
null
[]
package com.kodilla.sudoku; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Board extends Prototype { private static Board boardInstance = null; private List<Row> columns = new ArrayList<>(addRows()); private Map<String, Set<Element>> partsByName = new HashMap<>(addPartsByName()); private Set<String> boardValues = new HashSet<>(); public Board() { } public Board deepCopy() throws CloneNotSupportedException { Board clonedBoard = (Board) super.clone(); clonedBoard.columns = new ArrayList<>(); for (Row theRow : columns) { Row clonedRow = new Row(); clonedRow.getSudokuElements().clear(); for (Element element : theRow.getSudokuElements()) { clonedRow.getSudokuElements().add(element.deepCopy()); } clonedBoard.getColumns().add(clonedRow); } clonedBoard.partsByName = new HashMap<>(addPartsByName()); clonedBoard.boardValues = new HashSet<>(getBoardValues()); return clonedBoard; } public void repopulateValuesInOneOfNine() { partsByName.clear(); partsByName = new HashMap<>(addPartsByName()); } private Map<String, Set<Element>> addPartsByName() { return new HashMap<String, Set<Element>>() {{ put("topLeft", addElementsFromOneOfNine(0, 2, 0, 2)); put("topCentre", addElementsFromOneOfNine(3, 5, 0, 2)); put("topRight", addElementsFromOneOfNine(6, 8, 0, 2)); put("centreLeft", addElementsFromOneOfNine(0, 2, 3, 5)); put("centreCentre", addElementsFromOneOfNine(3, 5, 3, 5)); put("centreRight", addElementsFromOneOfNine(6, 8, 3, 5)); put("bottomLeft", addElementsFromOneOfNine(0, 2, 6, 8)); put("bottomCentre", addElementsFromOneOfNine(3, 5, 6, 8)); put("bottomRight", addElementsFromOneOfNine(6, 8, 6, 8)); }}; } private List<Row> addRows() { List<Row> result = new ArrayList<>(); IntStream.range(0, 9).forEach(n -> result.add(new Row())); return result; } public Set<String> getBoardValues() { return new HashSet<String>() {{ for (int column = 0; column < 9; column++) { for (int row = 0; row < 9; row++) { add(fieldByColumnAndRow(column, row).getValue()); } } }}; } public List<Row> getColumns() { return columns; } public Set<String> getColumnValues(int column) { Set<String> set = new HashSet<>(); IntStream.range(0, 9).forEach(row -> set.add(fieldByColumnAndRow(column, row).getValue())); set.remove(Element.EMPTY); return set; } public Set<String> getRowValues(int row) { Set<String> set = new HashSet<>(); IntStream.range(0, 9).forEach(column -> set.add(fieldByColumnAndRow(column, row).getValue())); set.remove(Element.EMPTY); return set; } public Set<String> getValuesFromOneOfNine(int column, int row) { return new HashSet<>(checkWhichPartOfBoard(column, row)).stream() .map(Element::getValue) .filter(n -> !Objects.equals(n, Element.EMPTY)) .collect(Collectors.toSet()); } public boolean setValue(int column, int row, String value) { if (!(getColumnValues(column).contains(value)) && !(getRowValues(row).contains(value)) && !(getValuesFromOneOfNine(column, row).contains(value)) && Integer.parseInt(value) <= 9 && Integer.parseInt(value) >= 1) { fieldByColumnAndRow(column, row).setValue(value); return true; } else { System.out.println("Cannot add this value"); return false; } } public Element fieldByColumnAndRow(int column, int row) { return getColumns().get(column).getSudokuElements().get(row); } public static Board getInstance() { if (boardInstance == null) { boardInstance = new Board(); } return boardInstance; } private Set<Element> addElementsFromOneOfNine(int fromColumn, int toColumn, int fromRow, int toRow) { Set<Element> result = new HashSet<>(); for (int column = fromColumn; column <= toColumn; column++) { for (int row = fromRow; row <= toRow; row++) { result.add(fieldByColumnAndRow(column, row)); } } return result; } public Set<Element> checkWhichPartOfBoard(int column, int row) { String fullNameOneOfNine; if (0 <= row && row <= 2) { fullNameOneOfNine = "top" + checkForRow(column); } else if (3 <= row && row <= 5) { fullNameOneOfNine = "centre" + checkForRow(column); } else if (6 <= row && row <= 8) { fullNameOneOfNine = "bottom" + checkForRow(column); } else { return null; } return partsByName.get(fullNameOneOfNine); } private String checkForRow(int column) { if (0 <= column && column <= 2) { return "Left"; } else if (3 <= column && column <= 5) { return "Centre"; } else if (6 <= column && column <= 8) { return "Right"; } else { return null; } } @Override public String toString() { String result = ""; for (int row = 0; row < 9; row++) { for (int column = 0; column < 9; column++) { result += " " + fieldByColumnAndRow(column, row).getValue() + " "; } result += "\n"; } return result; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Board that = (Board) o; return Objects.equals(columns, that.columns) && Objects.equals(partsByName, that.partsByName) && Objects.equals(boardValues, that.boardValues); } @Override public int hashCode() { return Objects.hash(columns, partsByName, boardValues); } public void fillTheSudokuBoardForTesting(Board board, int columnMax, int rowMax) { for (int columnNumber = 0; columnNumber < columnMax; columnNumber++) { for (int rowNumber = 0; rowNumber < rowMax; rowNumber++) { if (columnNumber == 0 || columnNumber == 3 || columnNumber == 6) { addingCorrectValueToBoard(board, columnNumber, rowNumber, 1); } else if (columnNumber == 1 || columnNumber == 4 || columnNumber == 7) { if (rowNumber < 6) { addingCorrectValueToBoard(board, columnNumber, rowNumber, 4); } else addingCorrectValueToBoard(board, columnNumber, rowNumber, -5); } else if (columnNumber == 2 || columnNumber == 5 || columnNumber == 8) { if (rowNumber < 3) { addingCorrectValueToBoard(board, columnNumber, rowNumber, 7); } else addingCorrectValueToBoard(board, columnNumber, rowNumber, -2); } } } } private void addingCorrectValueToBoard(Board board, int columnNumber, int rowNumber, int modifyByThis) { board.setValue(columnNumber, rowNumber, Integer.toString(biggerThanNine(rowNumber + modifyByThis + columnNumber / 3))); } private int biggerThanNine(int value) { return value < 10 ? value : value - 9; } }
7,747
0.565896
0.554795
207
36.429951
28.510929
127
false
false
0
0
0
0
0
0
0.94686
false
false
9
bfe1df9f7e15b6a4c9699b1a980d5e70cd73c421
15,719,580,339,767
ba5dad6168557798083a5860682752fec7346634
/src/main/java/de/rub/nds/ipsec/statemachineextractor/ike/v2/datastructures/SimpleBinaryIKEv2Payload.java
f12772f201deeb4eb0613b03597f141974f5c868
[ "Apache-2.0" ]
permissive
RUB-NDS/IPsec-StateMachineExtractor
https://github.com/RUB-NDS/IPsec-StateMachineExtractor
1a9225135e869f29791fa65a18ac621d648d867d
7f2b9693b6ef1cd1a8865f785f44f1ace2a5ed38
refs/heads/master
2023-03-28T12:23:43.455000
2020-11-17T12:45:57
2020-11-17T12:45:57
300,313,130
0
2
NOASSERTION
false
2020-10-13T15:08:57
2020-10-01T14:41:28
2020-10-13T14:15:30
2020-10-13T15:08:56
410
0
0
0
Java
false
false
/** * IPsec-StateMachineExtractor - Extract the state machine of an IKEv1/IKEv2 implementation * * Copyright © 2020 Ruhr University Bochum * * Licensed under Apache License 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package de.rub.nds.ipsec.statemachineextractor.ike.v2.datastructures; import de.rub.nds.ipsec.statemachineextractor.ike.GenericIKEParsingException; import de.rub.nds.ipsec.statemachineextractor.ike.IKEPayloadTypeEnum; import de.rub.nds.ipsec.statemachineextractor.ike.SimpleBinaryPayload; import de.rub.nds.ipsec.statemachineextractor.ike.v2.IKEv2ParsingException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * * @author Dennis Felsch <dennis.felsch at ruhr-uni-bochum.de> */ public abstract class SimpleBinaryIKEv2Payload extends IKEv2Payload implements SimpleBinaryPayload { byte[] binaryData = new byte[0]; public SimpleBinaryIKEv2Payload(IKEPayloadTypeEnum type) { super(type); } protected byte[] getBinaryData() { return binaryData.clone(); } protected void setBinaryData(byte[] binaryData) { this.binaryData = binaryData; } @Override public int getLength() { return HEADER_LEN + binaryData.length; } @Override public void writeBytes(ByteArrayOutputStream baos) { super.writeBytes(baos); baos.write(binaryData, 0, binaryData.length); } @Override protected void setBody(byte[] body) throws IKEv2ParsingException { this.setBinaryData(body); } protected static SimpleBinaryIKEv2Payload fromStream(ByteArrayInputStream bais, SimpleBinaryIKEv2Payload payload) throws GenericIKEParsingException { payload.fillFromStream(bais); return payload; } @Override protected void fillFromStream(ByteArrayInputStream bais) throws GenericIKEParsingException { int length = this.fillGenericPayloadHeaderFromStream(bais); if (length < HEADER_LEN) { throw new IKEv2ParsingException("Payload length too short!"); } byte[] buffer = new byte[length - HEADER_LEN]; int readBytes; try { readBytes = bais.read(buffer); } catch (IOException ex) { throw new IKEv2ParsingException(ex); } if (readBytes < length - HEADER_LEN) { throw new IKEv2ParsingException("Input stream ended early after " + readBytes + " bytes (should read " + (length - HEADER_LEN) + " bytes)!"); } this.setBody(buffer); if (length != this.getLength()) { throw new IKEv2ParsingException("Payload lengths differ - Computed: " + this.getLength() + "vs. Received: " + length + "!"); } } }
UTF-8
Java
2,764
java
SimpleBinaryIKEv2Payload.java
Java
[ { "context": "am;\nimport java.io.IOException;\n\n/**\n *\n * @author Dennis Felsch <dennis.felsch at ruhr-uni-bochum.de>\n */\npublic ", "end": 733, "score": 0.9998459219932556, "start": 720, "tag": "NAME", "value": "Dennis Felsch" } ]
null
[]
/** * IPsec-StateMachineExtractor - Extract the state machine of an IKEv1/IKEv2 implementation * * Copyright © 2020 Ruhr University Bochum * * Licensed under Apache License 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package de.rub.nds.ipsec.statemachineextractor.ike.v2.datastructures; import de.rub.nds.ipsec.statemachineextractor.ike.GenericIKEParsingException; import de.rub.nds.ipsec.statemachineextractor.ike.IKEPayloadTypeEnum; import de.rub.nds.ipsec.statemachineextractor.ike.SimpleBinaryPayload; import de.rub.nds.ipsec.statemachineextractor.ike.v2.IKEv2ParsingException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * * @author <NAME> <dennis.felsch at ruhr-uni-bochum.de> */ public abstract class SimpleBinaryIKEv2Payload extends IKEv2Payload implements SimpleBinaryPayload { byte[] binaryData = new byte[0]; public SimpleBinaryIKEv2Payload(IKEPayloadTypeEnum type) { super(type); } protected byte[] getBinaryData() { return binaryData.clone(); } protected void setBinaryData(byte[] binaryData) { this.binaryData = binaryData; } @Override public int getLength() { return HEADER_LEN + binaryData.length; } @Override public void writeBytes(ByteArrayOutputStream baos) { super.writeBytes(baos); baos.write(binaryData, 0, binaryData.length); } @Override protected void setBody(byte[] body) throws IKEv2ParsingException { this.setBinaryData(body); } protected static SimpleBinaryIKEv2Payload fromStream(ByteArrayInputStream bais, SimpleBinaryIKEv2Payload payload) throws GenericIKEParsingException { payload.fillFromStream(bais); return payload; } @Override protected void fillFromStream(ByteArrayInputStream bais) throws GenericIKEParsingException { int length = this.fillGenericPayloadHeaderFromStream(bais); if (length < HEADER_LEN) { throw new IKEv2ParsingException("Payload length too short!"); } byte[] buffer = new byte[length - HEADER_LEN]; int readBytes; try { readBytes = bais.read(buffer); } catch (IOException ex) { throw new IKEv2ParsingException(ex); } if (readBytes < length - HEADER_LEN) { throw new IKEv2ParsingException("Input stream ended early after " + readBytes + " bytes (should read " + (length - HEADER_LEN) + " bytes)!"); } this.setBody(buffer); if (length != this.getLength()) { throw new IKEv2ParsingException("Payload lengths differ - Computed: " + this.getLength() + "vs. Received: " + length + "!"); } } }
2,757
0.690554
0.681506
82
32.695122
34.76741
153
false
false
0
0
0
0
0
0
0.365854
false
false
9
59b8cd451f5763978403ca24fccd020ad1c1b173
23,021,024,732,374
5abc02cac7e116b87bd50980bb6017c896e69bb6
/src/main/java/wiki/zzq/scheduler/Tools.java
5d00d1199fc96d0e59da526a2bfaddb4ab4e7eda
[]
no_license
zhizuqiu/mesos-framework-demo
https://github.com/zhizuqiu/mesos-framework-demo
132dd6f721966f5084767ee290653b87ebcd033f
a5757057d96d205ea041d48dabbd875ce5fc1017
refs/heads/master
2020-09-28T17:58:33.183000
2020-05-28T09:49:13
2020-05-28T09:49:13
226,829,776
0
1
null
false
2019-12-09T09:10:13
2019-12-09T09:09:01
2019-12-09T09:09:56
2019-12-09T09:10:12
0
0
0
1
Java
false
false
package wiki.zzq.scheduler; import org.apache.mesos.Protos; import java.util.Arrays; public class Tools { // 生成一个测试任务 public static Protos.TaskInfo buildTaskInfo(Protos.Offer offer, double cpus, double mem, String role, String cmd) { // 任务id String taskId = "task_id_1"; // 任务名字 String taskName = "task_name"; Protos.TaskInfo.Builder builder = Protos.TaskInfo.newBuilder(); builder.setName(taskName) .setTaskId(Protos.TaskID.newBuilder().setValue(taskId).build()) .setSlaveId(offer.getSlaveId()); builder.addAllResources( Arrays.asList( // 所需的cpus Protos.Resource.newBuilder() .setName("cpus") .setType(Protos.Value.Type.SCALAR) .setScalar(Protos.Value.Scalar.newBuilder().setValue(cpus)) .setRole(role) // .setReservation() 使用预留资源时 .build(), // 所需的mem Protos.Resource.newBuilder() .setName("mem") .setType(Protos.Value.Type.SCALAR) .setScalar(Protos.Value.Scalar.newBuilder().setValue(mem)) .setRole(role) // .setReservation() 使用预留资源时 .build() ) ); // builder.setLabels() 设置任务label,用于标识和mesos插件读取 // builder.setDiscovery() 设置服务发现机制 // builder.setHealthCheck() 设置健康检查 builder.setCommand(Protos.CommandInfo.newBuilder().setShell(true).setValue(cmd)); return builder.build(); } public static boolean matchResources(Protos.Offer offer, double cpus, double mem, String role) { boolean matchedCpus = false; boolean matchedMem = false; for (Protos.Resource r : offer.getResourcesList()) { if (r.getRole().equals(role) && "cpus".equals(r.getName()) && r.getScalar().getValue() > cpus) { matchedCpus = true; } if (r.getRole().equals(role) && "mem".equals(r.getName()) && r.getScalar().getValue() > mem) { matchedMem = true; } } return matchedCpus && matchedMem; } }
UTF-8
Java
2,579
java
Tools.java
Java
[]
null
[]
package wiki.zzq.scheduler; import org.apache.mesos.Protos; import java.util.Arrays; public class Tools { // 生成一个测试任务 public static Protos.TaskInfo buildTaskInfo(Protos.Offer offer, double cpus, double mem, String role, String cmd) { // 任务id String taskId = "task_id_1"; // 任务名字 String taskName = "task_name"; Protos.TaskInfo.Builder builder = Protos.TaskInfo.newBuilder(); builder.setName(taskName) .setTaskId(Protos.TaskID.newBuilder().setValue(taskId).build()) .setSlaveId(offer.getSlaveId()); builder.addAllResources( Arrays.asList( // 所需的cpus Protos.Resource.newBuilder() .setName("cpus") .setType(Protos.Value.Type.SCALAR) .setScalar(Protos.Value.Scalar.newBuilder().setValue(cpus)) .setRole(role) // .setReservation() 使用预留资源时 .build(), // 所需的mem Protos.Resource.newBuilder() .setName("mem") .setType(Protos.Value.Type.SCALAR) .setScalar(Protos.Value.Scalar.newBuilder().setValue(mem)) .setRole(role) // .setReservation() 使用预留资源时 .build() ) ); // builder.setLabels() 设置任务label,用于标识和mesos插件读取 // builder.setDiscovery() 设置服务发现机制 // builder.setHealthCheck() 设置健康检查 builder.setCommand(Protos.CommandInfo.newBuilder().setShell(true).setValue(cmd)); return builder.build(); } public static boolean matchResources(Protos.Offer offer, double cpus, double mem, String role) { boolean matchedCpus = false; boolean matchedMem = false; for (Protos.Resource r : offer.getResourcesList()) { if (r.getRole().equals(role) && "cpus".equals(r.getName()) && r.getScalar().getValue() > cpus) { matchedCpus = true; } if (r.getRole().equals(role) && "mem".equals(r.getName()) && r.getScalar().getValue() > mem) { matchedMem = true; } } return matchedCpus && matchedMem; } }
2,579
0.504684
0.504277
63
37.968254
30.176712
119
false
false
0
0
0
0
0
0
0.365079
false
false
9
f0ef0ac989c6d09ffd2fc3fdbbc3ea095294b940
4,913,442,595,886
693240e17d15b316af230076c6eefef0e4ecb0b5
/PClassic/PClassic2015s-solutions/PewterCity.java
2f5103fde553ad05e34b826d2685a85fa7392612
[]
no_license
elc1798/competition-programming
https://github.com/elc1798/competition-programming
95d8eb366fb7552edce7d6d83ae14affd8d156bf
ed0a4f26a0205bf978786a205873e63939c11db0
refs/heads/master
2021-01-19T20:08:08.309000
2016-02-05T01:06:26
2016-02-05T01:06:26
28,168,648
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class PewterCity { public static int digitValue(char c){ if (c == 'I'){ return 1; } else if (c == 'V'){ return 5; } else if (c == 'X'){ return 10; } else if (c == 'L'){ return 50; } else if (c == 'C'){ return 100; } else { throw new IllegalArgumentException("Not a valid Roman digit"); } } public static int value(String str){ char[] arr = str.toCharArray(); int sum = 0, digit, secondDigit; for(int index = 0; index < arr.length; index++){ digit = digitValue(arr[index]); if(index < arr.length - 1){ secondDigit = digitValue(arr[index + 1]); } else { secondDigit = 0; } if (digit >= secondDigit){ sum += digit; } else{ sum += secondDigit - digit; index++; } } return sum; } static long choose(int i, int u) { long num = 1, denom = 1; for (int index = i-u+1; index <= i; index++) { num *= index; } for (int index = 1; index <= u; index++) { denom *= index; } return num / denom; } public static int pathsToPewter(String iRom, String uRom){ int i = value(iRom); int u = value(uRom); return (int) choose(i, u); } public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader( new FileReader("PewterCityIN.txt")); while(reader.ready()){ String i = reader.readLine(); //First input on first line String u = reader.readLine(); //Second input on second line System.out.println(pathsToPewter(i, u)); } reader.close(); } }
UTF-8
Java
1,715
java
PewterCity.java
Java
[]
null
[]
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class PewterCity { public static int digitValue(char c){ if (c == 'I'){ return 1; } else if (c == 'V'){ return 5; } else if (c == 'X'){ return 10; } else if (c == 'L'){ return 50; } else if (c == 'C'){ return 100; } else { throw new IllegalArgumentException("Not a valid Roman digit"); } } public static int value(String str){ char[] arr = str.toCharArray(); int sum = 0, digit, secondDigit; for(int index = 0; index < arr.length; index++){ digit = digitValue(arr[index]); if(index < arr.length - 1){ secondDigit = digitValue(arr[index + 1]); } else { secondDigit = 0; } if (digit >= secondDigit){ sum += digit; } else{ sum += secondDigit - digit; index++; } } return sum; } static long choose(int i, int u) { long num = 1, denom = 1; for (int index = i-u+1; index <= i; index++) { num *= index; } for (int index = 1; index <= u; index++) { denom *= index; } return num / denom; } public static int pathsToPewter(String iRom, String uRom){ int i = value(iRom); int u = value(uRom); return (int) choose(i, u); } public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader( new FileReader("PewterCityIN.txt")); while(reader.ready()){ String i = reader.readLine(); //First input on first line String u = reader.readLine(); //Second input on second line System.out.println(pathsToPewter(i, u)); } reader.close(); } }
1,715
0.565598
0.555102
82
18.914635
17.725689
65
false
false
0
0
0
0
0
0
2.54878
false
false
9
b737567d24e542d7941061aca08bd00ba908283b
16,088,947,498,856
2c20434ebd2e6d048e38d8e880fbd393006bd104
/app/src/main/java/alizinha/c4q/nyc/onemorechance/AddEventToCalendar.java
c29c90df953548592d4ed729e120ddcd62621d28
[]
no_license
alizinha/robinhood_hackathon
https://github.com/alizinha/robinhood_hackathon
f7a25b445c98e67c794a7e9f1e2e7d04ae033741
4e33198e20655c6160bbbe2c5c8eb887abe7bf1a
refs/heads/master
2021-01-15T19:24:14.774000
2015-08-03T16:02:57
2015-08-03T16:02:57
40,049,822
0
1
null
true
2015-08-03T16:02:57
2015-08-01T14:52:59
2015-08-01T15:35:15
2015-08-03T16:02:57
2,091
0
1
1
Java
null
null
package alizinha.c4q.nyc.onemorechance; import android.content.Intent; import android.os.Bundle; import android.provider.CalendarContract; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; /** * Created by Allison Bojarski on 8/1/15. */ public class AddEventToCalendar extends ActionBarActivity { private Button mButtonSubmit; private TextView mEditTextNewTitle; private TextView mEditTextNewLocation; private TextView mEditTextDescription; private TextView mEditTextNewEvent; private String getTitle; private String getLocation; private String getDescription; private EditText mNewTitle; private EditText mNewLocation; private EditText mNewDescription; boolean isSpanish = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_event_to_calendar); isSpanish = getIntent().getFlags() == 1; mButtonSubmit = (Button) findViewById(R.id.submit); mEditTextNewTitle = (TextView) findViewById(R.id.title); mEditTextNewEvent = (TextView) findViewById(R.id.evento); mNewTitle = (EditText) findViewById(R.id.newTitle); mNewLocation = (EditText) findViewById(R.id.newLocation); mNewDescription = (EditText) findViewById(R.id.newDescription); if (isSpanish) { mNewTitle.setHint("Titulo de Nuevo Evento"); mNewLocation.setHint("Ubicación"); mNewDescription.setHint("Descripción"); mButtonSubmit.setText("Crear Evento"); mEditTextNewEvent.setText("Añadir Evento"); } mButtonSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mNewTitle.getText() != null) { getTitle = mNewTitle.getText().toString(); } else { getTitle = ""; } if (mNewLocation.getText() != null) { getLocation = mNewLocation.getText().toString(); } else { getLocation = ""; } if (mNewDescription.getText() != null) { getDescription = mNewDescription.getText().toString(); } else { getDescription = ""; } Intent calIntent = new Intent(Intent.ACTION_INSERT); calIntent.setType("vnd.android.cursor.item/event"); calIntent.putExtra(CalendarContract.Events.TITLE, getTitle); calIntent.putExtra(CalendarContract.Events.EVENT_LOCATION, getLocation); calIntent.putExtra(CalendarContract.Events.DESCRIPTION, getDescription); startActivity(calIntent); } }); } }
UTF-8
Java
3,001
java
AddEventToCalendar.java
Java
[ { "context": "import android.widget.TextView;\n\n/**\n * Created by Allison Bojarski on 8/1/15.\n */\n\n\npublic class AddEventToCalendar ", "end": 344, "score": 0.9996926188468933, "start": 328, "tag": "NAME", "value": "Allison Bojarski" } ]
null
[]
package alizinha.c4q.nyc.onemorechance; import android.content.Intent; import android.os.Bundle; import android.provider.CalendarContract; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; /** * Created by <NAME> on 8/1/15. */ public class AddEventToCalendar extends ActionBarActivity { private Button mButtonSubmit; private TextView mEditTextNewTitle; private TextView mEditTextNewLocation; private TextView mEditTextDescription; private TextView mEditTextNewEvent; private String getTitle; private String getLocation; private String getDescription; private EditText mNewTitle; private EditText mNewLocation; private EditText mNewDescription; boolean isSpanish = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_event_to_calendar); isSpanish = getIntent().getFlags() == 1; mButtonSubmit = (Button) findViewById(R.id.submit); mEditTextNewTitle = (TextView) findViewById(R.id.title); mEditTextNewEvent = (TextView) findViewById(R.id.evento); mNewTitle = (EditText) findViewById(R.id.newTitle); mNewLocation = (EditText) findViewById(R.id.newLocation); mNewDescription = (EditText) findViewById(R.id.newDescription); if (isSpanish) { mNewTitle.setHint("Titulo de Nuevo Evento"); mNewLocation.setHint("Ubicación"); mNewDescription.setHint("Descripción"); mButtonSubmit.setText("Crear Evento"); mEditTextNewEvent.setText("Añadir Evento"); } mButtonSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mNewTitle.getText() != null) { getTitle = mNewTitle.getText().toString(); } else { getTitle = ""; } if (mNewLocation.getText() != null) { getLocation = mNewLocation.getText().toString(); } else { getLocation = ""; } if (mNewDescription.getText() != null) { getDescription = mNewDescription.getText().toString(); } else { getDescription = ""; } Intent calIntent = new Intent(Intent.ACTION_INSERT); calIntent.setType("vnd.android.cursor.item/event"); calIntent.putExtra(CalendarContract.Events.TITLE, getTitle); calIntent.putExtra(CalendarContract.Events.EVENT_LOCATION, getLocation); calIntent.putExtra(CalendarContract.Events.DESCRIPTION, getDescription); startActivity(calIntent); } }); } }
2,991
0.626751
0.624416
87
33.436783
24.396486
88
false
false
0
0
0
0
0
0
0.586207
false
false
9
c81ec1fc79adab63b0dd4ad5accb2578cef60b4a
16,088,947,499,146
71ac3b98b02ff2d0933cb59d3ca110cdb242418e
/src/main/java/com/neelesh/pocgraphql/GitHubDetails.java
8dc8a623ecab60ce7d46894fdc69f7cdf17f7c05
[]
no_license
Allah-The-Dev/githubGraphQlPOC
https://github.com/Allah-The-Dev/githubGraphQlPOC
654df55636d8438969504482c77c511abd63601d
78182737d677b100d369260bc956de6d78620f2e
refs/heads/master
2023-04-28T19:30:13.628000
2019-11-08T09:15:17
2019-11-08T09:15:17
213,548,011
2
0
null
false
2023-04-14T17:48:53
2019-10-08T04:21:01
2019-11-08T09:15:20
2023-04-14T17:48:53
34
2
0
3
Java
false
false
package com.neelesh.pocgraphql; class GitHubDetails{ private String repoUrl; private String accessToken; public String getRepoUrl() { return repoUrl; } public void setRepoUrl(String repoUrl) { this.repoUrl = repoUrl; } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } }
UTF-8
Java
444
java
GitHubDetails.java
Java
[]
null
[]
package com.neelesh.pocgraphql; class GitHubDetails{ private String repoUrl; private String accessToken; public String getRepoUrl() { return repoUrl; } public void setRepoUrl(String repoUrl) { this.repoUrl = repoUrl; } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } }
444
0.641892
0.641892
23
18.347826
16.38294
52
false
false
0
0
0
0
0
0
0.304348
false
false
9
fd346d609972a7ad6aa700fdac4baf25fb6889ac
22,033,182,237,966
ec6bc2da141c6086f590355e47ece4b484741b71
/src/main/java/xin/wangning/control/Controller.java
6d8a4a67cb117ee4dc5acda5a593b2dff7e0513a
[]
no_license
wn160921/zhihuSpider
https://github.com/wn160921/zhihuSpider
7b8c38fffc89c4787852b3336c016ce78e67dd02
391682911a2f2be259e45a75fbda5e5206c54ef2
refs/heads/master
2020-04-03T15:17:38.634000
2018-12-05T13:08:50
2018-12-05T13:08:50
155,358,030
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package xin.wangning.control; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import java.io.*; import java.util.List; import java.util.Scanner; import java.util.Set; import com.alibaba.fastjson.JSON; import xin.wangning.domain.Article; import xin.wangning.domain.MyData; import xin.wangning.domain.Question; import xin.wangning.parser.DriverParser; import xin.wangning.parser.HTMLParser; import xin.wangning.url.UrlManager; import xin.wangning.util.MyUtil; public class Controller { static ChromeDriver driver = null; static Scanner scanner = null; public static UrlManager urlManager; public static HTMLParser htmlParser; public static DriverParser driverParser; public static MyData myData; public static void main(String[] args) { urlManager = new UrlManager(); htmlParser = new HTMLParser(); driver = getWebDriver(); driverParser = new DriverParser(driver); boolean exitFlag = true; while (exitFlag) { print("输入操作"); print("1、自动加载cookies登录"); print("2、手动登录"); print("3、退出"); print("4、开始"); scanner = new Scanner(System.in); int order = scanner.nextInt(); switch (order) { case 1: loadCookies(); driver.get("https://www.zhihu.com"); break; case 2: loginByHand(); saveCookies(); break; case 3: driver.close(); exitFlag = false; break; case 4: crawl(); break; default: break; } } } public static void print(String s) { System.out.println(s); } //仅供初始化用 public static ChromeDriver getWebDriver() { ChromeDriver webDriver = new ChromeDriver(); webDriver.manage().window().maximize(); webDriver.get("https://www.baidu.com"); return webDriver; } public static boolean loginByHand() { driver.get("https://www.zhihu.com"); print("完成后输入0,其它出bug"); int end = scanner.nextInt(); if (end == Constant.LOGIN_COMPLETE) { return true; } else { return false; } } public static void saveCookies() { Set<Cookie> cookieSet = driver.manage().getCookies(); String cookiesStr = JSON.toJSONString(cookieSet); File file = new File("cookies.json"); try { if (file.exists()) { file.delete(); } file.createNewFile(); FileWriter fw = new FileWriter(file); BufferedWriter writer = new BufferedWriter(fw); writer.write(cookiesStr); writer.flush(); writer.close(); fw.close(); } catch (Exception e) { e.printStackTrace(); } } public static void loadCookies() { File file = new File("cookies.json"); try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); StringBuilder builder = new StringBuilder(); String line = ""; while ((line = br.readLine()) != null) { builder.append(line); } String cookiesStr = builder.toString(); List<Cookie> cookieSet = JSON.parseArray(cookiesStr, Cookie.class); for (Cookie cookie : cookieSet) { driver.manage().addCookie(cookie); } } catch (Exception e) { e.printStackTrace(); } } public static void crawl() { driver.get("https://www.zhihu.com/topic/19631819/newest"); // driver.get("https://www.zhihu.com/topic/19550901/hot"); // getAllQuestionShow(20); List<String> urls = driverParser.getAllQuestionAndArticleUrl(200); urlManager.addUrls(urls); String url; while (!(url = urlManager.getUrl()).equals("")) { if (url.contains("/p/")) { // driver.get(url); // Article article = htmlParser.parseArticle(driver.getPageSource()); // article.setArticleUrl(url); // MyUtil.dumpArticle(article); } else { driver.get(url); // getAllAnswerShow(); // Question question = htmlParser.parseQuestion(driver.getPageSource()); Question question = driverParser.parserQuestion(); question.setUrl(url); MyUtil.dumpQuestion(question); // myData.addQuestion(question); } } // DataUtil.storage(myData); } public static void getAllQuestionShow(int num) { while (true) { String jsDown = "window.scrollTo(0,document.body.scrollHeight);"; String jsUp = "window.scrollTo(0,0);"; try { ((JavascriptExecutor) driver).executeScript(jsUp); ((JavascriptExecutor) driver).executeScript(jsDown); Thread.sleep(1000); List<WebElement> elements = driver.findElements(By.className("List-item")); if (elements.size() >= num) { break; } } catch (InterruptedException e) { e.printStackTrace(); } } } public static void getAllAnswerShow() { try { WebElement allAnswerElem = driver.findElement(By.className("QuestionMainAction")); allAnswerElem.sendKeys(Keys.ENTER); // allAnswerElem.click(); Thread.sleep(1000); } catch (Exception e) { //e.printStackTrace(); } while (true) { String jsDown = "window.scrollTo(0,document.body.scrollHeight);"; String jsUp = "window.scrollTo(0,0);"; try { ((JavascriptExecutor) driver).executeScript(jsUp); ((JavascriptExecutor) driver).executeScript(jsDown); Thread.sleep(1000); List<WebElement> elements = driver.findElements(By.cssSelector(".QuestionAnswers-answerButton")); if (elements.size() > 0) { break; } // .QuestionAnswers-answerButton } catch (InterruptedException e) { e.printStackTrace(); } } } //滚动使加载所有的问题 public static void mainScroll(String className, int minTimes) { //先点击几个按钮加载所有的答案或者评论 try { WebElement allAnswerElem = driver.findElement(By.className("QuestionMainAction")); allAnswerElem.click(); Thread.sleep(1000); } catch (Exception e) { } List<WebElement> elements = driver.findElements(By.className(className)); int length = elements.size(); while (true) { String jsDown = "window.scrollTo(0,document.body.scrollHeight);"; String jsUp = "window.scrollTo(0,0);"; try { ((JavascriptExecutor) driver).executeScript(jsUp); // Thread.sleep(1000); ((JavascriptExecutor) driver).executeScript(jsDown); Thread.sleep(4000); List<WebElement> elements2 = driver.findElements(By.className(className)); if (length == elements2.size()) { break; } else if (elements2.size() >= minTimes) { break; } else { length = elements2.size(); } } catch (InterruptedException e) { e.printStackTrace(); } } } }
UTF-8
Java
8,070
java
Controller.java
Java
[]
null
[]
package xin.wangning.control; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import java.io.*; import java.util.List; import java.util.Scanner; import java.util.Set; import com.alibaba.fastjson.JSON; import xin.wangning.domain.Article; import xin.wangning.domain.MyData; import xin.wangning.domain.Question; import xin.wangning.parser.DriverParser; import xin.wangning.parser.HTMLParser; import xin.wangning.url.UrlManager; import xin.wangning.util.MyUtil; public class Controller { static ChromeDriver driver = null; static Scanner scanner = null; public static UrlManager urlManager; public static HTMLParser htmlParser; public static DriverParser driverParser; public static MyData myData; public static void main(String[] args) { urlManager = new UrlManager(); htmlParser = new HTMLParser(); driver = getWebDriver(); driverParser = new DriverParser(driver); boolean exitFlag = true; while (exitFlag) { print("输入操作"); print("1、自动加载cookies登录"); print("2、手动登录"); print("3、退出"); print("4、开始"); scanner = new Scanner(System.in); int order = scanner.nextInt(); switch (order) { case 1: loadCookies(); driver.get("https://www.zhihu.com"); break; case 2: loginByHand(); saveCookies(); break; case 3: driver.close(); exitFlag = false; break; case 4: crawl(); break; default: break; } } } public static void print(String s) { System.out.println(s); } //仅供初始化用 public static ChromeDriver getWebDriver() { ChromeDriver webDriver = new ChromeDriver(); webDriver.manage().window().maximize(); webDriver.get("https://www.baidu.com"); return webDriver; } public static boolean loginByHand() { driver.get("https://www.zhihu.com"); print("完成后输入0,其它出bug"); int end = scanner.nextInt(); if (end == Constant.LOGIN_COMPLETE) { return true; } else { return false; } } public static void saveCookies() { Set<Cookie> cookieSet = driver.manage().getCookies(); String cookiesStr = JSON.toJSONString(cookieSet); File file = new File("cookies.json"); try { if (file.exists()) { file.delete(); } file.createNewFile(); FileWriter fw = new FileWriter(file); BufferedWriter writer = new BufferedWriter(fw); writer.write(cookiesStr); writer.flush(); writer.close(); fw.close(); } catch (Exception e) { e.printStackTrace(); } } public static void loadCookies() { File file = new File("cookies.json"); try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); StringBuilder builder = new StringBuilder(); String line = ""; while ((line = br.readLine()) != null) { builder.append(line); } String cookiesStr = builder.toString(); List<Cookie> cookieSet = JSON.parseArray(cookiesStr, Cookie.class); for (Cookie cookie : cookieSet) { driver.manage().addCookie(cookie); } } catch (Exception e) { e.printStackTrace(); } } public static void crawl() { driver.get("https://www.zhihu.com/topic/19631819/newest"); // driver.get("https://www.zhihu.com/topic/19550901/hot"); // getAllQuestionShow(20); List<String> urls = driverParser.getAllQuestionAndArticleUrl(200); urlManager.addUrls(urls); String url; while (!(url = urlManager.getUrl()).equals("")) { if (url.contains("/p/")) { // driver.get(url); // Article article = htmlParser.parseArticle(driver.getPageSource()); // article.setArticleUrl(url); // MyUtil.dumpArticle(article); } else { driver.get(url); // getAllAnswerShow(); // Question question = htmlParser.parseQuestion(driver.getPageSource()); Question question = driverParser.parserQuestion(); question.setUrl(url); MyUtil.dumpQuestion(question); // myData.addQuestion(question); } } // DataUtil.storage(myData); } public static void getAllQuestionShow(int num) { while (true) { String jsDown = "window.scrollTo(0,document.body.scrollHeight);"; String jsUp = "window.scrollTo(0,0);"; try { ((JavascriptExecutor) driver).executeScript(jsUp); ((JavascriptExecutor) driver).executeScript(jsDown); Thread.sleep(1000); List<WebElement> elements = driver.findElements(By.className("List-item")); if (elements.size() >= num) { break; } } catch (InterruptedException e) { e.printStackTrace(); } } } public static void getAllAnswerShow() { try { WebElement allAnswerElem = driver.findElement(By.className("QuestionMainAction")); allAnswerElem.sendKeys(Keys.ENTER); // allAnswerElem.click(); Thread.sleep(1000); } catch (Exception e) { //e.printStackTrace(); } while (true) { String jsDown = "window.scrollTo(0,document.body.scrollHeight);"; String jsUp = "window.scrollTo(0,0);"; try { ((JavascriptExecutor) driver).executeScript(jsUp); ((JavascriptExecutor) driver).executeScript(jsDown); Thread.sleep(1000); List<WebElement> elements = driver.findElements(By.cssSelector(".QuestionAnswers-answerButton")); if (elements.size() > 0) { break; } // .QuestionAnswers-answerButton } catch (InterruptedException e) { e.printStackTrace(); } } } //滚动使加载所有的问题 public static void mainScroll(String className, int minTimes) { //先点击几个按钮加载所有的答案或者评论 try { WebElement allAnswerElem = driver.findElement(By.className("QuestionMainAction")); allAnswerElem.click(); Thread.sleep(1000); } catch (Exception e) { } List<WebElement> elements = driver.findElements(By.className(className)); int length = elements.size(); while (true) { String jsDown = "window.scrollTo(0,document.body.scrollHeight);"; String jsUp = "window.scrollTo(0,0);"; try { ((JavascriptExecutor) driver).executeScript(jsUp); // Thread.sleep(1000); ((JavascriptExecutor) driver).executeScript(jsDown); Thread.sleep(4000); List<WebElement> elements2 = driver.findElements(By.className(className)); if (length == elements2.size()) { break; } else if (elements2.size() >= minTimes) { break; } else { length = elements2.size(); } } catch (InterruptedException e) { e.printStackTrace(); } } } }
8,070
0.529975
0.521411
237
32.50211
21.55723
113
false
false
0
0
0
0
0
0
0.616034
false
false
9
1cbaad587e5a09f0fc9e3cf8e94c831611a351a8
22,857,815,954,548
4049a236da9490159745412ecb77fa1d5905eb64
/Kapsch.MobileApps/KapschMobile/1_iVehicleTest/src/main/java/za/co/kapsch/ivehicletest/orm/VehicleInspectionResultsRepository.java
3f5af0b29465f0907980479694e95d49c8b722d9
[]
no_license
noptran/ITS
https://github.com/noptran/ITS
ce1a3588d8a32bf0bfb25d9a66dc4a70afee206a
d9ef1173308c18a6f57ae0681151752c59cb6f15
refs/heads/master
2022-01-29T01:51:04.158000
2018-07-17T12:19:01
2018-07-17T12:19:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package za.co.kapsch.ivehicletest.orm; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.j256.ormlite.dao.Dao; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.ErrorManager; import za.co.kapsch.ivehicletest.App; import za.co.kapsch.ivehicletest.Models.VehicleInspectionResultModel; import za.co.kapsch.ivehicletest.Models.VehicleInspectionResultsModel; import za.co.kapsch.shared.Enums.ErrorSeverity; import za.co.kapsch.shared.MessageManager; import za.co.kapsch.shared.Utilities; /** * Created by CSenekal on 2018/01/22. */ public class VehicleInspectionResultsRepository { public static final String UPLOADED_COLUMN = "Uploaded"; public static final String BOOKING_ID_COLUMN = "BookingID"; public static void createOrUpdate(VehicleInspectionResultsModel vehicleInspectionResults) throws SQLException { final OrmDbHelper ormDbHelper = new OrmDbHelper(App.getContext()); SQLiteDatabase db = ormDbHelper.getWritableDatabase(); try { db.beginTransaction(); final Dao<VehicleInspectionResultsModel, Integer> vehicleInspectionResultsDao = ormDbHelper.getVehicleInspectionResultsDao(); final Dao<VehicleInspectionResultModel, Integer> vehicleInspectionResultDao = ormDbHelper.getVehicleInspectionResultDao(); Dao.CreateOrUpdateStatus status = vehicleInspectionResultsDao.createOrUpdate(vehicleInspectionResults); for (VehicleInspectionResultModel vehicleInspectionResult : vehicleInspectionResults.getVehicleInspectionResultList()) { vehicleInspectionResult.setVehicleInspectionResultsID(vehicleInspectionResults.getID()); vehicleInspectionResultDao.createOrUpdate(vehicleInspectionResult); } db.setTransactionSuccessful(); }finally { db.endTransaction(); ormDbHelper.close(); } } public static List<VehicleInspectionResultsModel> getVehicleInspectionResultList() throws SQLException { final OrmDbHelper ormDbHelper = new OrmDbHelper(App.getContext()); try { final Dao<VehicleInspectionResultsModel, Integer> vehicleInspectionResultsDao = ormDbHelper.getVehicleInspectionResultsDao(); final List<VehicleInspectionResultsModel> vehicleInspectionResultsList = vehicleInspectionResultsDao.queryForAll(); return vehicleInspectionResultsList; } finally { ormDbHelper.close(); } } public static List<VehicleInspectionResultsModel> getUnSyncedVehicleInspectionResults() throws SQLException { final OrmDbHelper ormDbHelper = new OrmDbHelper(App.getContext()); try { final Dao<VehicleInspectionResultsModel, Integer> vehicleInspectionResultsDao = ormDbHelper.getVehicleInspectionResultsDao(); final List<VehicleInspectionResultsModel> vehicleInspectionResultsList = vehicleInspectionResultsDao.query(vehicleInspectionResultsDao.queryBuilder() .where() .eq(UPLOADED_COLUMN, false).prepare()); return vehicleInspectionResultsList; }finally { ormDbHelper.close(); } } public static boolean update(VehicleInspectionResultsModel vehicleInspectionResults) throws SQLException { final OrmDbHelper ormDbHelper = new OrmDbHelper(App.getContext()); try { final Dao<VehicleInspectionResultsModel, Integer> vehicleInspectionResultsDao = ormDbHelper.getVehicleInspectionResultsDao(); return (vehicleInspectionResultsDao.update(vehicleInspectionResults) > 0); } finally { ormDbHelper.close(); } } public static List<VehicleInspectionResultsModel> getVehicleInspectionResultsList(long bookingID) throws SQLException { final OrmDbHelper ormDbHelper = new OrmDbHelper(App.getContext()); try { final Dao<VehicleInspectionResultsModel, Integer> vehicleInspectionResultsDao = ormDbHelper.getVehicleInspectionResultsDao(); final List<VehicleInspectionResultsModel> vehicleInspectionResultsList = vehicleInspectionResultsDao.query(vehicleInspectionResultsDao.queryBuilder() .where() .eq(BOOKING_ID_COLUMN, bookingID).prepare()); return vehicleInspectionResultsList; }finally { ormDbHelper.close(); } } }
UTF-8
Java
4,526
java
VehicleInspectionResultsRepository.java
Java
[ { "context": " za.co.kapsch.shared.Utilities;\n\n/**\n * Created by CSenekal on 2018/01/22.\n */\n\npublic class VehicleInspectio", "end": 610, "score": 0.9947812557220459, "start": 602, "tag": "USERNAME", "value": "CSenekal" } ]
null
[]
package za.co.kapsch.ivehicletest.orm; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.j256.ormlite.dao.Dao; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.ErrorManager; import za.co.kapsch.ivehicletest.App; import za.co.kapsch.ivehicletest.Models.VehicleInspectionResultModel; import za.co.kapsch.ivehicletest.Models.VehicleInspectionResultsModel; import za.co.kapsch.shared.Enums.ErrorSeverity; import za.co.kapsch.shared.MessageManager; import za.co.kapsch.shared.Utilities; /** * Created by CSenekal on 2018/01/22. */ public class VehicleInspectionResultsRepository { public static final String UPLOADED_COLUMN = "Uploaded"; public static final String BOOKING_ID_COLUMN = "BookingID"; public static void createOrUpdate(VehicleInspectionResultsModel vehicleInspectionResults) throws SQLException { final OrmDbHelper ormDbHelper = new OrmDbHelper(App.getContext()); SQLiteDatabase db = ormDbHelper.getWritableDatabase(); try { db.beginTransaction(); final Dao<VehicleInspectionResultsModel, Integer> vehicleInspectionResultsDao = ormDbHelper.getVehicleInspectionResultsDao(); final Dao<VehicleInspectionResultModel, Integer> vehicleInspectionResultDao = ormDbHelper.getVehicleInspectionResultDao(); Dao.CreateOrUpdateStatus status = vehicleInspectionResultsDao.createOrUpdate(vehicleInspectionResults); for (VehicleInspectionResultModel vehicleInspectionResult : vehicleInspectionResults.getVehicleInspectionResultList()) { vehicleInspectionResult.setVehicleInspectionResultsID(vehicleInspectionResults.getID()); vehicleInspectionResultDao.createOrUpdate(vehicleInspectionResult); } db.setTransactionSuccessful(); }finally { db.endTransaction(); ormDbHelper.close(); } } public static List<VehicleInspectionResultsModel> getVehicleInspectionResultList() throws SQLException { final OrmDbHelper ormDbHelper = new OrmDbHelper(App.getContext()); try { final Dao<VehicleInspectionResultsModel, Integer> vehicleInspectionResultsDao = ormDbHelper.getVehicleInspectionResultsDao(); final List<VehicleInspectionResultsModel> vehicleInspectionResultsList = vehicleInspectionResultsDao.queryForAll(); return vehicleInspectionResultsList; } finally { ormDbHelper.close(); } } public static List<VehicleInspectionResultsModel> getUnSyncedVehicleInspectionResults() throws SQLException { final OrmDbHelper ormDbHelper = new OrmDbHelper(App.getContext()); try { final Dao<VehicleInspectionResultsModel, Integer> vehicleInspectionResultsDao = ormDbHelper.getVehicleInspectionResultsDao(); final List<VehicleInspectionResultsModel> vehicleInspectionResultsList = vehicleInspectionResultsDao.query(vehicleInspectionResultsDao.queryBuilder() .where() .eq(UPLOADED_COLUMN, false).prepare()); return vehicleInspectionResultsList; }finally { ormDbHelper.close(); } } public static boolean update(VehicleInspectionResultsModel vehicleInspectionResults) throws SQLException { final OrmDbHelper ormDbHelper = new OrmDbHelper(App.getContext()); try { final Dao<VehicleInspectionResultsModel, Integer> vehicleInspectionResultsDao = ormDbHelper.getVehicleInspectionResultsDao(); return (vehicleInspectionResultsDao.update(vehicleInspectionResults) > 0); } finally { ormDbHelper.close(); } } public static List<VehicleInspectionResultsModel> getVehicleInspectionResultsList(long bookingID) throws SQLException { final OrmDbHelper ormDbHelper = new OrmDbHelper(App.getContext()); try { final Dao<VehicleInspectionResultsModel, Integer> vehicleInspectionResultsDao = ormDbHelper.getVehicleInspectionResultsDao(); final List<VehicleInspectionResultsModel> vehicleInspectionResultsList = vehicleInspectionResultsDao.query(vehicleInspectionResultsDao.queryBuilder() .where() .eq(BOOKING_ID_COLUMN, bookingID).prepare()); return vehicleInspectionResultsList; }finally { ormDbHelper.close(); } } }
4,526
0.725365
0.722713
117
37.683762
44.410217
161
false
false
0
0
0
0
0
0
0.461538
false
false
9
b3732d0548ab5f4853cccb9d3418fc0a029ca096
9,251,359,568,241
f8277606f5f84e3d5a0e045e4379c9f7f5ba7d77
/rules-web/src/main/java/com/hstc/rules/domain/Testtitle.java
9c422bf7f3c729f7ee49a5a9c1ad2b8c947724c2
[ "Apache-2.0" ]
permissive
czbiao/rules
https://github.com/czbiao/rules
77ee768073f46a791d20ffe60cd29f467b065c03
b1bb5894eab65ac881a6671bd0db3d6ed165582e
refs/heads/master
2020-05-14T08:33:25.886000
2019-04-29T15:12:32
2019-04-29T15:12:32
181,724,597
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hstc.rules.domain; import javax.persistence.*; import java.io.Serializable; /** * Created by linjingshan on 2018-7-2. */ @Entity @Table(name = "testtitle", schema = "saverulessystem", catalog = "") @IdClass(TesttitlePK.class) public class Testtitle implements Serializable { @Id @Column(name = "student_id") private long studentId; @Id @Column(name = "test_id") private int testId; @Column(name = "title_ids") private String titleIds; @Column(name = "blank_ids") private String blankIds; @Column(name = "judge_ids") private String judgeIds; @Column(name = "short_ids") private String shortIds; @Column(name = "case_ids") private String caseIds; @Column(name = "discuss_ids") private String discussIds; public long getStudentId() { return studentId; } public void setStudentId(long studentId) { this.studentId = studentId; } public int getTestId() { return testId; } public void setTestId(int testId) { this.testId = testId; } public String getTitleIds() { return titleIds; } public void setTitleIds(String titleIds) { this.titleIds = titleIds; } public String getBlankIds() { return blankIds; } public void setBlankIds(String blankIds) { this.blankIds = blankIds; } public String getJudgeIds() { return judgeIds; } public void setJudgeIds(String judgeIds) { this.judgeIds = judgeIds; } public String getShortIds() { return shortIds; } public void setShortIds(String shortIds) { this.shortIds = shortIds; } public String getCaseIds() { return caseIds; } public void setCaseIds(String caseIds) { this.caseIds = caseIds; } public String getDiscussIds() { return discussIds; } public void setDiscussIds(String discussIds) { this.discussIds = discussIds; } }
UTF-8
Java
2,109
java
Testtitle.java
Java
[ { "context": "import java.io.Serializable;\r\n\r\n/**\r\n * Created by linjingshan on 2018-7-2.\r\n */\r\n@Entity\r\n@Table(name = \"testti", "end": 125, "score": 0.9994112253189087, "start": 114, "tag": "USERNAME", "value": "linjingshan" } ]
null
[]
package com.hstc.rules.domain; import javax.persistence.*; import java.io.Serializable; /** * Created by linjingshan on 2018-7-2. */ @Entity @Table(name = "testtitle", schema = "saverulessystem", catalog = "") @IdClass(TesttitlePK.class) public class Testtitle implements Serializable { @Id @Column(name = "student_id") private long studentId; @Id @Column(name = "test_id") private int testId; @Column(name = "title_ids") private String titleIds; @Column(name = "blank_ids") private String blankIds; @Column(name = "judge_ids") private String judgeIds; @Column(name = "short_ids") private String shortIds; @Column(name = "case_ids") private String caseIds; @Column(name = "discuss_ids") private String discussIds; public long getStudentId() { return studentId; } public void setStudentId(long studentId) { this.studentId = studentId; } public int getTestId() { return testId; } public void setTestId(int testId) { this.testId = testId; } public String getTitleIds() { return titleIds; } public void setTitleIds(String titleIds) { this.titleIds = titleIds; } public String getBlankIds() { return blankIds; } public void setBlankIds(String blankIds) { this.blankIds = blankIds; } public String getJudgeIds() { return judgeIds; } public void setJudgeIds(String judgeIds) { this.judgeIds = judgeIds; } public String getShortIds() { return shortIds; } public void setShortIds(String shortIds) { this.shortIds = shortIds; } public String getCaseIds() { return caseIds; } public void setCaseIds(String caseIds) { this.caseIds = caseIds; } public String getDiscussIds() { return discussIds; } public void setDiscussIds(String discussIds) { this.discussIds = discussIds; } }
2,109
0.59412
0.591276
95
20.200001
16.337622
68
false
false
0
0
0
0
0
0
0.305263
false
false
9
a26ce546adda2ea511d2cd4de274adb2952fbec7
4,148,938,420,299
ec081813413a0bdbd28c271c58d70d15443ab81b
/src/main/java/Algorithmn/leetcode/leetcode74.java
6cf3c7dad6536cd760b2c47782d7c58b153e6044
[]
no_license
qinzhewudao/LearnJavaProject
https://github.com/qinzhewudao/LearnJavaProject
7d6daff1050f33f12a76ee2edf7db865db035dea
b6054484cc138323aabc62fa93646e1d1dcde21f
refs/heads/master
2021-09-18T09:57:30.388000
2021-09-06T02:17:03
2021-09-06T02:17:03
193,211,737
1
2
null
false
2021-07-01T08:16:49
2019-06-22T08:42:19
2021-07-01T08:15:55
2021-07-01T08:15:52
321
0
2
2
Java
false
false
package Algorithmn.leetcode; /** * @author sheyang * @description * @date 2019/9/1 * @time 下午6:31 */ public class leetcode74 { public boolean searchMatrix(int[][] matrix, int target) { int col = matrix.length; if (col <= 0) { return false; } int row = matrix[0].length; if (row <= 0) { return false; } int i; for (i = 0; i < col; i++) { if (matrix[i][row - 1] > target) { break; } else if (matrix[i][row - 1] < target) { i++; } else { return true; } } if (i >= col) { return false; } for (int j = row - 1; j >= 0; ) { if (matrix[i][j] > target) { j--; } else { return matrix[i][j] >= target; } } return false; } public static void main(String[] args) { leetcode74 leetcode74 = new leetcode74(); System.out.println(leetcode74.searchMatrix(new int[][]{{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 50}}, 3)); } }
UTF-8
Java
1,167
java
leetcode74.java
Java
[ { "context": "package Algorithmn.leetcode;\n\n/**\n * @author sheyang\n * @description\n * @date 2019/9/1\n * @time 下午6:31", "end": 52, "score": 0.9924020171165466, "start": 45, "tag": "USERNAME", "value": "sheyang" } ]
null
[]
package Algorithmn.leetcode; /** * @author sheyang * @description * @date 2019/9/1 * @time 下午6:31 */ public class leetcode74 { public boolean searchMatrix(int[][] matrix, int target) { int col = matrix.length; if (col <= 0) { return false; } int row = matrix[0].length; if (row <= 0) { return false; } int i; for (i = 0; i < col; i++) { if (matrix[i][row - 1] > target) { break; } else if (matrix[i][row - 1] < target) { i++; } else { return true; } } if (i >= col) { return false; } for (int j = row - 1; j >= 0; ) { if (matrix[i][j] > target) { j--; } else { return matrix[i][j] >= target; } } return false; } public static void main(String[] args) { leetcode74 leetcode74 = new leetcode74(); System.out.println(leetcode74.searchMatrix(new int[][]{{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 50}}, 3)); } }
1,167
0.420464
0.379192
48
23.229166
20.477875
118
false
false
0
0
0
0
0
0
0.666667
false
false
9
e52a357788095de894b14987fa5ea1950f870b46
28,509,992,949,687
0f88411890976a2e120202b7f85071f66f718a71
/mingribook-master/ChapterThree/chapter6_to_end/src/chapter/five/UpAndLower.java
d9fb961d27d27eb1eac73ab88a8313dd2f813088
[]
no_license
little111cow/java_learn
https://github.com/little111cow/java_learn
c01bc94e981825a7d5277c0af04b8fef5b9a3289
d5c4d43b4280de1a3ea7ffd168fec5306c12d0c6
refs/heads/main
2023-08-17T12:21:29.424000
2021-10-04T09:07:40
2021-10-04T09:07:40
405,888,855
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package chapter.five; public class UpAndLower { public static void main(String[] args) { // TODO Auto-generated method stub String str = new String("abc DEF"); String newstr = str.toLowerCase(); String newstr2 = str.toUpperCase(); System.out.println(newstr); System.out.println(newstr2); } }
UTF-8
Java
309
java
UpAndLower.java
Java
[]
null
[]
package chapter.five; public class UpAndLower { public static void main(String[] args) { // TODO Auto-generated method stub String str = new String("abc DEF"); String newstr = str.toLowerCase(); String newstr2 = str.toUpperCase(); System.out.println(newstr); System.out.println(newstr2); } }
309
0.705502
0.699029
14
21.071428
16.051098
41
false
false
0
0
0
0
0
0
1.428571
false
false
4